repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
omniAwesome/tbag-tank | classes/cannon.lua | 2 | 6767 | -- Cannon
-- It consists of a tower and actual cannon. Cannon can rotate and shoot the cannon balls
local eachframe = require('libs.eachframe')
local relayout = require('libs.relayout')
local sounds = require('libs.sounds')
local _M = {}
local newBall = require('classes.ball').newBall
local newPuff = require('classes.puff').newPuff
function _M.newCannon(params)
local map = params.map
local level = params.level
-- Tower and cannon images are aligned to the level's grid, hence the mapX and mapY
local tower = display.newImageRect(map.group, 'images/tower.png', 192, 256)
tower.anchorY = 1
tower.x, tower.y = map:mapXYToPixels(level.cannon.mapX + 0.5, level.cannon.mapY + 1)
map.snapshot:invalidate()
local cannon = display.newImageRect(map.physicsGroup, 'images/cannon.png', 128, 64)
cannon.anchorX = 0.25
cannon.x, cannon.y = map:mapXYToPixels(level.cannon.mapX + 0.5, level.cannon.mapY - 3)
-- Cannon force is set by a player by moving the finger away from the cannon
cannon.force = 0
cannon.forceRadius = 0
-- Increments are for gamepad control
cannon.radiusIncrement = 0
cannon.rotationIncrement = 0
-- Minimum and maximum radius of the force circle indicator
local radiusMin, radiusMax = 64, 200
-- Indicates force value
local forceArea = display.newCircle(map.physicsGroup, cannon.x, cannon.y, radiusMax)
forceArea.strokeWidth = 4
forceArea:setFillColor(1, 0.5, 0.2, 0.2)
forceArea:setStrokeColor(1, 0.5, 0.2)
forceArea.isVisible = false
-- touchArea is larger than cannon image so player does not need to be very accurate with the fingers
local touchArea = display.newCircle(map.physicsGroup, cannon.x, cannon.y, 128)
touchArea.isVisible = false
touchArea.isHitTestable = true
touchArea:addEventListener('touch', cannon)
local trajectoryPoints = {} -- White dots along the flying path of a ball
local balls = {} -- Container for the ammo
function cannon:getAmmoCount()
return #balls + (self.ball and 1 or 0)
end
-- Create and stack all available cannon balls near the tower
function cannon:prepareAmmo()
local mapX, mapY = level.cannon.mapX - 1, level.cannon.mapY
for i = #level.ammo, 1, -1 do
local x, y = map:mapXYToPixels(mapX + 0.5, mapY + 0.5)
local ball = newBall({g = self.parent, type = level.ammo[i], x = x, y = y})
table.insert(balls, ball)
mapX = mapX - 1
if (#level.ammo - i + 1) % 3 == 0 then
mapX, mapY = level.cannon.mapX - 1, mapY - 1
end
end
end
-- Move next available cannon ball into the cannon
function cannon:load()
if #balls > 0 then
self.ball = table.remove(balls, #balls)
transition.to(self.ball, {time = 500, x = self.x, y = self.y, transition = easing.outExpo})
end
end
-- Launch loaded cannon ball
function cannon:fire()
if self.ball and not self.ball.isLaunched then
self.ball:launch(self.rotation, self.force)
self:removeTrajectoryPoints()
self.launchTime = system.getTimer() -- This time value is needed for the trajectory points
self.lastTrajectoryPointTime = self.launchTime
newPuff({g = self.parent, x = self.x, y = self.y, isExplosion = true}) -- Display an explosion visual effect
map:snapCameraTo(self.ball)
sounds.play('cannon')
end
end
function cannon:setForce(radius, rotation)
self.rotation = rotation % 360
if radius > radiusMin then
if radius > radiusMax then
radius = radiusMax
end
self.force = radius
else
self.force = 0
end
-- Only show the force indication if there is a loaded cannon ball
if self.ball and not self.ball.isLaunched then
forceArea.isVisible = true
forceArea.xScale = 2 * radius / forceArea.width
forceArea.yScale = forceArea.xScale
end
return math.min(radius, radiusMax), self.rotation
end
function cannon:engageForce()
forceArea.isVisible = false
self.forceRadius = 0
if self.force > 0 then
self:fire()
end
end
function cannon:touch(event)
if event.phase == 'began' then
display.getCurrentStage():setFocus(self, event.id)
self.isFocused = true
sounds.play('cannon_touch')
elseif self.isFocused then
if event.phase == 'moved' then
local x, y = self.parent:contentToLocal(event.x, event.y)
x, y = x - self.x, y - self.y
local rotation = math.atan2(y, x) * 180 / math.pi + 180
local radius = math.sqrt(x ^ 2 + y ^ 2)
self:setForce(radius, rotation)
else
display.getCurrentStage():setFocus(self, nil)
self.isFocused = false
self:engageForce()
end
end
return true
end
cannon:addEventListener('touch')
-- Add white trajectory points each time interval
function cannon:addTrajectoryPoint()
local now = system.getTimer()
-- Draw them for no longer than the first value and each second value millisecods
if now - self.launchTime < 1000 and now - self.lastTrajectoryPointTime > 85 then
self.lastTrajectoryPointTime = now
local point = display.newCircle(self.parent, self.ball.x, self.ball.y, 2)
table.insert(trajectoryPoints, point)
end
end
-- Clean the trajectory before drawing another one
function cannon:removeTrajectoryPoints()
for i = #trajectoryPoints, 1, -1 do
table.remove(trajectoryPoints, i):removeSelf()
end
end
-- echFrame() is like enterFrame(), but managed by a library
-- Track a launched ball until it stops and load another one
function cannon:eachFrame()
local step = 2
local damping = 0.99
if self.ball then
if self.ball.isLaunched then
local vx, vy = self.ball:getLinearVelocity()
if vx ^ 2 + vy ^ 2 < 4 or
self.ball.x < 0 or
self.ball.x > map.map.tilewidth * map.map.width or
self.ball.y > map.map.tilewidth * map.map.height then
self.ball:destroy()
self.ball = nil
self:load()
map:moveCameraSmoothly({x = self.x - relayout._CX, y = self.y - relayout._CY, time = 1000, delay = 500})
elseif not self.isPaused then
self:addTrajectoryPoint()
end
elseif self.radiusIncrement ~= 0 or self.rotationIncrement ~= 0 then
self.radiusIncrement = self.radiusIncrement * damping
if math.abs(self.radiusIncrement) < 0.02 then
self.radiusIncrement = 0
end
self.rotationIncrement = self.rotationIncrement * damping
if math.abs(self.rotationIncrement) < 0.02 then
self.rotationIncrement = 0
end
self.forceRadius = self.forceRadius + self.radiusIncrement * step
self.forceRadius = self:setForce(math.max(math.abs(self.forceRadius), 1), self.rotation + self.rotationIncrement * step)
end
end
end
eachframe.add(cannon)
-- finalize() is called by Corona when display object is destroyed
function cannon:finalize()
eachframe.remove(self)
end
cannon:addEventListener('finalize')
cannon:prepareAmmo()
cannon:load()
return cannon
end
return _M
| mit |
tysonliddell/OpenRA | mods/d2k/maps/harkonnen-05/harkonnen05-AI.lua | 4 | 2450 | --[[
Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
AttackGroupSize =
{
easy = 6,
normal = 8,
hard = 10
}
AttackDelays =
{
easy = { DateTime.Seconds(4), DateTime.Seconds(7) },
normal = { DateTime.Seconds(2), DateTime.Seconds(5) },
hard = { DateTime.Seconds(1), DateTime.Seconds(3) }
}
OrdosInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" }
OrdosVehicleTypes = { "raider", "raider", "quad" }
OrdosTankType = { "combat_tank_o" }
ActivateAI = function()
IdlingUnits[ordos_main] = Reinforcements.Reinforce(ordos_main, InitialOrdosReinforcements[1], InitialOrdosPaths[1]), Reinforcements.Reinforce(ordos_main, InitialOrdosReinforcements[2], InitialOrdosPaths[2])
IdlingUnits[ordos_small] = Reinforcements.Reinforce(ordos_small, InitialOrdosReinforcements[1], InitialOrdosPaths[3])
IdlingUnits[corrino] = { CSaraukar1, CSaraukar2, CSaraukar3, CSaraukar4, CSaraukar5 }
DefendAndRepairBase(ordos_main, OrdosMainBase, 0.75, AttackGroupSize[Difficulty])
DefendAndRepairBase(ordos_small, OrdosSmallBase, 0.75, AttackGroupSize[Difficulty])
DefendAndRepairBase(corrino, CorrinoBase, 0.75, AttackGroupSize[Difficulty])
local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end
local infantryToBuild = function() return { Utils.Random(OrdosInfantryTypes) } end
local vehilcesToBuild = function() return { Utils.Random(OrdosVehicleTypes) } end
local tanksToBuild = function() return OrdosTankType end
local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5
ProduceUnits(ordos_main, OBarracks1, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
ProduceUnits(ordos_main, OLightFactory1, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
ProduceUnits(ordos_main, OHeavyFactory, delay, tanksToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
ProduceUnits(ordos_small, OBarracks3, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
ProduceUnits(ordos_small, OLightFactory2, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
end
| gpl-3.0 |
DeinFreund/Zero-K | units/jumpbomb.lua | 1 | 3484 | unitDef = {
unitname = [[jumpbomb]],
name = [[Skuttle]],
description = [[Cloaked Jumping Anti-Heavy Bomb]],
acceleration = 0.18,
brakeRate = 0.54,
buildCostMetal = 550,
builder = false,
buildPic = [[jumpbomb.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
cloakCost = 5,
cloakCostMoving = 15,
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[20 20 20]],
collisionVolumeType = [[ellipsoid]],
selectionVolumeOffsets = [[0 0 0]],
selectionVolumeScales = [[28 28 28]],
selectionVolumeType = [[ellipsoid]],
corpse = [[DEAD]],
customParams = {
canjump = 1,
jump_range = 400,
jump_height = 120,
jump_speed = 6,
jump_reload = 10,
jump_from_midair = 0,
aimposoffset = [[0 2 0]],
midposoffset = [[0 2 0]],
modelradius = [[10]],
selection_scale = 1, -- Maybe change later
},
explodeAs = [[jumpbomb_DEATH]],
fireState = 0,
footprintX = 2,
footprintZ = 2,
iconType = [[jumpjetbomb]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
initCloaked = true,
kamikaze = true,
kamikazeDistance = 25,
kamikazeUseLOS = true,
maneuverleashlength = [[140]],
maxDamage = 250,
maxSlope = 36,
maxVelocity = 1.5225,
maxWaterDepth = 15,
minCloakDistance = 180,
movementClass = [[SKBOT2]],
noAutoFire = false,
noChaseCategory = [[FIXEDWING LAND SINK TURRET SHIP SATELLITE SWIM GUNSHIP FLOAT SUB HOVER]],
objectName = [[skuttle.s3o]],
selfDestructAs = [[jumpbomb_DEATH]],
selfDestructCountdown = 0,
script = [[jumpbomb.lua]],
sightDistance = 280,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ChickenTrackPointy]],
trackWidth = 34,
turnRate = 2000,
workerTime = 0,
featureDefs = {
DEAD = {
blocking = false,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[skuttle_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
--------------------------------------------------------------------------------
local weaponDefs = {
jumpbomb_DEATH = {
areaOfEffect = 180,
craterBoost = 4,
craterMult = 5,
edgeEffectiveness = 0.3,
explosionGenerator = "custom:NUKE_150",
explosionSpeed = 10000,
impulseBoost = 0,
impulseFactor = 0.1,
name = "Explosion",
soundHit = "explosion/mini_nuke",
customParams = {
lups_explodelife = 1.5,
},
damage = {
default = 8007.1,
},
},
}
unitDef.weaponDefs = weaponDefs
--------------------------------------------------------------------------------
return lowerkeys({ jumpbomb = unitDef })
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Temenos/mobs/Water_Elemental.lua | 16 | 1711 | -----------------------------------
-- Area: Temenos E T
-- NPC: Water_Elemental
-----------------------------------
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();
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
switch (mobID): caseof {
-- 100 a 106 inclut (Temenos -Northern Tower )
[16928885] = function (x)
GetNPCByID(16928768+277):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+277):setStatus(STATUS_NORMAL);
end ,
[16928886] = function (x)
GetNPCByID(16928768+190):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+190):setStatus(STATUS_NORMAL);
end ,
[16928887] = function (x)
GetNPCByID(16928768+127):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+127):setStatus(STATUS_NORMAL);
end ,
[16928888] = function (x)
GetNPCByID(16928768+69):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+69):setStatus(STATUS_NORMAL);
end ,
[16929038] = function (x)
if (IsMobDead(16929033)==false) then
DespawnMob(16929033);
SpawnMob(16929039);
end
end ,
}
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Lower_Delkfutts_Tower/npcs/Grounds_Tome.lua | 34 | 1149 | -----------------------------------
-- Area: Lower Delkfutt's Tower
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_LOWER_DELKFUTTS_TOWER,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,777,778,779,780,781,0,0,0,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,777,778,779,780,781,0,0,0,0,0,GOV_MSG_LOWER_DELKFUTTS_TOWER);
end;
| gpl-3.0 |
Al-Asaadi/llGHll | plugins/h2.lua | 1 | 1991 | do
function run(msg, matches)
return [[
🔹 أوامر الحماية داخل المجموعة 🔹
_________________
🔹طرد <معرف-رد> : طرد | ⛔️
🔹كتم <معرف-رد> : كتم | 🔕
🔹حظر <معرف-رد> : حظر | 🚷
🔹الغاء الحظر <معرف-رد> : الغاء الحظر | ⭕️
🔹قائمة الحظر : المحظورين | 🆘
🔹ايدي : ايدي | 🆔
🔹مغادرة : مغادرة | 🚫
_________________
🔹اوامر الفتح والقفل في المجموعة | ✂️
_________________
🔹قفل الصوتيات : لمنع الصوتيات | 🔊
🔹قفل المتحركة : لمنع المتحركة | 🎡
🔹قفل الملفات : لمنع الملفات | 🗂
🔹قفل الصور :لمنع الصور | 🌠
🔹قفل الكتابة :لمنع الكتابة | 📝
🔹قفل الفيديوهات : لمنع الفديوات | 🎥
🔹قفل التوجية : لمنع التوجيه | ↩️
🔹قفل التكرار : لمنع التكرار | 🔐
🔹قفل البوتات : لمنع البوتات | 🤖
🔹قفل الروابط : لمنع الروابط | 🔗
🔹قفل الاضافة : لمنع الاضافة | 👤
🔹قفل الاضافة الجماعية : لمنع الاضافة الجماعية | 🚸
🔹قفل اشعارات : اشعارات الدخول | ⚛
🔹قفل جهات اتصال : جهات الاتصال | 📵
🔹قفل التفليش : لمنع الكلايش الطويله | 📊
🔹قفل المحادثة : لمنع المحادثة | 🔕
🔹قفل العربيه : اللغة العربية | 🆎
🔹قفل التحذير : الحماية | ⛔️
_________________
🔹طريقة استخدام الاوامر 🔹
🔹 قفل + الامر - للقفل
🔹 فتح + الامر - للفتح
_________________
🔹channel : @llYAll
]]
end
return {
patterns = {
"^h2"
},
run = run
}
end | gpl-2.0 |
hiddenvirus/hiddenblaster | bot/bot.lua | 2 | 7095 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '0.14.6'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
if plugins[disabled_plugin].hidden then
print('Plugin '..disabled_plugin..' is disabled on this chat')
else
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
end
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"banhammer",
"echo",
"get",
"google",
"groupmanager",
"help",
"id",
"images",
"img_google",
"location",
"media",
"plugins",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"youtube",
"media_handler",
"moderation"},
sudo_users = {101860317},
disabled_channels = {},
moderation = {data = 'data/moderation.json'}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
DaTaK-BoT/DaTaK | 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-2.0 |
codelua/TabliqGar | 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 |
DeinFreund/Zero-K | LuaRules/Configs/icon_generator.lua | 5 | 10219 | -- $Id: icon_generator.lua 4354 2009-04-11 14:32:28Z licho $
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--
-- Icon Generator Config File
--
--// Info
if (info) then
local ratios = {["5to4"]=(4/5)} --{["16to10"]=(10/16), ["1to1"]=(1/1), ["5to4"]=(4/5)} --, ["4to3"]=(3/4)}
local resolutions = {{64,64}} --{{128,128},{64,64}}
local schemes = {""}
return schemes,resolutions,ratios
end
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--// filename ext
imageExt = ".png"
--// render into a fbo in 4x size
renderScale = 4
--// faction colors (check (and needs) LuaRules/factions.lua)
factionTeams = {
arm = 0, --// arm
core = 1, --// core
chicken = 2, --// chicken
unknown = 2, --// unknown
}
factionColors = {
arm = {0.05, 0.96, 0.95}, --// arm
core = {0.05, 0.96, 0.95}, --// core
chicken = {1.0,0.8,0.2}, --// chicken
unknown = {0.05, 0.96, 0.95}, --// unknown
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--// render options textured
textured = (scheme~="bw")
lightAmbient = {1.1,1.1,1.1}
lightDiffuse = {0.4,0.4,0.4}
lightPos = {-0.2,0.4,0.5}
--// Ambient Occlusion & Outline settings
aoPower = ((scheme=="bw") and 1.5) or 1
aoContrast = ((scheme=="bw") and 2.5) or 1
aoTolerance = 0
olContrast = ((scheme=="bw") and 5) or 10
olTolerance = 0
--// halo (white)
halo = false --(scheme~="bw")
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--// backgrounds
background = true
local function Greater30(a) return a>30; end
local function GreaterEq15(a) return a>=15; end
local function GreaterZero(a) return a>0; end
local function GreaterEqZero(a) return a>=0; end
local function GreaterFour(a) return a>4; end
local function LessEqZero(a) return a<=0; end
local function IsCoreOrChicken(a)
if a then return a.chicken
else return false end
end
local function IsHover(a)
return a and a.name and string.find(a.name, "hover") ~= nil
end
backgrounds = {
--// stuff that needs hardcoding
{check={name="shipcarrier"}, texture="LuaRules/Images/IconGenBkgs/bg_water.png"},
--[[terraforms
{check={name="rampup"}, texture="LuaRules/Images/IconGenBkgs/rampup.png"},
{check={name="rampdown"}, texture="LuaRules/Images/IconGenBkgs/rampdown.png"},
{check={name="levelterra"}, texture="LuaRules/Images/IconGenBkgs/level.png"},
{check={name="armblock"}, texture="LuaRules/Images/IconGenBkgs/block.png"},
{check={name="corblock"}, texture="LuaRules/Images/IconGenBkgs/block.png"},
{check={name="armtrench"}, texture="LuaRules/Images/IconGenBkgs/trench.png"},
{check={name="cortrench"}, texture="LuaRules/Images/IconGenBkgs/trench.png"},
]]--
--//air
{check={canFly=true}, texture="LuaRules/Images/IconGenBkgs/bg_air.png"},
--//hovers
{check={factions=IsCoreOrChicken,moveDef=IsHover}, texture="LuaRules/Images/IconGenBkgs/bg_hover_rock.png"},
{check={moveDef=IsHover}, texture="LuaRules/Images/IconGenBkgs/bg_hover.png"},
--//subs
{check={waterline=GreaterEq15,minWaterDepth=GreaterZero}, texture="LuaRules/Images/IconGenBkgs/bg_underwater.png"},
{check={floatOnWater=false,minWaterDepth=GreaterFour}, texture="LuaRules/Images/IconGenBkgs/bg_underwater.png"},
--//sea
{check={floatOnWater=true,minWaterDepth=GreaterZero}, texture="LuaRules/Images/IconGenBkgs/bg_water.png"},
--//amphibous
{check={factions=IsCoreOrChicken,maxWaterDepth=Greater30,minWaterDepth=LessEqZero}, texture="LuaRules/Images/IconGenBkgs/bg_amphibous_rock.png"},
{check={maxWaterDepth=Greater30,minWaterDepth=LessEqZero}, texture="LuaRules/Images/IconGenBkgs/bg_amphibous.png"},
--//ground
{check={factions=IsCoreOrChicken}, texture="LuaRules/Images/IconGenBkgs/bg_ground_rock.png"},
{check={}, texture="LuaRules/Images/IconGenBkgs/bg_ground.png"},
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--// default settings for rendering
--//zoom := used to make all model icons same in size (DON'T USE, it is just for auto-configuration!)
--//offset := used to center the model in the fbo (not in the final icon!) (DON'T USE, it is just for auto-configuration!)
--//rot := facing direction
--//angle := topdown angle of the camera (0 degree = frontal, 90 degree = topdown)
--//clamp := clip everything beneath it (hide underground stuff)
--//scale := render the model x times as large and then scale down, to replaces missing AA support of FBOs (and fix rendering of very tine structures like antennas etc.))
--//unfold := unit needs cob to unfolds
--//move := send moving cob events (works only with unfold)
--//attack := send attack cob events (works only with unfold)
--//shotangle := vertical aiming, useful for arties etc. (works only with unfold+attack)
--//wait := wait that time in gameframes before taking the screenshot (default 300) (works only with unfold)
--//border := free space around the final icon (in percent/100)
--//empty := empty model (used for fake units in CA)
--//attempts := number of tries to scale the model to fit in the icon
defaults = {border=0.05, angle=45, rot="right", clamp=-10000, scale=1.5, empty=false, attempts=10, wait=120, zoom=1.0, offset={0,0,0},};
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--// per unitdef settings
unitConfigs = {
[UnitDefNames.staticradar.id] = {
scale = 3,
rot = 200,
clamp = 10,
},
[UnitDefNames.staticjammer.id] = {
rot = -45,
},
[UnitDefNames.staticnuke.id] = {
clamp = 0,
},
[UnitDefNames.hoverraid.id] = {
clamp = 0,
},
[UnitDefNames.turretmissile.id] = {
clamp = 2,
},
[UnitDefNames.turretheavylaser.id] = {
clamp = 2,
},
[UnitDefNames.vehscout.id] = {
border = 0.156,
},
[UnitDefNames.gunshipbomb.id] = {
border = 0.156,
},
[UnitDefNames.gunshipemp.id] = {
border = 0.125,
},
[UnitDefNames.vehraid.id] = {
border = 0.125,
},
[UnitDefNames.spiderscout.id] = {
border = 0.125,
},
[UnitDefNames.jumpsumo.id] = {
unfold = true,
},
[UnitDefNames.jumpraid.id] = {
unfold = true,
},
[UnitDefNames.shieldskirm.id] = {
unfold = true,
},
[UnitDefNames.shieldshield.id] = {
unfold = true,
},
[UnitDefNames.staticshield.id] = {
unfold = true,
},
[UnitDefNames.tankarty.id] = {
unfold = true,
attack = true,
shotangle = 45,
wait = 120,
},
[UnitDefNames.shieldraid.id] = {
unfold = true,
attack = true,
wait = 120,
},
[UnitDefNames.turretgauss.id] = {
unfold = true,
attack = true,
wait = 50,
},
[UnitDefNames.spiderantiheavy.id] = {
unfold = true,
},
[UnitDefNames.turretantiheavy.id] = {
unfold = true,
},
[UnitDefNames.staticheavyradar.id] = {
unfold = true,
wait = 225,
},
[UnitDefNames.energysolar.id] = {
unfold = true,
},
[UnitDefNames.cloaksnipe.id] = {
-- unfold = true,
-- attack = true,
},
[UnitDefNames.cloakassault.id] = {
unfold = true,
attack = true,
},
[UnitDefNames.hoverdepthcharge.id] = {
unfold = true,
},
[UnitDefNames.cloakjammer.id] = {
unfold = true,
wait = 100,
},
[UnitDefNames.staticmex.id] = {
clamp = 0,
unfold = true,
wait = 600,
},
[UnitDefNames.turretheavy.id] = {
unfold = true,
},
[UnitDefNames.gunshipkrow.id] = {
unfold = true,
},
[UnitDefNames.chickenf.id] = {
unfold = true,
wait = 190,
},
[UnitDefNames.chicken_pigeon.id] = {
border = 0.11,
},
[UnitDefNames.chicken_dodo.id] = {
border = defaults.border,
},
[UnitDefNames.chickenbroodqueen.id] = {
rot = 29,
angle = 10,
unfold = false,
},
[UnitDefNames.striderdetriment.id] = {
rot = 20,
angle = 10,
},
[UnitDefNames.striderbantha.id] = {
rot = 28,
angle = 10,
unfold = true,
},
[UnitDefNames.striderdante.id] = {
rot = 28,
angle = 10,
},
[UnitDefNames.nebula.id] = {
rot = 28,
angle = 10,
},
[UnitDefNames.turretaaheavy.id] = {
rot = 30,
angle = 30,
},
[UnitDefNames.spiderassault.id] = {
unfold = true,
},
[UnitDefNames.amphlaunch.id] = {
unfold = true,
},
[UnitDefNames.spidercon.id] = {
scale = 3,
attempts = 10,
},
[UnitDefNames.commrecon1.id] = {
unfold = true,
--attack = true,
},
[UnitDefNames.commsupport1.id] = {
unfold = true,
--attack = true,
},
[UnitDefNames.zenith.id] = {
wait = 50,
},
[UnitDefNames.fakeunit.id] = {
empty = true,
},
[UnitDefNames.fakeunit_aatarget.id] = {
empty = true,
},
[UnitDefNames.fakeunit_los.id] = {
empty = true,
},
[UnitDefNames.wolverine_mine.id] = {
unfold = true,
wait = 60,
},
[UnitDefNames.hovercon.id] = {
unfold = true,
wait = 60,
},
}
for i=1,#UnitDefs do
if (UnitDefs[i].canFly) then
if (unitConfigs[i]) then
if (unitConfigs[i].unfold ~= false) then
unitConfigs[i].unfold = true
unitConfigs[i].move = true
end
else
unitConfigs[i] = {unfold = true, move = true}
end
elseif (UnitDefs[i].canKamikaze) then
if (unitConfigs[i]) then
if (not unitConfigs[i].border) then
unitConfigs[i].border = 0.156
end
else
unitConfigs[i] = {border = 0.156}
end
end
end
| gpl-2.0 |
u20024804/fbcunn | test/test_WeightedLookupTable.lua | 8 | 2146 | -- Copyright 2004-present Facebook. All Rights Reserved.
require('fbtorch')
require('fb.luaunit')
require('fbcunn')
require('nn')
local function all(tensor)
return torch.sum(torch.ne(tensor, 0)) == tensor:numel()
end
local function almost_equal(t1, t2, tol)
return torch.lt(torch.abs(t1 - t2), tol)
end
-- w = weighted
-- u = unweighted
-- e.g.
-- wlut = weighted lookup table
-- ulut = unweighted lookup table
function test_WeightedLookupTable_forward()
local embedding_dim = 4
local table_size = 30
local input_length = 9
local tol = 1e-8
local wlut = nn.WeightedLookupTable(table_size, embedding_dim)
local ulut = nn.LookupTable(table_size, embedding_dim)
ulut.weight:copy(wlut.weight)
assert(all(torch.eq(wlut.weight, ulut.weight)))
local uinput = torch.rand(input_length):mul(table_size):ceil()
local weights = torch.rand(input_length, 1)
local winput = torch.cat(uinput, weights, 2)
local woutput = wlut:forward(winput)
local uoutput = ulut:forward(uinput)
local expected_woutput = torch.cmul(uoutput, weights:expandAs(uoutput))
assert(all(almost_equal(woutput, expected_woutput, tol)))
end
function test_WeightedLookupTable_accGradParameters()
local embedding_dim = 4
local table_size = 30
local input_length = 9
local tol = 1e-8
local wlut = nn.WeightedLookupTable(table_size, embedding_dim)
local ulut = nn.LookupTable(table_size, embedding_dim)
ulut.weight:copy(wlut.weight)
assert(all(torch.eq(wlut.weight, ulut.weight)))
local uinput = torch.rand(input_length):mul(table_size):ceil()
local weights = torch.range(1, input_length):reshape(input_length, 1)
local winput = torch.cat(uinput, weights, 2)
local woutput = wlut:forward(winput)
local uoutput = ulut:forward(uinput)
local wgradOutput = torch.randn(woutput:size())
local ugradOutput = torch.cmul(wgradOutput, weights:expandAs(wgradOutput))
wlut:accGradParameters(winput, wgradOutput, 1)
ulut:accGradParameters(uinput, ugradOutput, 1)
assert(all(almost_equal(wlut.gradWeight, ulut.gradWeight, tol)))
end
LuaUnit:main()
| bsd-3-clause |
Jmainguy/docker_images | prosody/prosody/share/lua/5.1/luarocks/pack.lua | 20 | 7450 |
--- Module implementing the LuaRocks "pack" command.
-- Creates a rock, packing sources or binaries.
--module("luarocks.pack", package.seeall)
local pack = {}
package.loaded["luarocks.pack"] = pack
local unpack = unpack or table.unpack
local path = require("luarocks.path")
local repos = require("luarocks.repos")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local search = require("luarocks.search")
pack.help_summary = "Create a rock, packing sources or binaries."
pack.help_arguments = "{<rockspec>|<name> [<version>]}"
pack.help = [[
Argument may be a rockspec file, for creating a source rock,
or the name of an installed package, for creating a binary rock.
In the latter case, the app version may be given as a second
argument.
]]
--- Create a source rock.
-- Packages a rockspec and its required source files in a rock
-- file with the .src.rock extension, which can later be built and
-- installed with the "build" command.
-- @param rockspec_file string: An URL or pathname for a rockspec file.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
function pack.pack_source_rock(rockspec_file)
assert(type(rockspec_file) == "string")
local rockspec, err = fetch.load_rockspec(rockspec_file)
if err then
return nil, "Error loading rockspec: "..err
end
rockspec_file = rockspec.local_filename
local name_version = rockspec.name .. "-" .. rockspec.version
local rock_file = fs.absolute_name(name_version .. ".src.rock")
local source_file, source_dir = fetch.fetch_sources(rockspec, false)
if not source_file then
return nil, source_dir
end
local ok, err = fs.change_dir(source_dir)
if not ok then return nil, err end
fs.delete(rock_file)
fs.copy(rockspec_file, source_dir)
if not fs.zip(rock_file, dir.base_name(rockspec_file), dir.base_name(source_file)) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
return rock_file
end
local function copy_back_files(name, version, file_tree, deploy_dir, pack_dir)
local ok, err = fs.make_dir(pack_dir)
if not ok then return nil, err end
for file, sub in pairs(file_tree) do
local source = dir.path(deploy_dir, file)
local target = dir.path(pack_dir, file)
if type(sub) == "table" then
local ok, err = copy_back_files(name, version, sub, source, target)
if not ok then return nil, err end
else
local versioned = path.versioned_name(source, deploy_dir, name, version)
if fs.exists(versioned) then
fs.copy(versioned, target)
else
fs.copy(source, target)
end
end
end
return true
end
-- @param name string: Name of package to pack.
-- @param version string or nil: A version number may also be passed.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
local function do_pack_binary_rock(name, version)
assert(type(name) == "string")
assert(type(version) == "string" or not version)
local query = search.make_query(name, version)
query.exact_name = true
local results = {}
search.manifest_search(results, cfg.rocks_dir, query)
if not next(results) then
return nil, "'"..name.."' does not seem to be an installed rock."
end
local versions = results[name]
if not version then
local first = next(versions)
if next(versions, first) then
return nil, "Please specify which version of '"..name.."' to pack."
end
version = first
end
if not version:match("[^-]+%-%d+") then
return nil, "Expected version "..version.." in version-revision format."
end
local info = versions[version][1]
local root = path.root_dir(info.repo)
local prefix = path.install_dir(name, version, root)
if not fs.exists(prefix) then
return nil, "'"..name.." "..version.."' does not seem to be an installed rock."
end
local rock_manifest = manif.load_rock_manifest(name, version, root)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
local name_version = name .. "-" .. version
local rock_file = fs.absolute_name(name_version .. "."..cfg.arch..".rock")
local temp_dir = fs.make_temp_dir("pack")
fs.copy_contents(prefix, temp_dir)
local is_binary = false
if rock_manifest.lib then
local ok, err = copy_back_files(name, version, rock_manifest.lib, path.deploy_lib_dir(root), dir.path(temp_dir, "lib"))
if not ok then return nil, "Failed copying back files: " .. err end
is_binary = true
end
if rock_manifest.lua then
local ok, err = copy_back_files(name, version, rock_manifest.lua, path.deploy_lua_dir(root), dir.path(temp_dir, "lua"))
if not ok then return nil, "Failed copying back files: " .. err end
end
local ok, err = fs.change_dir(temp_dir)
if not ok then return nil, err end
if not is_binary and not repos.has_binaries(name, version) then
rock_file = rock_file:gsub("%."..cfg.arch:gsub("%-","%%-").."%.", ".all.")
end
fs.delete(rock_file)
if not fs.zip(rock_file, unpack(fs.list_dir())) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
fs.delete(temp_dir)
return rock_file
end
function pack.pack_binary_rock(name, version, cmd, ...)
-- The --pack-binary-rock option for "luarocks build" basically performs
-- "luarocks build" on a temporary tree and then "luarocks pack". The
-- alternative would require refactoring parts of luarocks.build and
-- luarocks.pack, which would save a few file operations: the idea would be
-- to shave off the final deploy steps from the build phase and the initial
-- collect steps from the pack phase.
local temp_dir, err = fs.make_temp_dir("luarocks-build-pack-"..dir.base_name(name))
if not temp_dir then
return nil, "Failed creating temporary directory: "..err
end
util.schedule_function(fs.delete, temp_dir)
path.use_tree(temp_dir)
local ok, err = cmd(...)
if not ok then
return nil, err
end
local rname, rversion = path.parse_name(name)
if not rname then
rname, rversion = name, version
end
return do_pack_binary_rock(rname, rversion)
end
--- Driver function for the "pack" command.
-- @param arg string: may be a rockspec file, for creating a source rock,
-- or the name of an installed package, for creating a binary rock.
-- @param version string or nil: if the name of a package is given, a
-- version may also be passed.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
function pack.run(...)
local flags, arg, version = util.parse_flags(...)
assert(type(version) == "string" or not version)
if type(arg) ~= "string" then
return nil, "Argument missing. "..util.see_help("pack")
end
local file, err
if arg:match(".*%.rockspec") then
file, err = pack.pack_source_rock(arg)
else
file, err = do_pack_binary_rock(arg, version)
end
if err then
return nil, err
else
util.printout("Packed: "..file)
return true
end
end
return pack
| gpl-2.0 |
three2one/Atlas | examples/tutorial-union.lua | 40 | 1614 | --[[ $%BEGINLICENSE%$
Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
res = { }
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then return end
local q = packet:sub(2)
res = { }
if q:sub(1, 6):upper() == "SELECT" then
proxy.queries:append(1, packet, { resultset_is_needed = true })
proxy.queries:append(2, packet, { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
end
end
function read_query_result(inj)
for row in inj.resultset.rows do
res[#res + 1] = row
end
if inj.id ~= 2 then
return proxy.PROXY_IGNORE_RESULT
end
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
rows = res
}
}
local fields = {}
for n = 1, #inj.resultset.fields do
fields[#fields + 1] = {
type = inj.resultset.fields[n].type,
name = inj.resultset.fields[n].name,
}
end
proxy.response.resultset.fields = fields
return proxy.PROXY_SEND_RESULT
end
| gpl-2.0 |
AresTao/darkstar | scripts/globals/items/ulbukan_lobster.lua | 18 | 1342 | -----------------------------------------
-- ID: 5960
-- Item: Ulbukan Lobster
-- Food Effect: 5 Min, Mithra only
-----------------------------------------
-- Dexterity -3
-- Vitality 1
-- Defense +9%
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5960);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -3);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_DEFP, 9);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -3);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_DEFP, 9);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Castle_Oztroja/npcs/_m70.lua | 19 | 1199 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _m70 (Torch Stand)
-- Involved in Mission: Magicite
-- @pos -97.134 24.250 -105.979 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Castle_Oztroja/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(YAGUDO_TORCH)) then
player:startEvent(0x000b);
else
player:messageSpecial(PROBABLY_WORKS_WITH_SOMETHING_ELSE);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Monastic_Cavern/npcs/Altar.lua | 27 | 1815 | -----------------------------------
-- Area: Monastic Cavern
-- NPC: Altar
-- Involved in Quests: The Circle of Time
-- @pos 109 -3 -145 150
-----------------------------------
package.loaded["scripts/zones/Monastic_Cavern/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Monastic_Cavern/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME);
if (circleOfTime == QUEST_ACCEPTED and player:getVar("circleTime") >= 7) then
if (player:hasKeyItem(STAR_RING1) and player:hasKeyItem(MOON_RING)) then
if (player:getVar("circleTime") == 7) then
SpawnMob(17391804,180):updateClaim(player); -- Spawn bugaboo
elseif (player:getVar("circleTime") == 8) then
player:startEvent(0x03); -- Show final CS
end
end
else
player:messageSpecial(ALTAR)
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 == 0x03) then
player:setVar("circleTime",9); -- After bugaboo is killed, and final CS shows up
player:delKeyItem(MOON_RING);
player:delKeyItem(STAR_RING1);
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Hadayah.lua | 24 | 1799 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Hadayah
-- Type: Alchemy Image Support
-- @pos -10.470 -6.25 -141.700 241
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,1);
local SkillLevel = player:getSkillLevel(SKILL_ALCHEMY);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then
player:startEvent(0x027E,4,SkillLevel,1,511,187,0,7,2184);
else
player:startEvent(0x027E,4,SkillLevel,1,511,5662,6955,7,2184);
end
else
player:startEvent(0x027E,0,0,0,0,0,0,7,0); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x027E and option == 1) then
player:messageSpecial(ALCHEMY_SUPPORT,0,7,1);
player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
hiddenvirus/hiddenblaster | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
AresTao/darkstar | scripts/globals/abilities/building_flourish.lua | 28 | 2817 | -----------------------------------
-- Ability: Building Flourish
-- Enhances potency of your next weapon skill. Requires at least one Finishing Move.
-- Obtained: Dancer Level 50
-- Finishing Moves Used: 1-3
-- Recast Time: 00:10
-- Duration: 01:00
--
-- Using one Finishing Move boosts the Accuracy of your next weapon skill.
-- Using two Finishing Moves boosts both the Accuracy and Attack of your next weapon skill.
-- Using three Finishing Moves boosts the Accuracy, Attack and Critical Hit Rate of your next weapon skill.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
return 0,0;
else
return MSGBASIC_NO_FINISHINGMOVES,0;
end;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_1);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,1,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_2);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,2,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_3);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_4);
player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_5);
player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
end;
end; | gpl-3.0 |
thess/OpenWrt-luci | applications/luci-app-statistics/luasrc/statistics/i18n.lua | 39 | 1879 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.i18n", package.seeall)
require("luci.util")
require("luci.i18n")
Instance = luci.util.class()
function Instance.__init__( self, graph )
self.i18n = luci.i18n
self.graph = graph
end
function Instance._subst( self, str, val )
str = str:gsub( "%%H", self.graph.opts.host or "" )
str = str:gsub( "%%pn", val.plugin or "" )
str = str:gsub( "%%pi", val.pinst or "" )
str = str:gsub( "%%dt", val.dtype or "" )
str = str:gsub( "%%di", val.dinst or "" )
str = str:gsub( "%%ds", val.dsrc or "" )
return str
end
function Instance.title( self, plugin, pinst, dtype, dinst, user_title )
local title = user_title or
"p=%s/pi=%s/dt=%s/di=%s" % {
plugin,
(pinst and #pinst > 0) and pinst or "(nil)",
(dtype and #dtype > 0) and dtype or "(nil)",
(dinst and #dinst > 0) and dinst or "(nil)"
}
return self:_subst( title, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.label( self, plugin, pinst, dtype, dinst, user_label )
local label = user_label or
"dt=%s/di=%s" % {
(dtype and #dtype > 0) and dtype or "(nil)",
(dinst and #dinst > 0) and dinst or "(nil)"
}
return self:_subst( label, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.ds( self, source )
local label = source.title or
"dt=%s/di=%s/ds=%s" % {
(source.type and #source.type > 0) and source.type or "(nil)",
(source.instance and #source.instance > 0) and source.instance or "(nil)",
(source.ds and #source.ds > 0) and source.ds or "(nil)"
}
return self:_subst( label, {
dtype = source.type,
dinst = source.instance,
dsrc = source.ds
} ):gsub(":", "\\:")
end
| apache-2.0 |
gsage/engine | Tests/resources/specs/eal_spec.lua | 1 | 6743 | local eal = require 'lib.eal.manager'
-- registering test system assembly
local function decorator(cls)
-- also setup configure and destroy chains
cls.onCreate(function(self)
self.calledOnCreate = true
end, 100)
-- also setup configure and destroy chains
cls.onDestroy(function(self)
self.calledOnDestroy = true
end, 100)
function cls:ping()
return self.test.prop
end
return cls
end
-- registering test system assembly
local function stronglyDefinedDecorator(cls)
function cls:ok()
return true
end
return cls
end
-- dummy class extension
local function dummyDecorator(cls)
function cls:isDummy()
return true
end
return cls
end
-- burple class extension
local function burpleDecorator(cls)
function cls:isBurple()
return true
end
return cls
end
eal:extend({system="test"}, decorator)
eal:extend({system="test", type="testSystem"}, stronglyDefinedDecorator)
eal:extend({class={name="dummy"}}, dummyDecorator)
eal:extend({class={name="burple", requires={system="test"}}}, burpleDecorator)
local function firstMixinDecorator(cls)
cls.onCreate(function(self)
self.firstCreate = true
end)
cls.onDestroy(function(self)
self.firstDestroy = true
end)
function cls:firstMixinAdded()
return true
end
return cls
end
local function secondMixinDecorator(cls)
cls.onCreate(function(self)
self.sequenceValid = self.firstCreate == true
end)
cls.onDestroy(function(self)
self.sequenceValid = self.firstDestroy == true
end)
function cls:checkSequence()
return self.sequenceValid
end
return cls
end
eal:extend({mixin="second"}, secondMixinDecorator)
eal:extend({mixin="first"}, firstMixinDecorator)
describe("test engine abstraction layer #eal", function()
setup(function()
game:reset()
end)
teardown(function()
game:reset()
end)
it("reset should invalidate all eal entities", function()
local e = data:createEntity({
id = "abcd",
test = {
prop = "pong"
}
})
local wrapper = eal:getEntity(e.id)
game:reset()
assert.is_nil(wrapper.entity)
assert.truthy(wrapper.calledOnDestroy)
assert.equals(#eal.entities, 0)
assert.is_nil(eal.entities[e.id])
-- create the entity with the same id
local e = data:createEntity({
id = "abcd",
test = {
prop = "pong"
}
})
assert.equals(wrapper:ping(), "pong")
-- ensure that cache was cleared
local wrapper = eal:getEntity(e.id)
assert.is_not.is_nil(wrapper.entity)
assert.truthy(wrapper.calledOnCreate)
assert.equals(wrapper:ping(), "pong")
end)
describe("mixins", function()
local composition = data:createEntity({
vars = {
mixins = {"first", "second"},
},
test = {
prop = "ok"
},
stats = {
}
})
it("simple case works", function()
local wrapper = eal:getEntity(composition.id)
assert.truthy(wrapper:firstMixinAdded())
assert.truthy(wrapper:checkSequence())
end)
end)
describe("assemble entity", function()
it("check test system", function()
local entity = data:createEntity({
test = {
prop = "pong"
}
})
assert.equals(type(entity), "userdata")
local wrapper = eal:getEntity(entity.id)
assert.is_not.equals(wrapper.ping, nil)
assert.equals(wrapper:ping(), "pong")
assert.truthy(wrapper.calledOnCreate)
assert.truthy(core:removeEntity(entity.id))
assert.truthy(wrapper.calledOnDestroy)
-- entity was removed, so the wrapper should be invalid now
-- should raise errors, but no app crash expected
assert.has.errors(function() wrapper:ping() end)
end)
it("should cache assembled entity", function()
local entity = data:createEntity({
test = {
prop = "pongpong"
}
})
local s = spy.on(eal, "assemble")
local wrapper = eal:getEntity(entity.id)
assert.spy(s).was.not_called()
end)
it("should reuse assembled class", function()
local s = spy.on(eal, "assemble")
local entity = data:createEntity({
test = {
prop = "pongpong"
}
})
assert.spy(s).was.called(1)
s = spy.on(eal, "assembleNew")
assert.equals(type(entity), "userdata")
local wrapper = eal:getEntity(entity.id)
assert.is_not.equals(wrapper.ping, nil)
assert.spy(s).was.not_called()
assert.equals(wrapper:ping(), "pongpong")
end)
it("should return nil for not existing entity", function()
local wrapper = eal:getEntity("no one here")
assert.is_nil(wrapper)
end)
it("should also have strongly defined extension", function()
local s = spy.on(eal, "getEntity")
local entity = data:createEntity({
test = {
prop = "ok"
}
})
assert.spy(s).was.called(1)
local wrapper = eal:getEntity(entity.id)
assert.truthy(wrapper:ok())
end)
local dummy = data:createEntity({
vars = {
class = "dummy"
}
})
it("should extend class", function()
local wrapper = eal:getEntity(dummy.id)
assert.is_not.is_nil(wrapper.isDummy, "dummy class was not extended")
assert.truthy(wrapper:isDummy())
end)
local dummyPlus = data:createEntity({
vars = {
class = "dummy",
},
test = {
prop = "ok"
}
})
it("should extend both by class and systems decorators", function()
local wrapper = eal:getEntity(dummyPlus.id)
assert.is_not.is_nil(wrapper.ping, "dummy class did not get system decorators")
assert.is_not.is_nil(wrapper.isDummy, "dummy class was not extended")
assert.truthy(wrapper:isDummy())
end)
local burple = data:createEntity({
vars = {
class = "burple",
},
test = {
prop = "ok"
},
stats = {
}
})
it("should assemble class with the system dependency", function()
local wrapper = eal:getEntity(burple.id)
assert.is_not.is_nil(wrapper.ping, "system extension did not work")
assert.is_not.is_nil(wrapper.isBurple, "class extension did not work")
assert.truthy(wrapper:isBurple(), "class extension did not work")
end)
-- required system not defined, so it should not be defined
local noBurple = data:createEntity({
vars = {
class = "burple"
}
})
it("should consider class system requirements", function()
local wrapper = eal:getEntity(noBurple.id)
assert.is_nil(wrapper.ping, "requirements were ignored (system)")
assert.is_nil(wrapper.isBurple, "requirements were ignored (class)")
end)
end)
end)
| mit |
gsage/engine | resources/scripts/imgui/tools.lua | 1 | 1684 | require 'lib.class'
require 'imgui.base'
local icons = require 'imgui.icons'
local lm = require 'lib.locales'
local cm = require 'lib.context'
-- editor tools
ToolsView = class(ImguiWindow, function(self, open, positioner)
ImguiWindow.init(self, "tools", false, open)
self.icon = icons.dehaze
self.flags = ImGuiWindowFlags_NoScrollWithMouse + ImGuiWindowFlags_NoScrollbar + ImGuiWindowFlags_NoTitleBar + ImGuiWindowFlags_NoResize + ImGuiWindowFlags_NoMove + ImGuiWindowFlags_NoBringToFrontOnFocus
self.positioner = positioner
self.buttons = {}
self.onContextChange = function(context)
self.buttons = {}
for _, value in ipairs(context.actionsList) do
if value.icon then
local description = lm(context.name .. ".actions." .. value.action)
if description == lm.MISSING then
description = ""
end
table.insert(self.buttons, {
description = description,
icon = value.icon,
callback = value.callback,
padding = value.padding or 2
})
end
end
end
cm:onContextChange(self.onContextChange)
end)
-- render tools
function ToolsView:__call()
local x, y, width, height = self.positioner()
imgui.SetNextWindowPos(x, y)
imgui.SetNextWindowSize(width, height)
if self:imguiBegin() then
for _, button in ipairs(self.buttons) do
if imgui.Button(button.icon) then
button.callback()
end
if button.description ~= "" and imgui.IsItemHovered() then
imgui.BeginTooltip()
imgui.Text(button.description)
imgui.EndTooltip()
end
imgui.SameLine(0, button.padding)
end
self:imguiEnd()
end
end
| mit |
AresTao/darkstar | scripts/zones/West_Sarutabaruta_[S]/npcs/Sealed_Entrance_1.lua | 21 | 2312 | -----------------------------------
-- Area: West Sarutabaruta [S]
-- NPC: Sealed Entrance (Sealed_Entrance_1)
-- @pos -245.000 -18.100 660.000 95
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta_[S]/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/West_Sarutabaruta_[S]/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local QuestStatus = player:getQuestStatus(CRYSTAL_WAR, SNAKE_ON_THE_PLAINS);
local HasPutty = player:hasKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
local MaskBit1 = player:getMaskBit(player:getVar("SEALED_DOORS"),0)
local MaskBit2 = player:getMaskBit(player:getVar("SEALED_DOORS"),1)
local MaskBit3 = player:getMaskBit(player:getVar("SEALED_DOORS"),2)
if (QuestStatus == QUEST_ACCEPTED and HasPutty) then
if (MaskBit1 == false) then
if (MaskBit2 == false or MaskBit3 == false) then
player:setMaskBit(player:getVar("SEALED_DOORS"),"SEALED_DOORS",0,true);
player:messageSpecial(DOOR_OFFSET+1,ZONPAZIPPAS_ALLPURPOSE_PUTTY);
else
player:setMaskBit(player:getVar("SEALED_DOORS"),"SEALED_DOORS",0,true);
player:messageSpecial(DOOR_OFFSET+4,ZONPAZIPPAS_ALLPURPOSE_PUTTY);
player:delKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
end
else
player:messageSpecial(DOOR_OFFSET+2,ZONPAZIPPAS_ALLPURPOSE_PUTTY);
end
elseif (player:getQuestStatus(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS) == QUEST_COMPLETED) then
player:messageSpecial(DOOR_OFFSET+2, ZONPAZIPPAS_ALLPURPOSE_PUTTY);
else
player:messageSpecial(DOOR_OFFSET+3);
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 |
DeinFreund/Zero-K | units/damagesinkrock.lua | 6 | 1114 | unitDef = {
unitname = [[rocksink]],
name = [[Rocking Damage Sink thing]],
description = [[Rocks when you shoot at it.]],
acceleration = 0,
autoHeal = 500000,
buildCostMetal = 10,
builder = false,
buildingGroundDecalType = [[zenith_aoplane.dds]],
buildPic = [[zenith.png]],
category = [[SINK GUNSHIP]],
energyUse = 0,
footprintX = 2,
footprintZ = 2,
iconType = [[mahlazer]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 500000,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
objectName = [[zenith.s3o]],
script = [[nullrock.lua]],
sightDistance = 660,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[yyyy]],
}
return lowerkeys({ rocksink = unitDef })
| gpl-2.0 |
DeinFreund/Zero-K | LuaUI/Widgets/chili_new/headers/skinutils.lua | 1 | 35191 | --//=============================================================================
--//
function _DrawTextureAspect(x,y,w,h ,tw,th)
local twa = w/tw
local tha = h/th
local aspect = 1
if (twa < tha) then
aspect = twa
y = y + h*0.5 - th*aspect*0.5
h = th*aspect
else
aspect = tha
x = x + w*0.5 - tw*aspect*0.5
w = tw*aspect
end
local right = math.ceil(x+w)
local bottom = math.ceil(y+h)
x = math.ceil(x)
y = math.ceil(y)
gl.TexRect(x,y,right,bottom,false,true)
end
local _DrawTextureAspect = _DrawTextureAspect
function _DrawTiledTexture(x,y,w,h, skLeft,skTop,skRight,skBottom, texw,texh, texIndex)
texIndex = texIndex or 0
local txLeft = skLeft/texw
local txTop = skTop/texh
local txRight = skRight/texw
local txBottom = skBottom/texh
--//scale down the texture if we don't have enough space
local scaleY = h/(skTop+skBottom)
local scaleX = w/(skLeft+skRight)
local scale = (scaleX < scaleY) and scaleX or scaleY
if (scale<1) then
skTop = skTop * scale
skBottom = skBottom * scale
skLeft = skLeft * scale
skRight = skRight * scale
end
--//topleft
gl.MultiTexCoord(texIndex,0,0)
gl.Vertex(x, y)
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,0)
gl.Vertex(x+skLeft, y)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
--//topcenter
gl.MultiTexCoord(texIndex,1-txRight,0)
gl.Vertex(x+w-skRight, y)
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
--//topright
gl.MultiTexCoord(texIndex,1,0)
gl.Vertex(x+w, y)
gl.MultiTexCoord(texIndex,1,txTop)
gl.Vertex(x+w, y+skTop)
--//right center
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
--//background
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
--//left center
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,0,1-txBottom)
gl.Vertex(x, y+h-skBottom)
--//bottom right
gl.MultiTexCoord(texIndex,0,1)
gl.Vertex(x, y+h) --//degenerate
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,1)
gl.Vertex(x+skLeft, y+h)
--//bottom center
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
gl.MultiTexCoord(texIndex,1-txRight,1)
gl.Vertex(x+w-skRight, y+h)
--//bottom right
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom)
gl.MultiTexCoord(texIndex,1,1)
gl.Vertex(x+w, y+h)
end
local _DrawTiledTexture = _DrawTiledTexture
function _DrawTiledBorder(x,y,w,h, skLeft,skTop,skRight,skBottom, texw,texh, texIndex)
texIndex = texIndex or 0
local txLeft = skLeft/texw
local txTop = skTop/texh
local txRight = skRight/texw
local txBottom = skBottom/texh
--//scale down the texture if we don't have enough space
local scaleY = h/(skTop+skBottom)
local scaleX = w/(skLeft+skRight)
local scale = (scaleX < scaleY) and scaleX or scaleY
if (scale<1) then
skTop = skTop * scale
skBottom = skBottom * scale
skLeft = skLeft * scale
skRight = skRight * scale
end
--//topleft
gl.MultiTexCoord(texIndex,0,0)
gl.Vertex(x, y)
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,0)
gl.Vertex(x+skLeft, y)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
--//topcenter
gl.MultiTexCoord(texIndex,1-txRight,0)
gl.Vertex(x+w-skRight, y)
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
--//topright
gl.MultiTexCoord(texIndex,1,0)
gl.Vertex(x+w, y)
gl.MultiTexCoord(texIndex,1,txTop)
gl.Vertex(x+w, y+skTop)
--//right center
gl.Vertex(x+w, y+skTop) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom)
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
--//bottom right
gl.MultiTexCoord(texIndex,1,1)
gl.Vertex(x+w, y+h)
gl.MultiTexCoord(texIndex,1-txRight,1)
gl.Vertex(x+w-skRight, y+h)
--//bottom center
gl.Vertex(x+w-skRight, y+h) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,1)
gl.Vertex(x+skLeft, y+h)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
--//bottom left
gl.MultiTexCoord(texIndex,0,1)
gl.Vertex(x, y+h)
gl.MultiTexCoord(texIndex,0,1-txBottom)
gl.Vertex(x, y+h-skBottom)
--//left center
gl.Vertex(x, y+h-skBottom) --//degenerate
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
end
local _DrawTiledBorder = _DrawTiledBorder
local function _DrawDragGrip(obj)
local x = 13
local y = 8
local w = obj.dragGripSize[1]
local h = obj.dragGripSize[2]
gl.Color(0.8,0.8,0.8,0.9)
gl.Vertex(x, y + h*0.5)
gl.Vertex(x + w*0.5, y)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Color(0.3,0.3,0.3,0.9)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Vertex(x + w*0.5, y)
gl.Vertex(x + w, y + h*0.5)
gl.Vertex(x + w*0.5, y + h)
gl.Vertex(x, y + h*0.5)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Color(0.1,0.1,0.1,0.9)
gl.Vertex(x + w*0.5, y + h)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Vertex(x + w, y + h*0.5)
end
local function _DrawResizeGrip(obj)
if (obj.resizable) then
local x = 0
local y = 0
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
x = x-1
y = y-1
gl.Color(1,1,1,0.2)
gl.Vertex(x + resizeBox[1], y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2])
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.33), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.33))
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.66), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.66))
x = x+1
y = y+1
gl.Color(0.1, 0.1, 0.1, 0.9)
gl.Vertex(x + resizeBox[1], y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2])
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.33), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.33))
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.66), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.66))
end
end
local function _DrawCursor(x, y, w, h)
gl.Vertex(x, y)
gl.Vertex(x, y + h)
gl.Vertex(x + w, y)
gl.Vertex(x + w, y + h)
end
local function _DrawSelection(x, y, w, h)
gl.Vertex(x, y)
gl.Vertex(x, y + h)
gl.Vertex(x + w, y)
gl.Vertex(x + w, y + h)
end
--//=============================================================================
--//
function DrawWindow(obj)
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
local c = obj.color
if (c) then
gl.Color(c)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.TileImage,obj)
local texInfo = gl.TextureInfo(obj.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th)
gl.Texture(0,false)
if (obj.caption) then
obj.font:Print(obj.caption, w*0.5, 9, "center")
end
end
--//=============================================================================
--//
function DrawButton(obj)
if obj.debug then Spring.Echo("DrawButton", obj.name, obj.state.pressed) end
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
local bgcolor = obj.backgroundColor
if (obj.state.pressed) then
bgcolor = mulColor(bgcolor, 0.4)
elseif (obj.state.hovered) --[[ or (obj.state.focused)]] then
bgcolor = obj.focusColor
--bgcolor = mixColors(bgcolor, obj.focusColor, 0.5)
end
gl.Color(bgcolor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
local fgcolor = obj.borderColor
if (obj.state.pressed) then
fgcolor = mulColor(fgcolor, 0.4)
elseif (obj.state.hovered) --[[ or (obj.state.focused)]] then
fgcolor = obj.focusColor
end
gl.Color(fgcolor)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
if (obj.caption) then
obj.font:Print(obj.caption, w*0.5, math.floor(h*0.5 - obj.font.size*0.35), "center", "linecenter")
end
end
function DrawComboBox(self)
DrawButton(self)
if (self.state.pressed) then
gl.Color(self.focusColor)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,self.TileImageArrow,self)
local texInfo = gl.TextureInfo(self.TileImageArrow) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(self.width - self.padding[3], 0, self.padding[3], self.height, tw,th)
gl.Texture(0,false)
end
function DrawEditBox(obj)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, 0, obj.width, obj.height, skLeft,skTop,skRight,skBottom, tw,th)
--gl.Texture(0,false)
if obj.state.focused or obj.state.hovered then
gl.Color(obj.focusColor)
else
gl.Color(obj.borderColor)
end
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, 0, obj.width, obj.height, skLeft,skTop,skRight,skBottom, tw,th)
gl.Texture(0,false)
local text = obj.text
local font = obj.font
local displayHint = false
if text == "" and not obj.state.focused then
text = obj.hint
displayHint = true
font = obj.hintFont
end
if (text) then
if obj.passwordInput and not displayHint then
text = string.rep("*", #text)
end
if (obj.offset > obj.cursor) and not obj.multiline then
obj.offset = obj.cursor
end
local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea)
--// make cursor pos always visible (when text is longer than editbox!)
if not obj.multiline then
repeat
local txt = text:sub(obj.offset, obj.cursor)
local wt = font:GetTextWidth(txt)
if (wt <= clientWidth) then
break
end
if (obj.offset >= obj.cursor) then
break
end
obj.offset = obj.offset + 1
until (false)
end
local txt = text:sub(obj.offset)
--// strip part at the end that exceeds the editbox
local lsize = math.max(0, font:WrapText(txt, clientWidth, clientHeight):len() - 3) -- find a good start (3 dots at end if stripped)
while (lsize <= txt:len()) do
local wt = font:GetTextWidth(txt:sub(1, lsize))
if (wt > clientWidth) then
break
end
lsize = lsize + 1
end
txt = txt:sub(1, lsize - 1)
gl.Color(1,1,1,1)
if obj.multiline then
if obj.parent and obj.parent:InheritsFrom("scrollpanel") then
local scrollPosY = obj.parent.scrollPosY
local scrollHeight = obj.parent.clientArea[4]
local h, d, numLines = obj.font:GetTextHeight(obj.text);
local minDrawY = scrollPosY - (h or 0)
local maxDrawY = scrollPosY + scrollHeight + (h or 0)
for _, line in pairs(obj.physicalLines) do
local drawPos = clientY + line.y
if drawPos > minDrawY and drawPos < maxDrawY then
font:Draw(line.text, clientX, clientY + line.y)
end
end
else
for _, line in pairs(obj.physicalLines) do
font:Draw(line.text, clientX, clientY + line.y)
end
end
else
font:DrawInBox(txt, clientX, clientY, clientWidth, clientHeight, obj.align, obj.valign)
end
if obj.state.focused and obj.editable then
local cursorTxt = text:sub(obj.offset, obj.cursor - 1)
local cursorX = font:GetTextWidth(cursorTxt)
local dt = Spring.DiffTimers(Spring.GetTimer(), obj._interactedTime)
local as = math.sin(dt * 8);
local ac = math.cos(dt * 8);
if (as < 0) then as = 0 end
if (ac < 0) then ac = 0 end
local alpha = as + ac
if (alpha > 1) then alpha = 1 end
alpha = 0.8 * alpha
local cc = obj.cursorColor
gl.Color(cc[1], cc[2], cc[3], cc[4] * alpha)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawCursor, cursorX + clientX - 1, clientY, 3, clientHeight)
end
if obj.selStart and obj.state.focused then
local cc = obj.selectionColor
gl.Color(cc[1], cc[2], cc[3], cc[4])
local top, bottom = obj.selStartPhysicalY, obj.selEndPhysicalY
local left, right = obj.selStartPhysical, obj.selEndPhysical
if obj.multiline and top > bottom then
top, bottom = bottom, top
left, right = right, left
elseif top == bottom and left > right then
left, right = right, left
end
local y = clientY
local height = clientHeight
if obj.multiline and top == bottom then
local line = obj.physicalLines[top]
text = line.text
y = y + line.y
height = line.lh
end
if not obj.multiline or top == bottom then
local leftTxt = text:sub(obj.offset, left - 1)
local leftX = font:GetTextWidth(leftTxt)
local rightTxt = text:sub(obj.offset, right - 1)
local rightX = font:GetTextWidth(rightTxt)
local w = rightX - leftX
-- limit the selection to the editbox width
w = math.min(w, obj.width - leftX - 3)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, leftX + clientX - 1, y, w, height)
else
local topLine, bottomLine = obj.physicalLines[top], obj.physicalLines[bottom]
local leftTxt = topLine.text:sub(obj.offset, left - 1)
local leftX = font:GetTextWidth(leftTxt)
local rightTxt = bottomLine.text:sub(obj.offset, right - 1)
local rightX = font:GetTextWidth(rightTxt)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, leftX + clientX - 1, clientY + topLine.y, topLine.tw - leftX, topLine.lh)
for i = top+1, bottom-1 do
local line = obj.physicalLines[i]
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, clientX - 1, clientY + line.y, line.tw, line.lh)
end
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, clientX - 1, clientY + bottomLine.y, rightX, bottomLine.lh)
end
end
end
end
--//=============================================================================
--//
function DrawPanel(obj)
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
gl.Color(obj.borderColor)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawItemBkGnd(obj,x,y,w,h,state)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (state=="selected") then
gl.Color(obj.colorBK_selected)
else
gl.Color(obj.colorBK)
end
TextureHandler.LoadTexture(0,obj.imageBK,obj)
local texInfo = gl.TextureInfo(obj.imageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (state=="selected") then
gl.Color(obj.colorFG_selected)
else
gl.Color(obj.colorFG)
end
TextureHandler.LoadTexture(0,obj.imageFG,obj)
local texInfo = gl.TextureInfo(obj.imageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawScrollPanelBorder(self)
local clientX,clientY,clientWidth,clientHeight = unpack4(self.clientArea)
local contX,contY,contWidth,contHeight = unpack4(self.contentArea)
do
TextureHandler.LoadTexture(0,self.BorderTileImage,self)
local texInfo = gl.TextureInfo(self.BorderTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
local skLeft,skTop,skRight,skBottom = unpack4(self.bordertiles)
local width = self.width
local height = self.height
if (self._vscrollbar) then
width = width - self.scrollbarSize - 1
end
if (self._hscrollbar) then
height = height - self.scrollbarSize - 1
end
gl.Color(self.borderColor)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledBorder, 0,0,width,height, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
end
--//=============================================================================
--//
function DrawScrollPanel(obj)
local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea)
local contX,contY,contWidth,contHeight = unpack4(obj.contentArea)
if (obj.BackgroundTileImage) then
TextureHandler.LoadTexture(0,obj.BackgroundTileImage,obj)
local texInfo = gl.TextureInfo(obj.BackgroundTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
local skLeft,skTop,skRight,skBottom = unpack4(obj.bkgndtiles)
local width = obj.width
local height = obj.height
if (obj._vscrollbar) then
width = width - obj.scrollbarSize - 1
end
if (obj._hscrollbar) then
height = height - obj.scrollbarSize - 1
end
gl.Color(obj.backgroundColor)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,width,height, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
if obj._vscrollbar then
local x = obj.width - obj.scrollbarSize
local y = 0
local w = obj.scrollbarSize
local h = obj.height --FIXME what if hscrollbar is visible
if (obj._hscrollbar) then
h = h - obj.scrollbarSize
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
TextureHandler.LoadTexture(0,obj.TileImage,obj)
local texInfo = gl.TextureInfo(obj.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if obj._vscrolling or obj._vHovered then
gl.Color(obj.KnobColorSelected)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.KnobTileImage,obj)
texInfo = gl.TextureInfo(obj.KnobTileImage) or {xsize=1, ysize=1}
tw,th = texInfo.xsize, texInfo.ysize
skLeft,skTop,skRight,skBottom = unpack4(obj.KnobTiles)
local pos = obj.scrollPosY / contHeight
local visible = clientHeight / contHeight
local gripy = math.floor(y + h * pos) + 0.5
local griph = math.floor(h * visible)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,gripy,obj.scrollbarSize,griph, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
gl.Color(1,1,1,1)
end
if obj._hscrollbar then
gl.Color(1,1,1,1)
local x = 0
local y = obj.height - obj.scrollbarSize
local w = obj.width
local h = obj.scrollbarSize
if (obj._vscrollbar) then
w = w - obj.scrollbarSize
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.htiles)
TextureHandler.LoadTexture(0,obj.HTileImage,obj)
local texInfo = gl.TextureInfo(obj.HTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if obj._hscrolling or obj._hHovered then
gl.Color(obj.KnobColorSelected)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.HKnobTileImage,obj)
texInfo = gl.TextureInfo(obj.HKnobTileImage) or {xsize=1, ysize=1}
tw,th = texInfo.xsize, texInfo.ysize
skLeft,skTop,skRight,skBottom = unpack4(obj.HKnobTiles)
local pos = obj.scrollPosX / contWidth
local visible = clientWidth / contWidth
local gripx = math.floor(x + w * pos) + 0.5
local gripw = math.floor(w * visible)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, gripx,y,gripw,obj.scrollbarSize, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
end
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawCheckbox(obj)
local boxSize = obj.boxsize
local x = obj.width - boxSize
local y = obj.height*0.5 - boxSize*0.5
local w = boxSize
local h = boxSize
local tx = 0
local ty = obj.height * 0.5 --// verticale center
if obj.boxalign == "left" then
x = 0
tx = boxSize + 2
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (obj.state.hovered) then
gl.Color(obj.focusColor)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (obj.state.checked) then
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
gl.Texture(0,false)
gl.Color(1,1,1,1)
if (obj.caption) then
obj.font:Print(obj.caption, tx, ty - obj.font.size*0.35, nil, "linecenter")
end
end
--//=============================================================================
--//
function DrawProgressbar(obj)
local w = obj.width
local h = obj.height
local percent = (obj.value-obj.min)/(obj.max-obj.min)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
gl.Color(obj.color)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.ClipPlane(1, -1,0,0, w*percent)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.ClipPlane(1, false)
gl.Texture(0,false)
if (obj.caption) then
(obj.font):Print(obj.caption, w*0.5, h*0.5 - obj.font.size*0.35 , "center", "linecenter")
end
end
--//=============================================================================
--//
function DrawTrackbar(self)
local percent = self:_GetPercent()
local w = self.width
local h = self.height
local skLeft,skTop,skRight,skBottom = unpack4(self.tiles)
local pdLeft,pdTop,pdRight,pdBottom = unpack4(self.hitpadding)
gl.Color(1,1,1,1)
TextureHandler.LoadTexture(0,self.TileImage,self)
local texInfo = gl.TextureInfo(self.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
TextureHandler.LoadTexture(0,self.StepImage,self)
local texInfo = gl.TextureInfo(self.StepImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
--// scale the thumb down if we don't have enough space
if (th>h) then
tw = math.ceil(tw*(h/th))
th = h
end
if (tw>w) then
th = math.ceil(th*(w/tw))
tw = w
end
local barWidth = w - (pdLeft + pdRight)
local stepWidth = barWidth / ((self.max - self.min)/self.step)
if ((self.max - self.min)/self.step)<20 then
local newStepWidth = stepWidth
if (newStepWidth<20) then
newStepWidth = stepWidth*2
end
if (newStepWidth<20) then
newStepWidth = stepWidth*5
end
if (newStepWidth<20) then
newStepWidth = stepWidth*10
end
stepWidth = newStepWidth
local my = h*0.5
local mx = pdLeft+stepWidth
while (mx<(pdLeft+barWidth)) do
gl.TexRect(math.ceil(mx-tw*0.5),math.ceil(my-th*0.5),math.ceil(mx+tw*0.5),math.ceil(my+th*0.5),false,true)
mx = mx+stepWidth
end
end
if (self.state.hovered) then
gl.Color(self.focusColor)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,self.ThumbImage,self)
local texInfo = gl.TextureInfo(self.ThumbImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
--// scale the thumb down if we don't have enough space
tw = math.ceil(tw * (h / th))
th = h
local barWidth = w - (pdLeft + pdRight)
local mx = pdLeft + barWidth * percent
local my = h * 0.5
mx = math.floor(mx - tw * 0.5)
my = math.floor(my - th * 0.5)
gl.TexRect(mx, my, mx + tw, my + th, false, true)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawTreeviewNode(self)
if CompareLinks(self.treeview.selected,self) then
local x = self.clientArea[1]
local y = 0
local w = self.children[1].width
local h = self.clientArea[2] + self.children[1].height
local skLeft,skTop,skRight,skBottom = unpack4(self.treeview.tiles)
gl.Color(1,1,1,1)
TextureHandler.LoadTexture(0,self.treeview.ImageNodeSelected,self)
local texInfo = gl.TextureInfo(self.treeview.ImageNodeSelected) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
end
local function _DrawLineV(x, y1, y2, width, next_func, ...)
gl.Vertex(x-width*0.5, y1)
gl.Vertex(x+width*0.5, y1)
gl.Vertex(x-width*0.5, y2)
gl.Vertex(x+width*0.5, y1)
gl.Vertex(x-width*0.5, y2)
gl.Vertex(x+width*0.5, y2)
if (next_func) then
next_func(...)
end
end
local function _DrawLineH(x1, x2, y, width, next_func, ...)
gl.Vertex(x1, y-width*0.5)
gl.Vertex(x1, y+width*0.5)
gl.Vertex(x2, y-width*0.5)
gl.Vertex(x1, y+width*0.5)
gl.Vertex(x2, y-width*0.5)
gl.Vertex(x2, y+width*0.5)
if (next_func) then
next_func(...)
end
end
function DrawTreeviewNodeTree(self)
local x1 = math.ceil(self.padding[1]*0.5)
local x2 = self.padding[1]
local y1 = 0
local y2 = self.height
local y3 = self.padding[2] + math.ceil(self.children[1].height*0.5)
if (self.parent)and(CompareLinks(self,self.parent.nodes[#self.parent.nodes])) then
y2 = y3
end
gl.Color(self.treeview.treeColor)
gl.BeginEnd(GL.TRIANGLES, _DrawLineV, x1-0.5, y1, y2, 1, _DrawLineH, x1, x2, y3-0.5, 1)
if (not self.nodes[1]) then
return
end
gl.Color(1,1,1,1)
local image = self.ImageExpanded or self.treeview.ImageExpanded
if (not self.expanded) then
image = self.ImageCollapsed or self.treeview.ImageCollapsed
end
TextureHandler.LoadTexture(0, image, self)
local texInfo = gl.TextureInfo(image) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(0,0,math.ceil(self.padding[1]),math.ceil(self.children[1].height) ,tw,th)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawLine(self)
gl.Color(self.borderColor)
if (self.style:find("^v")) then
local skLeft,skTop,skRight,skBottom = unpack4(self.tilesV)
TextureHandler.LoadTexture(0,self.TileImageV,self)
local texInfo = gl.TextureInfo(self.TileImageV) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, self.width * 0.5 - 2, 0, 4, self.height, skLeft,skTop,skRight,skBottom, tw,th, 0)
else
local skLeft,skTop,skRight,skBottom = unpack4(self.tiles)
TextureHandler.LoadTexture(0,self.TileImage,self)
local texInfo = gl.TextureInfo(self.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, self.height * 0.5 - 2, self.width, 4, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
gl.Texture(0,false)
if (self.debug) then
gl.Color(0,1,0,0.5)
gl.PolygonMode(GL.FRONT_AND_BACK,GL.LINE)
gl.LineWidth(2)
gl.Rect(0,0,self.width,self.height)
gl.LineWidth(1)
gl.PolygonMode(GL.FRONT_AND_BACK,GL.FILL)
end
end
--//=============================================================================
--//
function DrawTabBarItem(obj)
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (obj.state.pressed) then
gl.Color(mulColor(obj.backgroundColor,0.4))
elseif (obj.state.hovered) then
gl.Color(obj.focusColor)
elseif (obj.state.selected) then
gl.Color(obj.focusColor)
else
gl.Color(obj.backgroundColor)
end
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (obj.state.pressed) then
gl.Color(0.6,0.6,0.6,1) --FIXME
elseif (obj.state.selected) then
gl.Color(obj.focusColor)
else
gl.Color(obj.borderColor)
end
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
if (obj.caption) then
local cx,cy,cw,ch = unpack4(obj.clientArea)
obj.font:DrawInBox(obj.caption, cx, cy, cw, ch, "center", "center")
end
end
--//=============================================================================
--//
function DrawDragGrip(obj)
gl.BeginEnd(GL.TRIANGLES, _DrawDragGrip, obj)
end
function DrawResizeGrip(obj)
gl.BeginEnd(GL.LINES, _DrawResizeGrip, obj)
end
--//=============================================================================
--// HitTest helpers
function _ProcessRelative(code, total)
--// FIXME: duplicated in control.lua!
if (type(code) == "string") then
local percent = tonumber(code:sub(1,-2)) or 0
if (percent<0) then
percent = 0
elseif (percent>100) then
percent = 100
end
return math.floor(total * percent)
elseif (code<0) then
return math.floor(total + code)
else
return math.floor(code)
end
end
function GetRelativeObjBox(obj,boxrelative)
return {
_ProcessRelative(boxrelative[1], obj.width),
_ProcessRelative(boxrelative[2], obj.height),
_ProcessRelative(boxrelative[3], obj.width),
_ProcessRelative(boxrelative[4], obj.height)
}
end
--//=============================================================================
--//
function NCHitTestWithPadding(obj,mx,my)
local hp = obj.hitpadding
local x = hp[1]
local y = hp[2]
local w = obj.width - hp[1] - hp[3]
local h = obj.height - hp[2] - hp[4]
--// early out
if (not InRect({x,y,w,h},mx,my)) then
return false
end
local resizable = obj.resizable
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
resizable = resizable or obj.tweakResizable
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (resizable) then
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
if (InRect(resizeBox,mx,my)) then
return obj
end
end
if (dragUseGrip) then
local dragBox = GetRelativeObjBox(obj,obj.boxes.drag)
if (InRect(dragBox,mx,my)) then
return obj
end
elseif (draggable) then
return obj
end
if obj.noClickThrough then
return obj
end
end
function WindowNCMouseDown(obj,x,y)
local resizable = obj.resizable
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
resizable = resizable or obj.tweakResizable
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (resizable) then
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
if (InRect(resizeBox,x,y)) then
obj:StartResizing(x,y)
return obj
end
end
if (dragUseGrip) then
local dragBox = GetRelativeObjBox(obj,obj.boxes.drag)
if (InRect(dragBox,x,y)) then
obj:StartDragging()
return obj
end
end
end
function WindowNCMouseDownPostChildren(obj,x,y)
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (draggable and not dragUseGrip) then
obj:StartDragging()
return obj
end
if obj.noClickThrough then
return obj
end
end
--//=============================================================================
| gpl-2.0 |
rafael/kong | kong/plugins/oauth2/schema.lua | 13 | 1225 | local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function generate_if_missing(v, t, column)
if not v or stringy.strip(v) == "" then
return true, nil, { [column] = utils.random_string()}
end
return true
end
local function check_mandatory_scope(v, t)
if v and not t.scopes then
return false, "To set a mandatory scope you also need to create available scopes"
end
return true
end
return {
no_consumer = true,
fields = {
scopes = { required = false, type = "array" },
mandatory_scope = { required = true, type = "boolean", default = false, func = check_mandatory_scope },
provision_key = { required = false, unique = true, type = "string", func = generate_if_missing },
token_expiration = { required = true, type = "number", default = 7200 },
enable_authorization_code = { required = true, type = "boolean", default = true },
enable_implicit_grant = { required = true, type = "boolean", default = false },
enable_client_credentials = { required = true, type = "boolean", default = false },
enable_password_grant = { required = true, type = "boolean", default = false },
hide_credentials = { type = "boolean", default = false }
}
}
| apache-2.0 |
cokeboL/gopher-lua | _lua5.1-tests/locals.lua | 18 | 2728 | print('testing local variables plus some extra stuff')
do
local i = 10
do local i = 100; assert(i==100) end
do local i = 1000; assert(i==1000) end
assert(i == 10)
if i ~= 10 then
local i = 20
else
local i = 30
assert(i == 30)
end
end
f = nil
local f
x = 1
a = nil
loadstring('local a = {}')()
assert(type(a) ~= 'table')
function f (a)
local _1, _2, _3, _4, _5
local _6, _7, _8, _9, _10
local x = 3
local b = a
local c,d = a,b
if (d == b) then
local x = 'q'
x = b
assert(x == 2)
else
assert(nil)
end
assert(x == 3)
local f = 10
end
local b=10
local a; repeat local b; a,b=1,2; assert(a+1==b); until a+b==3
assert(x == 1)
f(2)
assert(type(f) == 'function')
-- testing globals ;-)
do
local f = {}
local _G = _G
for i=1,10 do f[i] = function (x) A=A+1; return A, _G.getfenv(x) end end
A=10; assert(f[1]() == 11)
for i=1,10 do assert(setfenv(f[i], {A=i}) == f[i]) end
assert(f[3]() == 4 and A == 11)
local a,b = f[8](1)
assert(b.A == 9)
a,b = f[8](0)
assert(b.A == 11) -- `real' global
local g
local function f () assert(setfenv(2, {a='10'}) == g) end
g = function () f(); _G.assert(_G.getfenv(1).a == '10') end
g(); assert(getfenv(g).a == '10')
end
-- test for global table of loaded chunks
local function foo (s)
return loadstring(s)
end
assert(getfenv(foo("")) == _G)
local a = {loadstring = loadstring}
setfenv(foo, a)
assert(getfenv(foo("")) == _G)
setfenv(0, a) -- change global environment
assert(getfenv(foo("")) == a)
setfenv(0, _G)
-- testing limits for special instructions
local a
local p = 4
for i=2,31 do
for j=-3,3 do
assert(loadstring(string.format([[local a=%s;a=a+
%s;
assert(a
==2^%s)]], j, p-j, i))) ()
assert(loadstring(string.format([[local a=%s;
a=a-%s;
assert(a==-2^%s)]], -j, p-j, i))) ()
assert(loadstring(string.format([[local a,b=0,%s;
a=b-%s;
assert(a==-2^%s)]], -j, p-j, i))) ()
end
p =2*p
end
print'+'
if rawget(_G, "querytab") then
-- testing clearing of dead elements from tables
collectgarbage("stop") -- stop GC
local a = {[{}] = 4, [3] = 0, alo = 1,
a1234567890123456789012345678901234567890 = 10}
local t = querytab(a)
for k,_ in pairs(a) do a[k] = nil end
collectgarbage() -- restore GC and collect dead fiels in `a'
for i=0,t-1 do
local k = querytab(a, i)
assert(k == nil or type(k) == 'number' or k == 'alo')
end
end
print('OK')
return 5,f
| mit |
black123456789/man | plugins/time.lua | 94 | 3004 | -- Implement a command !time [area] which uses
-- 2 Google APIs to get the desired result:
-- 1. Geocoding to get from area to a lat/long pair
-- 2. Timezone to get the local time in that lat/long location
-- Globals
-- If you have a google api key for the geocoding/timezone api
api_key = nil
base_api = "https://maps.googleapis.com/maps/api"
dateFormat = "%A %d %B - %H:%M:%S"
-- Need the utc time for the google api
function utctime()
return os.time(os.date("!*t"))
end
-- Use the geocoding api to get the lattitude and longitude with accuracy specifier
-- CHECKME: this seems to work without a key??
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Get the data
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
-- Use timezone api to get the time in the lat,
-- Note: this needs an API key
function get_time(lat,lng)
local api = base_api .. "/timezone/json?"
-- Get a timestamp (server time is relevant here)
local timestamp = utctime()
local parameters = "location=" ..
URL.escape(lat) .. "," ..
URL.escape(lng) ..
"×tamp="..URL.escape(timestamp)
if api_key ~=nil then
parameters = parameters .. "&key="..api_key
end
local res,code = https.request(api..parameters)
if code ~= 200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Construct what we want
-- The local time in the location is:
-- timestamp + rawOffset + dstOffset
local localTime = timestamp + data.rawOffset + data.dstOffset
return localTime, data.timeZoneId
end
return localTime
end
function getformattedLocalTime(area)
if area == nil then
return "The time in nowhere is never"
end
lat,lng,acc = get_latlong(area)
if lat == nil and lng == nil then
return 'It seems that in "'..area..'" they do not have a concept of time.'
end
local localTime, timeZoneId = get_time(lat,lng)
return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime)
end
function run(msg, matches)
return getformattedLocalTime(matches[1])
end
return {
description = "Displays the local time in an area",
usage = "!time [area]: Displays the local time in that area",
patterns = {"^!time (.*)$"},
run = run
}
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
CarabusX/Zero-K | units/jumpsumo.lua | 3 | 8904 | return { jumpsumo = {
unitname = [[jumpsumo]],
name = [[Jugglenaut]],
description = [[Heavy Riot Jumper]],
acceleration = 0.3,
activateWhenBuilt = true,
brakeRate = 1.8,
buildCostMetal = 1700,
builder = false,
buildPic = [[jumpsumo.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[64 64 64]],
collisionVolumeType = [[ellipsoid]],
selectionvolumeoffsets = [[0 -16 0]],
corpse = [[DEAD]],
customParams = {
bait_level_default = 0,
canjump = 1,
jump_range = 360,
jump_height = 110,
jump_speed = 6,
jump_delay = 30,
jump_reload = 15,
jump_from_midair = 0,
jump_rotate_midair = 0,
aimposoffset = [[0 6 0]],
midposoffset = [[0 6 0]],
modelradius = [[32]],
lookahead = 120,
},
explodeAs = [[BIG_UNIT]],
footprintX = 4,
footprintZ = 4,
iconType = [[t3jumpjetriot]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
losEmitHeight = 60,
maxDamage = 13500,
maxSlope = 36,
maxVelocity = 1.15,
maxWaterDepth = 22,
movementClass = [[KBOT4]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]],
objectName = [[m-9.s3o]],
onoffable = true,
script = [[jumpsumo.lua]],
selfDestructAs = [[BIG_UNIT]],
sfxtypes = {
explosiongenerators = {
[[custom:sumosmoke]],
[[custom:BEAMWEAPON_MUZZLE_ORANGE]],
},
},
sightDistance = 480,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[crossFoot]],
trackWidth = 66,
turnRate = 600,
upright = false,
workerTime = 0,
weapons = {
{
def = [[FAKELASER]],
mainDir = [[0 0 1]],
maxAngleDif = 30,
},
{
def = [[GRAVITY_NEG]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[-1 0 0]],
maxAngleDif = 222,
},
{
def = [[GRAVITY_NEG]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[1 0 0]],
maxAngleDif = 222,
},
{
def = [[GRAVITY_POS]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[-1 0 0]],
maxAngleDif = 222,
},
{
def = [[GRAVITY_POS]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[1 0 0]],
maxAngleDif = 222,
},
{
def = [[LANDING]],
badTargetCategory = [[]],
mainDir = [[1 0 0]],
maxAngleDif = 0,
onlyTargetCategory = [[]],
},
},
weaponDefs = {
FAKELASER = {
name = [[Fake Laser]],
areaOfEffect = 12,
beamTime = 0.1,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
bogus = 1,
},
damage = {
default = 0,
},
duration = 0.1,
edgeEffectiveness = 0.99,
explosionGenerator = [[custom:flash1green]],
fireStarter = 70,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 5.53,
minIntensity = 1,
noSelfDamage = true,
proximityPriority = 10,
range = 440,
reloadtime = 0.1,
rgbColor = [[0 1 0]],
soundStart = [[weapon/laser/laser_burn5]],
soundTrigger = true,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 5.53,
tolerance = 10000,
turret = false,
weaponType = [[BeamLaser]],
weaponVelocity = 900,
},
GRAVITY_NEG = {
name = [[Attractive Gravity]],
areaOfEffect = 8,
avoidFriendly = false,
burst = 6,
burstrate = 0.033,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
impulse = [[-150]],
light_color = [[0.33 0.33 1.28]],
light_radius = 140,
},
damage = {
default = 0.001,
planes = 0.001,
},
duration = 0.0333,
explosionGenerator = [[custom:NONE]],
impactOnly = true,
intensity = 0.7,
interceptedByShieldType = 0,
noSelfDamage = true,
proximityPriority = -15,
range = 440,
reloadtime = 0.2,
rgbColor = [[0 0 1]],
rgbColor2 = [[1 0.5 1]],
size = 2,
soundStart = [[weapon/gravity_fire]],
soundTrigger = true,
thickness = 4,
tolerance = 5000,
turret = true,
weaponType = [[LaserCannon]],
weaponVelocity = 2200,
},
GRAVITY_POS = {
name = [[Repulsive Gravity]],
areaOfEffect = 8,
avoidFriendly = false,
burst = 6,
burstrate = 0.033,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
impulse = [[150]],
light_color = [[0.85 0.2 0.2]],
light_radius = 140,
},
damage = {
default = 0.001,
planes = 0.001,
},
duration = 0.0333,
explosionGenerator = [[custom:NONE]],
impactOnly = true,
intensity = 0.7,
interceptedByShieldType = 0,
noSelfDamage = true,
proximityPriority = 15,
range = 440,
reloadtime = 0.2,
rgbColor = [[1 0 0]],
rgbColor2 = [[1 0.5 1]],
size = 2,
soundStart = [[weapon/gravity_fire]],
soundTrigger = true,
thickness = 4,
tolerance = 5000,
turret = true,
weaponType = [[LaserCannon]],
weaponVelocity = 2200,
},
LANDING = {
name = [[Jugglenaut Landing]],
areaOfEffect = 340,
canattackground = false,
craterBoost = 4,
craterMult = 6,
damage = {
default = 1001.1,
planes = 1001.1,
},
edgeEffectiveness = 0,
explosionGenerator = [[custom:FLASH64]],
impulseBoost = 0.5,
impulseFactor = 1,
interceptedByShieldType = 1,
noSelfDamage = true,
range = 5,
reloadtime = 13,
soundHit = [[krog_stomp]],
soundStart = [[krog_stomp]],
soundStartVolume = 3,
turret = false,
weaponType = [[Cannon]],
weaponVelocity = 5,
customParams = {
hidden = true
}
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 3,
footprintZ = 3,
object = [[m-9_wreck.s3o]],
},
HEAP = {
blocking = false,
footprintX = 3,
footprintZ = 3,
object = [[debris3x3a.s3o]],
},
},
} }
| gpl-2.0 |
CarabusX/Zero-K | units/cloakjammer.lua | 4 | 1963 | return { cloakjammer = {
unitname = [[cloakjammer]],
name = [[Iris]],
description = [[Area Cloaker/Jammer Walker]],
acceleration = 0.75,
activateWhenBuilt = true,
brakeRate = 4.5,
buildCostMetal = 600,
buildPic = [[cloakjammer.png]],
canMove = true,
category = [[LAND UNARMED]],
corpse = [[DEAD]],
customParams = {
morphto = [[staticjammer]],
morphtime = 30,
area_cloak = 1,
area_cloak_upkeep = 15,
area_cloak_radius = 400,
priority_misc = 1,
cus_noflashlight = 1,
},
energyUse = 1.5,
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[kbotjammer]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 600,
maxSlope = 36,
maxVelocity = 1.9,
minCloakDistance = 180,
movementClass = [[AKBOT2]],
objectName = [[spherecloaker.s3o]],
onoffable = true,
pushResistant = 0,
script = [[cloakjammer.lua]],
radarDistanceJam = 400,
selfDestructAs = [[BIG_UNITEX]],
sightDistance = 400,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 18,
turnRate = 2520,
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[eraser_d.dae]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2a.s3o]],
},
},
} }
| gpl-2.0 |
awilliamson/Starfall | lua/weapons/gmod_tool/stools/starfall_processor.lua | 1 | 5151 | TOOL.Category = "Wire - Control"
TOOL.Name = "Starfall - Processor"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
-- ------------------------------- Sending / Recieving ------------------------------- --
include("starfall/sflib.lua")
local MakeSF
TOOL.ClientConVar[ "Model" ] = "models/spacecode/sfchip.mdl"
cleanup.Register( "starfall_processor" )
if SERVER then
CreateConVar('sbox_maxstarfall_processor', 10, {FCVAR_REPLICATED,FCVAR_NOTIFY,FCVAR_ARCHIVE})
function MakeSF( pl, Pos, Ang, model)
if not pl:CheckLimit( "starfall_processor" ) then return false end
local sf = ents.Create( "starfall_processor" )
if not IsValid(sf) then return false end
sf:SetAngles( Ang )
sf:SetPos( Pos )
sf:SetModel( model )
sf:Spawn()
sf.owner = pl
pl:AddCount( "starfall_processor", sf )
return sf
end
else
language.Add( "Tool.starfall_processor.name", "Starfall - Processor" )
language.Add( "Tool.starfall_processor.desc", "Spawns a starfall processor (Press shift+f to switch to screen and back again)" )
language.Add( "Tool.starfall_processor.0", "Primary: Spawns a processor / uploads code, Secondary: Opens editor" )
language.Add( "sboxlimit_starfall_processor", "You've hit the Starfall processor limit!" )
language.Add( "undone_Starfall Processor", "Undone Starfall Processor" )
end
function TOOL:LeftClick( trace )
if not trace.HitPos then return false end
if trace.Entity:IsPlayer() then return false end
if CLIENT then return true end
local ply = self:GetOwner()
if trace.Entity:IsValid() and trace.Entity:GetClass() == "starfall_processor" then
local ent = trace.Entity
if not SF.RequestCode(ply, function(mainfile, files)
if not mainfile then return end
if not IsValid(ent) then return end -- Probably removed during transfer
ent:Compile(files, mainfile)
end) then
WireLib.AddNotify(ply,"Cannot upload SF code, please wait for the current upload to finish.",NOTIFY_ERROR,7,NOTIFYSOUND_ERROR1)
end
return true
end
self:SetStage(0)
local model = self:GetClientInfo( "Model" )
if not self:GetSWEP():CheckLimit( "starfall_processor" ) then return false end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local sf = MakeSF( ply, trace.HitPos, Ang, model)
local min = sf:OBBMins()
sf:SetPos( trace.HitPos - trace.HitNormal * min.z )
local const = WireLib.Weld(sf, trace.Entity, trace.PhysicsBone, true)
undo.Create( "Starfall Processor" )
undo.AddEntity( sf )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "starfall_processor", sf )
if not SF.RequestCode(ply, function(mainfile, files)
if not mainfile then return end
if not IsValid(sf) then return end -- Probably removed during transfer
sf:Compile(files, mainfile)
end) then
WireLib.AddNotify(ply,"Cannot upload SF code, please wait for the current upload to finish.",NOTIFY_ERROR,7,NOTIFYSOUND_ERROR1)
end
return true
end
function TOOL:RightClick( trace )
if SERVER then self:GetOwner():SendLua("SF.Editor.open()") end
return false
end
function TOOL:Reload(trace)
return false
end
function TOOL:DrawHUD()
end
function TOOL:Think()
end
if CLIENT then
local function get_active_tool(ply, tool)
-- find toolgun
local activeWep = ply:GetActiveWeapon()
if not IsValid(activeWep) or activeWep:GetClass() ~= "gmod_tool" or activeWep.Mode ~= tool then return end
return activeWep:GetToolObject(tool)
end
hook.Add("PlayerBindPress", "wire_adv", function(ply, bind, pressed)
if not pressed then return end
if bind == "impulse 100" and ply:KeyDown( IN_SPEED ) then
local self = get_active_tool( ply, "starfall_processor" )
if not self then
self = get_active_tool( ply, "starfall_screen" )
if not self then return end
RunConsoleCommand( "gmod_tool", "starfall_processor" ) -- switch back to processor
return true
end
RunConsoleCommand( "gmod_tool", "starfall_screen" ) -- switch to screen
return true
end
end)
local lastclick = CurTime()
local function GotoDocs(button)
gui.OpenURL("http://sf.inp.io") -- old one: http://colonelthirtytwo.net/sfdoc/
end
function TOOL.BuildCPanel(panel)
panel:AddControl( "Header", { Text = "#Tool.starfall_processor.name", Description = "#Tool.starfall_processor.desc" } )
local gateModels = list.Get( "Starfall_gate_Models" )
table.Merge( gateModels, list.Get( "Wire_gate_Models" ) )
local modelPanel = WireDermaExts.ModelSelect( panel, "starfall_processor_Model", gateModels, 2 )
panel:AddControl("Label", {Text = ""})
local docbutton = vgui.Create("DButton" , panel)
panel:AddPanel(docbutton)
docbutton:SetText("Starfall Documentation")
docbutton.DoClick = GotoDocs
local filebrowser = vgui.Create("wire_expression2_browser")
panel:AddPanel(filebrowser)
filebrowser:Setup("starfall")
filebrowser:SetSize(235,400)
function filebrowser:OnFileOpen(filepath, newtab)
SF.Editor.editor:Open(filepath, nil, newtab)
end
local openeditor = vgui.Create("DButton", panel)
panel:AddPanel(openeditor)
openeditor:SetText("Open Editor")
openeditor.DoClick = SF.Editor.open
end
end
| bsd-3-clause |
mattyx14/otxserver | data/monster/humans/barbarian_headsplitter.lua | 2 | 3061 | local mType = Game.createMonsterType("Barbarian Headsplitter")
local monster = {}
monster.description = "a barbarian headsplitter"
monster.experience = 85
monster.outfit = {
lookType = 253,
lookHead = 115,
lookBody = 86,
lookLegs = 119,
lookFeet = 113,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 333
monster.Bestiary = {
class = "Human",
race = BESTY_RACE_HUMAN,
toKill = 500,
FirstUnlock = 25,
SecondUnlock = 250,
CharmsPoints = 15,
Stars = 2,
Occurrence = 0,
Locations = "Krimhorn, Bittermor, Ragnir, and Fenrock."
}
monster.health = 100
monster.maxHealth = 100
monster.race = "blood"
monster.corpse = 18062
monster.speed = 168
monster.manaCost = 450
monster.changeTarget = {
interval = 60000,
chance = 0
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = true,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = false,
staticAttackChance = 70,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "I will regain my honor with your blood!", yell = false},
{text = "Surrender is not option!", yell = false},
{text = "Its you or me!", yell = false},
{text = "Die! Die! Die!", yell = false}
}
monster.loot = {
{id = 2920, chance = 60300}, -- torch
{name = "gold coin", chance = 75600, maxCount = 30},
{id = 3052, chance = 230}, -- life ring
{name = "knife", chance = 14890},
{name = "brass helmet", chance = 20140},
{name = "viking helmet", chance = 5020},
{id = 3114, chance = 8000, maxCount = 2}, -- skull
{name = "scale armor", chance = 4060},
{name = "brown piece of cloth", chance = 980},
{name = "fur boots", chance = 90},
{name = "krimhorn helmet", chance = 110},
{name = "health potion", chance = 560}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -50},
{name ="combat", interval = 2000, chance = 15, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -60, range = 7, radius = 1, shootEffect = CONST_ANI_WHIRLWINDAXE, target = true}
}
monster.defenses = {
defense = 0,
armor = 7
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 20},
{type = COMBAT_EARTHDAMAGE, percent = -10},
{type = COMBAT_FIREDAMAGE, percent = 0},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 50},
{type = COMBAT_HOLYDAMAGE , percent = 20},
{type = COMBAT_DEATHDAMAGE , percent = -10}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = false},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
javad7070/senior | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-3.0 |
haswne/IRAQ_BOT | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-2.0 |
NAHAR99/GENERAL | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-3.0 |
mattyx14/otxserver | data/monster/giants/orclops_ravager.lua | 2 | 3704 | local mType = Game.createMonsterType("Orclops Ravager")
local monster = {}
monster.description = "an orclops ravager"
monster.experience = 1100
monster.outfit = {
lookType = 935,
lookHead = 94,
lookBody = 1,
lookLegs = 80,
lookFeet = 94,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 1320
monster.Bestiary = {
class = "Giant",
race = BESTY_RACE_GIANT,
toKill = 1000,
FirstUnlock = 50,
SecondUnlock = 500,
CharmsPoints = 25,
Stars = 3,
Occurrence = 0,
Locations = "Desecrated Glade."
}
monster.health = 1200
monster.maxHealth = 1200
monster.race = "blood"
monster.corpse = 25074
monster.speed = 260
monster.manaCost = 290
monster.changeTarget = {
interval = 5000,
chance = 0
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = false,
canPushCreatures = false,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 15,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = true
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "It's clobberin time!", yell = false},
{text = "Crushing! Smashing! Ripping! Yeah!!", yell = false}
}
monster.loot = {
{id = 3031, chance = 50320, maxCount = 120}, -- gold coin
{id = 3035, chance = 50320}, -- platinum coin
{id = 236, chance = 50320}, -- strong health potion
{id = 3078, chance = 50320}, -- mysterious fetish
{id = 3316, chance = 20000}, -- orcish axe
{id = 3724, chance = 50320, maxCount = 3}, -- red mushroom
{id = 23811, chance = 6000}, -- reinvigorating seeds
{id = 24380, chance = 4900}, -- bone toothpick
{id = 24381, chance = 1800}, -- beetle carapace
{id = 24382, chance = 12750}, -- bug meat
{id = 3027, chance = 2510, maxCount = 2}, -- black pearl
{id = 3030, chance = 1940, maxCount = 2}, -- small ruby
{id = 7452, chance = 1000}, -- spiked squelcher
{id = 8015, chance = 8870}, -- onion
{id = 9057, chance = 9700}, -- small topaz
{id = 16123, chance = 15290, maxCount = 3}, -- brown crystal splinter
{id = 17828, chance = 910}, -- pair of iron fists
{id = 2966, chance = 910}, -- war drum
{id = 7439, chance = 910}, -- berserk potion
{id = 7419, chance = 300} -- dreaded cleaver
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -240},
{name ="combat", interval = 2000, chance = 35, type = COMBAT_PHYSICALDAMAGE, minDamage = -180, maxDamage = -220, range = 7, shootEffect = CONST_ANI_LARGEROCK, target = true}
}
monster.defenses = {
defense = 25,
armor = 35,
{name ="speed", interval = 2000, chance = 10, speedChange = 336, effect = CONST_ME_MAGIC_RED, target = false, duration = 2000},
{name ="combat", interval = 2000, chance = 17, type = COMBAT_HEALING, minDamage = 80, maxDamage = 150, effect = CONST_ME_MAGIC_BLUE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = -10},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = 20},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 20},
{type = COMBAT_HOLYDAMAGE , percent = 50},
{type = COMBAT_DEATHDAMAGE , percent = 10}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
mojo2012/factorio-mojo-resource-processing | prototypes/entity/biofarm/tree-growing.lua | 1 | 2302 | require("prototypes.entity.biofarm.tree-definitions")
data:extend({
{
type = "tree",
name = "seedling",
icon = "__mojo-resource-processing__/graphics/icons/biofarm/seedling.png",
flags = {"placeable-neutral", "placeable-player", "player-creation", "breaths-air"},
minable = {
mining_particle = "wooden-particle",
mining_time = 0.5,
result = "seedling",
count = 1
},
emissions_per_tick = -0.0003,
max_health = 10,
collision_box = {{-0.8, -0.8}, {0.8, 0.8}},
selection_box = {{-0.8, -0.8}, {0.8, 0.8}},
drawing_box = {{-0.4, -0.6}, {0.2, 0.4}},
subgroup = "trees",
vehicle_impact_sound = { filename = "__base__/sound/car-wood-impact.ogg", volume = 1.0 },
variations = {
{
trunk = {
filename = "__mojo-resource-processing__/graphics/entity/biofarm/seedling-trunk.png",
width = 38,
height = 71,
frame_count = 4,
shift = {0, -0.55}
},
leaves = {
filename = "__mojo-resource-processing__/graphics/entity/biofarm/seedling-leaves.png",
width = 45,
height = 50,
frame_count = 3,
shift = {0, -1.00}
},
leaf_generation = {
type = "create-particle",
entity_name = "leaf-particle",
offset_deviation = {{-0.35, -0.35}, {0.35, 0.35}},
initial_height = 1,
initial_height_deviation = 0.5,
speed_from_center = 0.01
},
branch_generation = {
type = "create-particle",
entity_name = "branch-particle",
offset_deviation = {{-0.35, -0.35}, {0.35, 0.35}},
initial_height = 1,
initial_height_deviation = 1,
speed_from_center = 0.01,
frame_speed = 0.1,
repeat_count = 5,
}
}
},
colors = {
{r = 81, g = 126, b = 85},
{r = 81, g = 166, b = 89},
{r = 101, g = 191, b = 110},
{r = 147, g = 192, b = 39},
{r = 162, g = 222, b = 19},
{r = 201, g = 236, b = 116},
{r = 179, g = 199, b = 12},
{r = 181, g = 189, b = 114},
{r = 179, g = 199, b = 12},
{r = 200, g = 214, b = 83}
}
}
})
| gpl-3.0 |
spillerrec/BooruSurfer2 | premake4.lua | 1 | 1695 | solution( "BooruSurfer2" )
configurations{ "debug", "release" }
project( "Server" )
kind( "ConsoleApp" )
targetname( "BooruSurfer" )
language( "C++" )
location( "build" )
files( { "./src/**.h", "./src/**.cpp" } )
-- Enable C++14 support
buildoptions{ "-std=c++14 -pthread" }
-- Warnings
buildoptions{ "-Wall" }
links( {
"tidy"
, "jansson"
, "png"
, "sqlite3"
-- Poco libraries and dependencies
, "PocoNetSSL"
, "PocoCrypto"
, "PocoNet"
, "PocoUtil"
, "PocoJSON"
, "PocoXML"
, "PocoFoundation"
, "Ws2_32"
, "wsock32"
, "ssl"
, "crypto"
, "iphlpapi"
-- Windows thumbnail
, "Shell32"
, "Uuid"
, "Gdi32"
, "Ole32"
, "Windowscodecs"
, "boost_system-mgw52-mt-1_61"
, "boost_filesystem-mgw52-mt-1_61.dll"
} )
defines { "POCO_STATIC" }
configuration( "debug" )
build_dir = "debug"
targetdir( "bin/" .. build_dir )
defines( { "DEBUG" } )
flags { "Symbols" }
configuration( "release" )
build_dir = "release"
targetdir( "bin/" .. build_dir )
defines( { "RELEASE" } )
flags { "Optimize" }
-- Copy data files
os.mkdir( "bin/" .. build_dir .. "/data" )
files = os.matchfiles( "data/*.*" );
for k, f in pairs( files ) do
os.copyfile( f, "bin/" .. build_dir .. "/data/" .. path.getname(f) );
end
-- Copy resource files
os.mkdir( "bin/" .. build_dir .. "/data" )
files = os.matchfiles( "resources/*.*" );
for k, f in pairs( files ) do
os.copyfile( f, "bin/" .. build_dir .. "/resources/" .. path.getname(f) );
end
--Compile Scss
os.execute( "sass styles/main.scss bin/" .. build_dir .. "/resources/main.css" );
| gpl-3.0 |
punisherbot/erfan | bot/seedbot.lua | 24 | 10036 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban"
},
sudo_users = {110626080,103649648,111020322,0,tonumber(our_id)},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Teleseed v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
https://github.com/SEEDTEAM/TeleSeed
Admins
@iwals [Founder]
@imandaneshi [Developer]
@Rondoozle [Developer]
@seyedan25 [Manager]
Special thanks to
awkward_potato
Siyanew
topkecleon
Vamptacus
Our channels
@teleseedch [English]
@iranseed [persian]
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [GroupID] [Text]
Set a group's about text
!setrules [GroupID] [Text]
Set a group's rules
!lock [GroupID] [setting]
Lock a group's setting
!unlock [GroupID] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [GroupID]
Kick all memebers and delete group
!kill realm [RealmID]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Grt a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!br [group_id] [text]
!br 123456789 Hello !
This command will send text to [group_id]
**U can use both "/" and "!"
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
will return group logs
!banlist
will return group ban list
**U can use both "/" and "!"
*Only owner and mods can add bots in group
*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
hussian1997/hhhuu | plugins/set_type.lua | 8 | 1166 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY(@AHMED_ALOBIDE) ▀▄ ▄▀
▀▄ ▄▀ BY(@hussian_9) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function run(msg, matches, callback, extra)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(msg.to.id)]['group_type']
if matches[1] and is_sudo(msg) then
data[tostring(msg.to.id)]['group_type'] = matches[1]
save_data(_config.moderation.data, data)
return 'Group Type Seted To : '..matches[1]
end
if not is_owner(msg) then
return 'You Are Not Allow To set Group Type !'
end
end
return {
patterns = {
"^[#!/]type (.*)$",
},
run = run
}
| agpl-3.0 |
mattyx14/otxserver | data/monster/quests/forgotten_knowledge/soulcatcher.lua | 2 | 2063 | local mType = Game.createMonsterType("Soulcatcher")
local monster = {}
monster.description = "a soulcatcher"
monster.experience = 320
monster.outfit = {
lookTypeEx = 11053
}
monster.health = 50000
monster.maxHealth = 50000
monster.race = "undead"
monster.corpse = 0
monster.speed = 0
monster.manaCost = 0
monster.changeTarget = {
interval = 5000,
chance = 8
}
monster.strategiesTarget = {
nearest = 100,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = false,
canPushCreatures = false,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = true,
canWalkOnFire = true,
canWalkOnPoison = true
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
}
monster.attacks = {
{name ="combat", interval = 2000, chance = 25, type = COMBAT_LIFEDRAIN, minDamage = -300, maxDamage = -400, radius = 3, effect = CONST_ME_MAGIC_RED, target = false}
}
monster.defenses = {
defense = 50,
armor = 50,
{name ="soulcatcher summon", interval = 2000, chance = 10, target = false},
{name ="combat", interval = 2000, chance = 25, type = COMBAT_HEALING, minDamage = 100, maxDamage = 145, effect = CONST_ME_HITBYFIRE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 90},
{type = COMBAT_ENERGYDAMAGE, percent = 90},
{type = COMBAT_EARTHDAMAGE, percent = 90},
{type = COMBAT_FIREDAMAGE, percent = 90},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 90},
{type = COMBAT_HOLYDAMAGE , percent = 90},
{type = COMBAT_DEATHDAMAGE , percent = 90}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = false},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
mojo2012/factorio-mojo-resource-processing | prototypes/item/ore-processing/metal-products.lua | 1 | 3258 | data:extend(
{
{
type = "item",
name = "tin-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-tin/tin-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-a[tin-plate]",
stack_size = 200
},
{
type = "item",
name = "silver-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-silver/silver-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-c[silver-plate]",
stack_size = 200
},
{
type = "item",
name = "lead-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-lead/lead-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-f[lead-plate]",
stack_size = 200
},
{
type = "item",
name = "gold-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-gold/gold-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-d[gold-plate]",
stack_size = 200
},
{
type = "item",
name = "nickel-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-nickel/nickel-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-f[nickel-plate]",
stack_size = 200
},
{
type = "item",
name = "zinc-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-zinc/zinc-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-b[zinc-plate]",
stack_size = 200
},
{
type = "item",
name = "aluminium-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-bauxite/aluminium-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-g[aluminium-plate]",
stack_size = 200
},
{
type = "item",
name = "tungsten-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-tungsten/tungsten-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-i[tungsten-plate]",
stack_size = 200
},
-- rutil plate = titanium
{
type = "item",
name = "titanium-plate",
icon = "__mojo-resource-processing__/graphics/icons/ore-rutile/titanium-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-h[titanium-plate]",
stack_size = 200
},
--[[ type = "item",
name = "silicon",
icon = "__mojo-resource-processing__/graphics/icons/metal-plates/silicon-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-e[silicon-plate]",
stack_size = 200
},
{
type = "item",
name = "lithium",
icon = "__mojo-resource-processing__/graphics/icons/metal-plates/lithium-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-e[lithium-plate]",
stack_size = 200
},
{
type = "item",
name = "cobalt-plate",
icon = "__mojo-resource-processing__/graphics/icons/metal-plates/cobalt-plate.png",
flags = {"goes-to-main-inventory"},
subgroup = "raw-material",
order = "c-a-j[cobalt-plate]",
stack_size = 200
},--]]
}
)
| gpl-3.0 |
piccaso/debian-luakit | lib/cookie_blocking.lua | 7 | 1954 | ------------------------------------------------------
-- Simple domain-based cookie blocking --
-- © 2011 Mason Larobina <mason.larobina@gmail.com> --
------------------------------------------------------
require "cookies"
cookies.whitelist_path = luakit.config_dir .. "/cookie.whitelist"
cookies.blacklist_path = luakit.config_dir .. "/cookie.blacklist"
local cache = {}
local function mkglob(s)
s = string.gsub(s, "[%^%$%(%)%%%.%[%]%+%-%?]", "%%%1")
s = string.gsub(s, "*", "%%S*")
return "^"..s.."$"
end
local function load_rules(file)
assert(file, "invalid path")
local strip = lousy.util.string.strip
if os.exists(file) then
local rules = {}
for line in io.lines(file) do
table.insert(rules, mkglob(strip(line)))
end
return rules
end
end
function cookies.reload_lists()
cache = {} -- clear cache
cookies.whitelist = load_rules(cookies.whitelist_path)
cookies.blacklist = load_rules(cookies.blacklist_path)
end
function match_domain(rules, domain)
local match = string.match
for _, pat in ipairs(rules) do
if match(domain, pat) then return true end
end
end
cookies.add_signal("accept-cookie", function (cookie)
local domain = cookie.domain
-- Get cached block/allow result for given domain
if cache[domain] ~= nil then
return cache[domain]
end
local wl, bl = cookies.whitelist, cookies.blacklist
-- Check if domain in whitelist
if wl and wl[1] and match_domain(wl, domain) then
cache[domain] = true
return true
end
-- Check if domain in blacklist
if bl and bl[1] and match_domain(bl, domain) then
cache[domain] = false
return false
end
cache[domain] = cookies.default_allow
return cache[domain]
end)
-- Initial load of users cookie.whitelist / cookie.blacklist files
cookies.reload_lists()
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
mattyx14/otxserver | data/monster/giants/ogre_savage.lua | 2 | 3420 | local mType = Game.createMonsterType("Ogre Savage")
local monster = {}
monster.description = "an ogre savage"
monster.experience = 950
monster.outfit = {
lookType = 858,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 1162
monster.Bestiary = {
class = "Giant",
race = BESTY_RACE_GIANT,
toKill = 1000,
FirstUnlock = 50,
SecondUnlock = 500,
CharmsPoints = 25,
Stars = 3,
Occurrence = 0,
Locations = "Krailos Steppe."
}
monster.health = 1400
monster.maxHealth = 1400
monster.race = "blood"
monster.corpse = 22147
monster.speed = 220
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "Must! Chop! Food! Raahh!", yell = false},
{text = "You tasty!", yell = false},
{text = "UGGA UGGA!!", yell = false}
}
monster.loot = {
{id = 3031, chance = 92000, maxCount = 130}, -- gold coin
{id = 22193, chance = 3200, maxCount = 2}, -- onyx chip
{id = 22194, chance = 3200, maxCount = 3}, -- opal
{id = 3598, chance = 2200, maxCount = 7}, -- cookie
{id = 8016, chance = 1200, maxCount = 2}, -- jalapeno pepper
{id = 9057, chance = 1200, maxCount = 2}, -- small topaz
{id = 3030, chance = 1200, maxCount = 2}, -- small ruby
{id = 7439, chance = 1200}, -- berserk potion
{id = 3078, chance = 2200}, -- mysterious fetish
{id = 22188, chance = 1200}, -- ogre ear stud
{id = 22189, chance = 1200}, -- ogre nose ring
{id = 22191, chance = 1200}, -- skull fetish
{id = 236, chance = 2200, maxCount = 3}, -- strong health potion
{id = 3279, chance = 600}, -- war hammer
{id = 22192, chance = 300} -- shamanic mask
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -269, condition = {type = CONDITION_FIRE, totalDamage = 6, interval = 9000}},
{name ="combat", interval = 2000, chance = 15, type = COMBAT_FIREDAMAGE, minDamage = -70, maxDamage = -180, range = 7, shootEffect = CONST_ANI_POISON, target = false}
}
monster.defenses = {
defense = 20,
armor = 20,
{name ="combat", interval = 2000, chance = 10, type = COMBAT_HEALING, minDamage = 80, maxDamage = 95, effect = CONST_ME_MAGIC_BLUE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = -10},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = 20},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 20},
{type = COMBAT_HOLYDAMAGE , percent = 50},
{type = COMBAT_DEATHDAMAGE , percent = 10}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
PeqNP/GameKit | specs/heroin_spec.lua | 1 | 2271 | require("lang.Signal")
local ServiceLocator = require("heroin.ServiceLocator")
-- Dummy classes
local MyClass = Class()
function MyClass.new(self)
end
local SameClass = Class()
function SameClass.new(self)
local id
function self.init(i)
id = i
end
function self.getId()
return id
end
end
local MyContainer = Class()
MyContainer.implements("heroin.Container")
function MyContainer.new(self)
local deps = {
class = MyClass(),
same1 = SameClass(1),
same2 = SameClass(2)
}
function self.getDependencies()
return deps
end
end
-- Tests
describe("ServiceLocator", function()
local subject
before_each(function()
subject = ServiceLocator()
end)
it("should have set 'inject' to 'getDependency'", function()
assert.equal(subject.inject, subject.getDependency)
end)
context("registering a container", function()
local container
before_each(function()
container = MyContainer()
subject.registerContainer(container)
end)
it("should return dependency", function()
local inst = subject.getDependency(MyClass)
assert.truthy(inst.kindOf(MyClass))
end)
it("should return correct SameClass instance", function()
local inst = subject.getDependency("same1")
assert.truthy(inst.kindOf(SameClass))
assert.equal(inst.getId(), 1)
local inst = subject.getDependency("same2")
assert.truthy(inst.kindOf(SameClass))
assert.equal(inst.getId(), 2)
end)
-- it: should crash the app if dependency is not found.
context("when registering the same dependencies", function()
-- it: should crash the app if dependency is already registered.
end)
end)
context("registering a dependency", function()
local my
before_each(function()
my = MyClass()
subject.registerDependency("my", my)
end)
it("should return dependency", function()
local inst = subject.getDependency("my")
assert.truthy(inst.kindOf(MyClass))
assert.equal(inst, my)
end)
end)
end)
| mit |
amirhosein2233/uzzbot | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
lujingwei002/nodesrv | framework/nodesrv/debug/scenesrv/module/login.lua | 1 | 5284 | module('Login', package.seeall)
tmp_player_manager = tmp_player_manager or {}
player_manager = player_manager or {
--[uid] = player
}
player_count = player_count or 0
function PLAYER_ENTER(gatesrv, uid)
tmp_player_manager[uid] = gatesrv
loginfo('player enter uid(%d)', uid)
POST(centersrv, 'Login.PLAYER_ENTER', uid)
end
function PLAYER_EXIT(centersrv, uid)
loginfo('player exit uid(%d)', uid)
local player = player_manager[uid]
if not player then
logerr('player out found uid(%d)', uid)
POST(centersrv, 'Login.PLAYER_EXIT', uid)
return
end
player_logout(player)
end
--功能:可以上线
function PLAYER_PASS(sockfd, uid)
local player = player_manager[uid]
if player then
logerr('player had online uid(%d)', uid)
return
end
--开始加载数据
POST(datasrv1, 'DbSrv.GET', uid, 'Login.msg_db_srv_get_playerdata', unpack(Config.scenesrv.playerdata))
end
--功能:被顶号
function PLAYER_INSTEAD(gatesrv, uid)
loginfo('player exit uid(%d)', uid)
--解锁
--tmp_player_manager[uid] = nil
local player = player_manager[uid]
if not player then
logerr('player out found uid(%d)', uid)
return
end
local msg = Pblua.msgnew('login.DISCONNECT')
msg.errno = 15
Player.reply(player, msg)
player_logout(player)
end
--功能:登陆成功
--@player
function player_login(player)
local uid = player.uid
local user = player.playerdata.user
local rt, err = pcall(Player.init, player)
if not rt then
loginfo(err)
end
local msg = Pblua.msgnew('login.LOGIN')
Player.reply(player, msg)
end
--功能:下线
--player
function player_logout(player)
local uid = player.uid
local rt, err = pcall(Player.close, player)
if not rt then
logerr(err)
end
--保存数据
local playerdata = player.playerdata
local args = {}
for table_name, msg in pairs(playerdata) do
--是否有脏标志
if true or msg:isdirty() then
loginfo('uid(%d).%s is dirty', uid, table_name)
table.insert(args, table_name)
table.insert(args, msg)
else
loginfo('uid(%d).%s is clean', table_name)
end
end
POST(datasrv1, 'DbSrv.SET', uid, 'Login.msg_db_srv_set_playerdata', unpack(args))
end
--功能:读取数据返回
function msg_db_srv_get_playerdata(dbsrv, uid, result, ...)
--如果没有锁住
local gatesrv = tmp_player_manager[uid]
if not gatesrv then
POST(centersrv, 'Login.PLAYER_EXIT', uid)
logerr('player is disconnect')
return
end
local player = player_manager[uid]
if player then
player.gatesrv = gatesrv
logerr('player is online yet')
return
end
if result == 0 then
POST(centersrv, 'Login.PLAYER_EXIT', uid)
logerr('load playerdata fail uid(%d)', uid)
return
end
local playerdata = {}
local args = {...}
for index, varname in pairs(Config.centersrv.playerdata) do
playerdata[varname] = args[index]
end
--POST(gatesrv, 'Login.PLAYER_ENTER', uid)
loginfo( '加载数据成功')
--建立session
local player = {
gatesrv = gatesrv,
uid = uid,
playerdata = playerdata,
last_save_time = os.time(),
}
player_manager[uid] = player
tmp_player_manager[uid] = nil
player_count = player_count + 1
local rt, err = pcall(player_login, player)
if not rt then
logerr(err)
player_logout(player)
end
end
--功能:保存数据dv_srv返回
--@msg db_srv.SET_REPLY
function msg_db_srv_set_playerdata(dbsrv, uid, result, ...)
local player = player_manager[uid]
if not player then
logerr('player had exit')
return
end
if result == 0 then
logerr('save playerdata fail uid(%d)', uid)
return
end
local playerdata = player.playerdata
local user = playerdata.user
local args = {...}
for _, varname in pairs(args) do
local msg = playerdata[table_name]
--msg:setdirty(0)
end
--已经下线了
for k, v in pairs(playerdata) do
playerdata[k] = nil
end
player.playerdata = nil
--释放数据
player_manager[uid] = nil
player_count = player_count - 1
POST(centersrv, 'Login.PLAYER_EXIT', uid)
end
--功能:定时保存玩家数据
--function timer_check()
--local timenow = os.time()
--for uid, player in pairs(player_manager) do
--local playerdata = player.playerdata
--if timenow - player.last_save_time > Config.centersrv.save_interval then
--local args = {}
--for table_name, msg in pairs(playerdata) do
--if true or msg:isdirty() then
--loginfo('uid(%d).%s is dirty', uid, table_name)
--table.insert(args, table_name)
--table.insert(args, msg)
--else
--loginfo('uid(%d).%s is clean', table_name)
--end
--end
--POST(datasrv1, 'DbSrv.SET', uid, 'Login.msg_db_srv_set_playerdata', unpack(args))
--player.last_save_time = timenow
--end
--end
--end
| apache-2.0 |
fo369/luci-1505 | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/netlink.lua | 68 | 2502 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.sys")
local devices = luci.sys.net.devices()
m = Map("luci_statistics",
translate("Netlink Plugin Configuration"),
translate(
"The netlink plugin collects extended informations like " ..
"qdisc-, class- and filter-statistics for selected interfaces."
))
-- collectd_netlink config section
s = m:section( NamedSection, "collectd_netlink", "luci_statistics" )
-- collectd_netlink.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_netlink.interfaces (Interface)
interfaces = s:option( MultiValue, "Interfaces", translate("Basic monitoring") )
interfaces.widget = "select"
interfaces.optional = true
interfaces.size = #devices + 1
interfaces:depends( "enable", 1 )
interfaces:value("")
for i, v in ipairs(devices) do
interfaces:value(v)
end
-- collectd_netlink.verboseinterfaces (VerboseInterface)
verboseinterfaces = s:option( MultiValue, "VerboseInterfaces", translate("Verbose monitoring") )
verboseinterfaces.widget = "select"
verboseinterfaces.optional = true
verboseinterfaces.size = #devices + 1
verboseinterfaces:depends( "enable", 1 )
verboseinterfaces:value("")
for i, v in ipairs(devices) do
verboseinterfaces:value(v)
end
-- collectd_netlink.qdiscs (QDisc)
qdiscs = s:option( MultiValue, "QDiscs", translate("Qdisc monitoring") )
qdiscs.widget = "select"
qdiscs.optional = true
qdiscs.size = #devices + 1
qdiscs:depends( "enable", 1 )
qdiscs:value("")
for i, v in ipairs(devices) do
qdiscs:value(v)
end
-- collectd_netlink.classes (Class)
classes = s:option( MultiValue, "Classes", translate("Shaping class monitoring") )
classes.widget = "select"
classes.optional = true
classes.size = #devices + 1
classes:depends( "enable", 1 )
classes:value("")
for i, v in ipairs(devices) do
classes:value(v)
end
-- collectd_netlink.filters (Filter)
filters = s:option( MultiValue, "Filters", translate("Filter class monitoring") )
filters.widget = "select"
filters.optional = true
filters.size = #devices + 1
filters:depends( "enable", 1 )
filters:value("")
for i, v in ipairs(devices) do
filters:value(v)
end
-- collectd_netlink.ignoreselected (IgnoreSelected)
ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") )
ignoreselected.default = 0
ignoreselected:depends( "enable", 1 )
return m
| apache-2.0 |
nitheeshkl/kln_awesome | awesome_3.5/vicious/contrib/dio.lua | 16 | 2210 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
---------------------------------------------------
-- {{{ Grab environment
local ipairs = ipairs
local setmetatable = setmetatable
local table = { insert = table.insert }
local string = { gmatch = string.gmatch }
local helpers = require("vicious.helpers")
-- }}}
-- Disk I/O: provides I/O statistics for requested storage devices
-- vicious.contrib.dio
local dio = {}
-- Initialize function tables
local disk_usage = {}
local disk_total = {}
-- Variable definitions
local unit = { ["s"] = 1, ["kb"] = 2, ["mb"] = 2048 }
-- {{{ Disk I/O widget type
local function worker(format, disk)
if not disk then return end
local disk_lines = { [disk] = {} }
local disk_stats = helpers.pathtotable("/sys/block/" .. disk)
if disk_stats.stat then
local match = string.gmatch(disk_stats.stat, "[%s]+([%d]+)")
for i = 1, 11 do -- Store disk stats
table.insert(disk_lines[disk], match())
end
end
-- Ensure tables are initialized correctly
local diff_total = { [disk] = {} }
if not disk_total[disk] then
disk_usage[disk] = {}
disk_total[disk] = {}
while #disk_total[disk] < #disk_lines[disk] do
table.insert(disk_total[disk], 0)
end
end
for i, v in ipairs(disk_lines[disk]) do
-- Diskstats are absolute, substract our last reading
diff_total[disk][i] = v - disk_total[disk][i]
-- Store totals
disk_total[disk][i] = v
end
-- Calculate and store I/O
helpers.uformat(disk_usage[disk], "read", diff_total[disk][3], unit)
helpers.uformat(disk_usage[disk], "write", diff_total[disk][7], unit)
helpers.uformat(disk_usage[disk], "total", diff_total[disk][7] + diff_total[disk][3], unit)
-- Store I/O scheduler
if disk_stats.queue and disk_stats.queue.scheduler then
disk_usage[disk]["{sched}"] = string.gmatch(disk_stats.queue.scheduler, "%[([%a]+)%]")
end
return disk_usage[disk]
end
-- }}}
return setmetatable(dio, { __call = function(_, ...) return worker(...) end })
| gpl-2.0 |
rigeirani/nodc | plugins/welcome.lua | 114 | 3529 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n"
local text = sambutan..about..rules.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Sikout '..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
CarabusX/Zero-K | units/turretaaheavy.lua | 1 | 4367 | return { turretaaheavy = {
unitname = [[turretaaheavy]],
name = [[Artemis]],
description = [[Very Long-Range Anti-Air Missile Tower, Drains 4 m/s, 20 second stockpile]],
acceleration = 0,
activateWhenBuilt = true,
brakeRate = 0,
buildCostMetal = 2400,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 6,
buildingGroundDecalSizeY = 6,
buildingGroundDecalType = [[turretaaheavy_aoplane.dds]],
buildPic = [[turretaaheavy.png]],
category = [[SINK]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[74 74 74]],
collisionVolumeType = [[ellipsoid]],
corpse = [[DEAD]],
customParams = {
bait_level_default = 2,
modelradius = [[37]],
stockpilecost = [[80]],
stockpiletime = [[20]],
priority_misc = 1, -- Medium
},
explodeAs = [[ESTOR_BUILDING]],
footprintX = 4,
footprintZ = 4,
iconType = [[heavysam]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 3200,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
noAutoFire = false,
objectName = [[SCREAMER.s3o]],
onoffable = false,
script = [[turretaaheavy.lua]],
selfDestructAs = [[ESTOR_BUILDING]],
sightDistance = 660,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[oooooooooooooooo]],
weapons = {
{
def = [[ADVSAM]],
onlyTargetCategory = [[FIXEDWING GUNSHIP SATELLITE]],
},
},
weaponDefs = {
ADVSAM = {
name = [[Advanced Anti-Air Missile]],
areaOfEffect = 240,
canAttackGround = false,
cegTag = [[turretaaheavytrail]],
craterBoost = 0.1,
craterMult = 0.2,
cylinderTargeting = 3.2,
customParams = {
isaa = [[1]],
light_color = [[1.5 1.8 1.8]],
light_radius = 600,
},
damage = {
default = 160.15,
planes = 1601.5,
},
edgeEffectiveness = 0.25,
energypershot = 80,
explosionGenerator = [[custom:MISSILE_HIT_SPHERE_120]],
fireStarter = 90,
flightTime = 4,
groundbounce = 1,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
metalpershot = 80,
model = [[wep_m_avalanche.s3o]], -- Model radius 180 for QuadField fix.
noSelfDamage = true,
range = 2400,
reloadtime = 1.8,
smokeTrail = false,
soundHit = [[weapon/missile/heavy_aa_hit]],
soundStart = [[weapon/missile/heavy_aa_fire2]],
startVelocity = 1000,
stockpile = true,
stockpileTime = 10000,
texture1 = [[flarescale01]],
tolerance = 10000,
tracks = true,
trajectoryHeight = 0.55,
turnRate = 60000,
turret = true,
weaponAcceleration = 600,
weaponType = [[MissileLauncher]],
weaponVelocity = 1600,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 4,
footprintZ = 4,
object = [[screamer_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 4,
footprintZ = 4,
object = [[debris4x4a.s3o]],
},
},
} }
| gpl-2.0 |
Venomstrike/SimpleUI_WoW | Libs/AceDB-3.0/AceDB-3.0.lua | 11 | 24711 | --- **AceDB-3.0** manages the SavedVariables of your addon.
-- It offers profile management, smart defaults and namespaces for modules.\\
-- Data can be saved in different data-types, depending on its intended usage.
-- The most common data-type is the `profile` type, which allows the user to choose
-- the active profile, and manage the profiles of all of his characters.\\
-- The following data types are available:
-- * **char** Character-specific data. Every character has its own database.
-- * **realm** Realm-specific data. All of the players characters on the same realm share this database.
-- * **class** Class-specific data. All of the players characters of the same class share this database.
-- * **race** Race-specific data. All of the players characters of the same race share this database.
-- * **faction** Faction-specific data. All of the players characters of the same faction share this database.
-- * **factionrealm** Faction and realm specific data. All of the players characters on the same realm and of the same faction share this database.
-- * **global** Global Data. All characters on the same account share this database.
-- * **profile** Profile-specific data. All characters using the same profile share this database. The user can control which profile should be used.
--
-- Creating a new Database using the `:New` function will return a new DBObject. A database will inherit all functions
-- of the DBObjectLib listed here. \\
-- If you create a new namespaced child-database (`:RegisterNamespace`), you'll get a DBObject as well, but note
-- that the child-databases cannot individually change their profile, and are linked to their parents profile - and because of that,
-- the profile related APIs are not available. Only `:RegisterDefaults` and `:ResetProfile` are available on child-databases.
--
-- For more details on how to use AceDB-3.0, see the [[AceDB-3.0 Tutorial]].
--
-- You may also be interested in [[libdualspec-1-0|LibDualSpec-1.0]] to do profile switching automatically when switching specs.
--
-- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("DBExample")
--
-- -- declare defaults to be used in the DB
-- local defaults = {
-- profile = {
-- setting = true,
-- }
-- }
--
-- function MyAddon:OnInitialize()
-- -- Assuming the .toc says ## SavedVariables: MyAddonDB
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
-- end
-- @class file
-- @name AceDB-3.0.lua
-- @release $Id: AceDB-3.0.lua 1115 2014-09-21 11:52:35Z kaelten $
local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 25
local AceDB, oldminor = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR)
if not AceDB then return end -- No upgrade needed
-- Lua APIs
local type, pairs, next, error = type, pairs, next, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
-- WoW APIs
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub
AceDB.db_registry = AceDB.db_registry or {}
AceDB.frame = AceDB.frame or CreateFrame("Frame")
local CallbackHandler
local CallbackDummy = { Fire = function() end }
local DBObjectLib = {}
--[[-------------------------------------------------------------------------
AceDB Utility Functions
---------------------------------------------------------------------------]]
-- Simple shallow copy for copying defaults
local function copyTable(src, dest)
if type(dest) ~= "table" then dest = {} end
if type(src) == "table" then
for k,v in pairs(src) do
if type(v) == "table" then
-- try to index the key first so that the metatable creates the defaults, if set, and use that table
v = copyTable(v, dest[k])
end
dest[k] = v
end
end
return dest
end
-- Called to add defaults to a section of the database
--
-- When a ["*"] default section is indexed with a new key, a table is returned
-- and set in the host table. These tables must be cleaned up by removeDefaults
-- in order to ensure we don't write empty default tables.
local function copyDefaults(dest, src)
-- this happens if some value in the SV overwrites our default value with a non-table
--if type(dest) ~= "table" then return end
for k, v in pairs(src) do
if k == "*" or k == "**" then
if type(v) == "table" then
-- This is a metatable used for table defaults
local mt = {
-- This handles the lookup and creation of new subtables
__index = function(t,k)
if k == nil then return nil end
local tbl = {}
copyDefaults(tbl, v)
rawset(t, k, tbl)
return tbl
end,
}
setmetatable(dest, mt)
-- handle already existing tables in the SV
for dk, dv in pairs(dest) do
if not rawget(src, dk) and type(dv) == "table" then
copyDefaults(dv, v)
end
end
else
-- Values are not tables, so this is just a simple return
local mt = {__index = function(t,k) return k~=nil and v or nil end}
setmetatable(dest, mt)
end
elseif type(v) == "table" then
if not rawget(dest, k) then rawset(dest, k, {}) end
if type(dest[k]) == "table" then
copyDefaults(dest[k], v)
if src['**'] then
copyDefaults(dest[k], src['**'])
end
end
else
if rawget(dest, k) == nil then
rawset(dest, k, v)
end
end
end
end
-- Called to remove all defaults in the default table from the database
local function removeDefaults(db, defaults, blocker)
-- remove all metatables from the db, so we don't accidentally create new sub-tables through them
setmetatable(db, nil)
-- loop through the defaults and remove their content
for k,v in pairs(defaults) do
if k == "*" or k == "**" then
if type(v) == "table" then
-- Loop through all the actual k,v pairs and remove
for key, value in pairs(db) do
if type(value) == "table" then
-- if the key was not explicitly specified in the defaults table, just strip everything from * and ** tables
if defaults[key] == nil and (not blocker or blocker[key] == nil) then
removeDefaults(value, v)
-- if the table is empty afterwards, remove it
if next(value) == nil then
db[key] = nil
end
-- if it was specified, only strip ** content, but block values which were set in the key table
elseif k == "**" then
removeDefaults(value, v, defaults[key])
end
end
end
elseif k == "*" then
-- check for non-table default
for key, value in pairs(db) do
if defaults[key] == nil and v == value then
db[key] = nil
end
end
end
elseif type(v) == "table" and type(db[k]) == "table" then
-- if a blocker was set, dive into it, to allow multi-level defaults
removeDefaults(db[k], v, blocker and blocker[k])
if next(db[k]) == nil then
db[k] = nil
end
else
-- check if the current value matches the default, and that its not blocked by another defaults table
if db[k] == defaults[k] and (not blocker or blocker[k] == nil) then
db[k] = nil
end
end
end
end
-- This is called when a table section is first accessed, to set up the defaults
local function initSection(db, section, svstore, key, defaults)
local sv = rawget(db, "sv")
local tableCreated
if not sv[svstore] then sv[svstore] = {} end
if not sv[svstore][key] then
sv[svstore][key] = {}
tableCreated = true
end
local tbl = sv[svstore][key]
if defaults then
copyDefaults(tbl, defaults)
end
rawset(db, section, tbl)
return tableCreated, tbl
end
-- Metatable to handle the dynamic creation of sections and copying of sections.
local dbmt = {
__index = function(t, section)
local keys = rawget(t, "keys")
local key = keys[section]
if key then
local defaultTbl = rawget(t, "defaults")
local defaults = defaultTbl and defaultTbl[section]
if section == "profile" then
local new = initSection(t, section, "profiles", key, defaults)
if new then
-- Callback: OnNewProfile, database, newProfileKey
t.callbacks:Fire("OnNewProfile", t, key)
end
elseif section == "profiles" then
local sv = rawget(t, "sv")
if not sv.profiles then sv.profiles = {} end
rawset(t, "profiles", sv.profiles)
elseif section == "global" then
local sv = rawget(t, "sv")
if not sv.global then sv.global = {} end
if defaults then
copyDefaults(sv.global, defaults)
end
rawset(t, section, sv.global)
else
initSection(t, section, section, key, defaults)
end
end
return rawget(t, section)
end
}
local function validateDefaults(defaults, keyTbl, offset)
if not defaults then return end
offset = offset or 0
for k in pairs(defaults) do
if not keyTbl[k] or k == "profiles" then
error(("Usage: AceDBObject:RegisterDefaults(defaults): '%s' is not a valid datatype."):format(k), 3 + offset)
end
end
end
local preserve_keys = {
["callbacks"] = true,
["RegisterCallback"] = true,
["UnregisterCallback"] = true,
["UnregisterAllCallbacks"] = true,
["children"] = true,
}
local realmKey = GetRealmName()
local charKey = UnitName("player") .. " - " .. realmKey
local _, classKey = UnitClass("player")
local _, raceKey = UnitRace("player")
local factionKey = UnitFactionGroup("player")
local factionrealmKey = factionKey .. " - " .. realmKey
local localeKey = GetLocale():lower()
local regionTable = { "US", "KR", "EU", "TW", "CN" }
local regionKey = _G["GetCurrentRegion"] and regionTable[GetCurrentRegion()] or string.sub(GetCVar("realmList"), 1, 2):upper()
local factionrealmregionKey = factionrealmKey .. " - " .. regionKey
-- Actual database initialization function
local function initdb(sv, defaults, defaultProfile, olddb, parent)
-- Generate the database keys for each section
-- map "true" to our "Default" profile
if defaultProfile == true then defaultProfile = "Default" end
local profileKey
if not parent then
-- Make a container for profile keys
if not sv.profileKeys then sv.profileKeys = {} end
-- Try to get the profile selected from the char db
profileKey = sv.profileKeys[charKey] or defaultProfile or charKey
-- save the selected profile for later
sv.profileKeys[charKey] = profileKey
else
-- Use the profile of the parents DB
profileKey = parent.keys.profile or defaultProfile or charKey
-- clear the profileKeys in the DB, namespaces don't need to store them
sv.profileKeys = nil
end
-- This table contains keys that enable the dynamic creation
-- of each section of the table. The 'global' and 'profiles'
-- have a key of true, since they are handled in a special case
local keyTbl= {
["char"] = charKey,
["realm"] = realmKey,
["class"] = classKey,
["race"] = raceKey,
["faction"] = factionKey,
["factionrealm"] = factionrealmKey,
["factionrealmregion"] = factionrealmregionKey,
["profile"] = profileKey,
["locale"] = localeKey,
["global"] = true,
["profiles"] = true,
}
validateDefaults(defaults, keyTbl, 1)
-- This allows us to use this function to reset an entire database
-- Clear out the old database
if olddb then
for k,v in pairs(olddb) do if not preserve_keys[k] then olddb[k] = nil end end
end
-- Give this database the metatable so it initializes dynamically
local db = setmetatable(olddb or {}, dbmt)
if not rawget(db, "callbacks") then
-- try to load CallbackHandler-1.0 if it loaded after our library
if not CallbackHandler then CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0", true) end
db.callbacks = CallbackHandler and CallbackHandler:New(db) or CallbackDummy
end
-- Copy methods locally into the database object, to avoid hitting
-- the metatable when calling methods
if not parent then
for name, func in pairs(DBObjectLib) do
db[name] = func
end
else
-- hack this one in
db.RegisterDefaults = DBObjectLib.RegisterDefaults
db.ResetProfile = DBObjectLib.ResetProfile
end
-- Set some properties in the database object
db.profiles = sv.profiles
db.keys = keyTbl
db.sv = sv
--db.sv_name = name
db.defaults = defaults
db.parent = parent
-- store the DB in the registry
AceDB.db_registry[db] = true
return db
end
-- handle PLAYER_LOGOUT
-- strip all defaults from all databases
-- and cleans up empty sections
local function logoutHandler(frame, event)
if event == "PLAYER_LOGOUT" then
for db in pairs(AceDB.db_registry) do
db.callbacks:Fire("OnDatabaseShutdown", db)
db:RegisterDefaults(nil)
-- cleanup sections that are empty without defaults
local sv = rawget(db, "sv")
for section in pairs(db.keys) do
if rawget(sv, section) then
-- global is special, all other sections have sub-entrys
-- also don't delete empty profiles on main dbs, only on namespaces
if section ~= "global" and (section ~= "profiles" or rawget(db, "parent")) then
for key in pairs(sv[section]) do
if not next(sv[section][key]) then
sv[section][key] = nil
end
end
end
if not next(sv[section]) then
sv[section] = nil
end
end
end
end
end
end
AceDB.frame:RegisterEvent("PLAYER_LOGOUT")
AceDB.frame:SetScript("OnEvent", logoutHandler)
--[[-------------------------------------------------------------------------
AceDB Object Method Definitions
---------------------------------------------------------------------------]]
--- Sets the defaults table for the given database object by clearing any
-- that are currently set, and then setting the new defaults.
-- @param defaults A table of defaults for this database
function DBObjectLib:RegisterDefaults(defaults)
if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected.", 2)
end
validateDefaults(defaults, self.keys)
-- Remove any currently set defaults
if self.defaults then
for section,key in pairs(self.keys) do
if self.defaults[section] and rawget(self, section) then
removeDefaults(self[section], self.defaults[section])
end
end
end
-- Set the DBObject.defaults table
self.defaults = defaults
-- Copy in any defaults, only touching those sections already created
if defaults then
for section,key in pairs(self.keys) do
if defaults[section] and rawget(self, section) then
copyDefaults(self[section], defaults[section])
end
end
end
end
--- Changes the profile of the database and all of it's namespaces to the
-- supplied named profile
-- @param name The name of the profile to set as the current profile
function DBObjectLib:SetProfile(name)
if type(name) ~= "string" then
error("Usage: AceDBObject:SetProfile(name): 'name' - string expected.", 2)
end
-- changing to the same profile, dont do anything
if name == self.keys.profile then return end
local oldProfile = self.profile
local defaults = self.defaults and self.defaults.profile
-- Callback: OnProfileShutdown, database
self.callbacks:Fire("OnProfileShutdown", self)
if oldProfile and defaults then
-- Remove the defaults from the old profile
removeDefaults(oldProfile, defaults)
end
self.profile = nil
self.keys["profile"] = name
-- if the storage exists, save the new profile
-- this won't exist on namespaces.
if self.sv.profileKeys then
self.sv.profileKeys[charKey] = name
end
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.SetProfile(db, name)
end
end
-- Callback: OnProfileChanged, database, newProfileKey
self.callbacks:Fire("OnProfileChanged", self, name)
end
--- Returns a table with the names of the existing profiles in the database.
-- You can optionally supply a table to re-use for this purpose.
-- @param tbl A table to store the profile names in (optional)
function DBObjectLib:GetProfiles(tbl)
if tbl and type(tbl) ~= "table" then
error("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected.", 2)
end
-- Clear the container table
if tbl then
for k,v in pairs(tbl) do tbl[k] = nil end
else
tbl = {}
end
local curProfile = self.keys.profile
local i = 0
for profileKey in pairs(self.profiles) do
i = i + 1
tbl[i] = profileKey
if curProfile and profileKey == curProfile then curProfile = nil end
end
-- Add the current profile, if it hasn't been created yet
if curProfile then
i = i + 1
tbl[i] = curProfile
end
return tbl, i
end
--- Returns the current profile name used by the database
function DBObjectLib:GetCurrentProfile()
return self.keys.profile
end
--- Deletes a named profile. This profile must not be the active profile.
-- @param name The name of the profile to be deleted
-- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:DeleteProfile(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected.", 2)
end
if self.keys.profile == name then
error("Cannot delete the active profile in an AceDBObject.", 2)
end
if not rawget(self.profiles, name) and not silent then
error("Cannot delete profile '" .. name .. "'. It does not exist.", 2)
end
self.profiles[name] = nil
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.DeleteProfile(db, name, true)
end
end
-- switch all characters that use this profile back to the default
if self.sv.profileKeys then
for key, profile in pairs(self.sv.profileKeys) do
if profile == name then
self.sv.profileKeys[key] = nil
end
end
end
-- Callback: OnProfileDeleted, database, profileKey
self.callbacks:Fire("OnProfileDeleted", self, name)
end
--- Copies a named profile into the current profile, overwriting any conflicting
-- settings.
-- @param name The name of the profile to be copied into the current profile
-- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:CopyProfile(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:CopyProfile(name): 'name' - string expected.", 2)
end
if name == self.keys.profile then
error("Cannot have the same source and destination profiles.", 2)
end
if not rawget(self.profiles, name) and not silent then
error("Cannot copy profile '" .. name .. "'. It does not exist.", 2)
end
-- Reset the profile before copying
DBObjectLib.ResetProfile(self, nil, true)
local profile = self.profile
local source = self.profiles[name]
copyTable(source, profile)
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.CopyProfile(db, name, true)
end
end
-- Callback: OnProfileCopied, database, sourceProfileKey
self.callbacks:Fire("OnProfileCopied", self, name)
end
--- Resets the current profile to the default values (if specified).
-- @param noChildren if set to true, the reset will not be populated to the child namespaces of this DB object
-- @param noCallbacks if set to true, won't fire the OnProfileReset callback
function DBObjectLib:ResetProfile(noChildren, noCallbacks)
local profile = self.profile
for k,v in pairs(profile) do
profile[k] = nil
end
local defaults = self.defaults and self.defaults.profile
if defaults then
copyDefaults(profile, defaults)
end
-- populate to child namespaces
if self.children and not noChildren then
for _, db in pairs(self.children) do
DBObjectLib.ResetProfile(db, nil, noCallbacks)
end
end
-- Callback: OnProfileReset, database
if not noCallbacks then
self.callbacks:Fire("OnProfileReset", self)
end
end
--- Resets the entire database, using the string defaultProfile as the new default
-- profile.
-- @param defaultProfile The profile name to use as the default
function DBObjectLib:ResetDB(defaultProfile)
if defaultProfile and type(defaultProfile) ~= "string" then
error("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or nil expected.", 2)
end
local sv = self.sv
for k,v in pairs(sv) do
sv[k] = nil
end
local parent = self.parent
initdb(sv, self.defaults, defaultProfile, self)
-- fix the child namespaces
if self.children then
if not sv.namespaces then sv.namespaces = {} end
for name, db in pairs(self.children) do
if not sv.namespaces[name] then sv.namespaces[name] = {} end
initdb(sv.namespaces[name], db.defaults, self.keys.profile, db, self)
end
end
-- Callback: OnDatabaseReset, database
self.callbacks:Fire("OnDatabaseReset", self)
-- Callback: OnProfileChanged, database, profileKey
self.callbacks:Fire("OnProfileChanged", self, self.keys["profile"])
return self
end
--- Creates a new database namespace, directly tied to the database. This
-- is a full scale database in it's own rights other than the fact that
-- it cannot control its profile individually
-- @param name The name of the new namespace
-- @param defaults A table of values to use as defaults
function DBObjectLib:RegisterNamespace(name, defaults)
if type(name) ~= "string" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected.", 2)
end
if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected.", 2)
end
if self.children and self.children[name] then
error ("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace with that name already exists.", 2)
end
local sv = self.sv
if not sv.namespaces then sv.namespaces = {} end
if not sv.namespaces[name] then
sv.namespaces[name] = {}
end
local newDB = initdb(sv.namespaces[name], defaults, self.keys.profile, nil, self)
if not self.children then self.children = {} end
self.children[name] = newDB
return newDB
end
--- Returns an already existing namespace from the database object.
-- @param name The name of the new namespace
-- @param silent if true, the addon is optional, silently return nil if its not found
-- @usage
-- local namespace = self.db:GetNamespace('namespace')
-- @return the namespace object if found
function DBObjectLib:GetNamespace(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:GetNamespace(name): 'name' - string expected.", 2)
end
if not silent and not (self.children and self.children[name]) then
error ("Usage: AceDBObject:GetNamespace(name): 'name' - namespace does not exist.", 2)
end
if not self.children then self.children = {} end
return self.children[name]
end
--[[-------------------------------------------------------------------------
AceDB Exposed Methods
---------------------------------------------------------------------------]]
--- Creates a new database object that can be used to handle database settings and profiles.
-- By default, an empty DB is created, using a character specific profile.
--
-- You can override the default profile used by passing any profile name as the third argument,
-- or by passing //true// as the third argument to use a globally shared profile called "Default".
--
-- Note that there is no token replacement in the default profile name, passing a defaultProfile as "char"
-- will use a profile named "char", and not a character-specific profile.
-- @param tbl The name of variable, or table to use for the database
-- @param defaults A table of database defaults
-- @param defaultProfile The name of the default profile. If not set, a character specific profile will be used as the default.
-- You can also pass //true// to use a shared global profile called "Default".
-- @usage
-- -- Create an empty DB using a character-specific default profile.
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB")
-- @usage
-- -- Create a DB using defaults and using a shared default profile
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
function AceDB:New(tbl, defaults, defaultProfile)
if type(tbl) == "string" then
local name = tbl
tbl = _G[name]
if not tbl then
tbl = {}
_G[name] = tbl
end
end
if type(tbl) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected.", 2)
end
if defaults and type(defaults) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected.", 2)
end
if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected.", 2)
end
return initdb(tbl, defaults, defaultProfile)
end
-- upgrade existing databases
for db in pairs(AceDB.db_registry) do
if not db.parent then
for name,func in pairs(DBObjectLib) do
db[name] = func
end
else
db.RegisterDefaults = DBObjectLib.RegisterDefaults
db.ResetProfile = DBObjectLib.ResetProfile
end
end
| mit |
zain211/zain.aliraqex | libs/dateparser.lua | 114 | 6213 | local difftime, time, date = os.difftime, os.time, os.date
local format = string.format
local tremove, tinsert = table.remove, table.insert
local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable
local dateparser={}
--we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore.
local unix_timestamp
do
local now = time()
local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now)))
unix_timestamp = function(t, offset_sec)
local success, improper_time = pcall(time, t)
if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end
return improper_time - local_UTC_offset_sec - offset_sec
end
end
local formats = {} -- format names
local format_func = setmetatable({}, {__mode='v'}) --format functions
---register a date format parsing function
function dateparser.register_format(format_name, format_function)
if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end
local found
for i, f in ipairs(format_func) do --for ordering
if f==format_function then
found=true
break
end
end
if not found then
tinsert(format_func, format_function)
end
formats[format_name] = format_function
return true
end
---register a date format parsing function
function dateparser.unregister_format(format_name)
if type(format_name)~="string" then return nil, "format name must be a string" end
formats[format_name]=nil
end
---return the function responsible for handling format_name date strings
function dateparser.get_format_function(format_name)
return formats[format_name] or nil, ("format %s not registered"):format(format_name)
end
---try to parse date string
--@param str date string
--@param date_format optional date format name, if known
--@return unix timestamp if str can be parsed; nil, error otherwise.
function dateparser.parse(str, date_format)
local success, res, err
if date_format then
if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end
success, res = pcall(formats[date_format], str)
else
for i, func in ipairs(format_func) do
success, res = pcall(func, str)
if success and res then return res end
end
end
return success and res
end
dateparser.register_format('W3CDTF', function(rest)
local year, day_of_year, month, day, week
local hour, minute, second, second_fraction, offset_hours
local alt_rest
year, rest = rest:match("^(%d%d%d%d)%-?(.*)$")
day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$")
if day_of_year then rest=alt_rest end
month, rest = rest:match("^(%d%d)%-?(.*)$")
day, rest = rest:match("^(%d%d)(.*)$")
if #rest>0 then
rest = rest:match("^T(.*)$")
hour, rest = rest:match("^([0-2][0-9]):?(.*)$")
minute, rest = rest:match("^([0-6][0-9]):?(.*)$")
second, rest = rest:match("^([0-6][0-9])(.*)$")
second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$")
if second_fraction then
rest=alt_rest
end
if rest=="Z" then
rest=""
offset_hours=0
else
local sign, offset_h, offset_m
sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$")
local offset_m, alt_rest = rest:match("^(%d%d)(.*)$")
if offset_m then rest=alt_rest end
offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 then return nil end
end
year = tonumber(year)
local d = {
year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))),
month = tonumber(month) or 1,
day = tonumber(day) or 1,
hour = tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
local t = unix_timestamp(d, (offset_hours or 0) * 3600)
if second_fraction then
return t + tonumber("0."..second_fraction)
else
return t
end
end)
do
local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/
A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9,
K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5,
S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12,
Z = 0,
EST = -5, EDT = -4, CST = -6, CDT = -5,
MST = -7, MDT = -6, PST = -8, PDT = -7,
GMT = 0, UT = 0, UTC = 0
}
local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12}
dateparser.register_format('RFC2822', function(rest)
local year, month, day, day_of_year, week_of_year, weekday
local hour, minute, second, second_fraction, offset_hours
local alt_rest
weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$")
if weekday then rest=alt_rest end
day, rest=rest:match("^(%d%d?)%s+(.*)$")
month, rest=rest:match("^(%w%w%w)%s+(.*)$")
month = month_val[month]
year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$")
hour, rest = rest:match("^(%d%d?):(.*)$")
minute, rest = rest:match("^(%d%d?)(.*)$")
second, alt_rest = rest:match("^:(%d%d)(.*)$")
if second then rest = alt_rest end
local tz, offset_sign, offset_h, offset_m
tz, alt_rest = rest:match("^%s+(%u+)(.*)$")
if tz then
rest = alt_rest
offset_hours = tz_table[tz]
else
offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$")
offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 or not (year and day and month and hour and minute) then
return nil
end
year = tonumber(year)
local d = {
year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))),
month = month,
day = tonumber(day),
hour= tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
return unix_timestamp(d, offset_hours * 3600)
end)
end
dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough
dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF
return dateparser
| gpl-2.0 |
CarabusX/Zero-K | effects/gundam_mainmegapartgun.lua | 26 | 2945 | -- mainmegapartgun
return {
["mainmegapartgun"] = {
dirt = {
count = 4,
ground = true,
properties = {
alphafalloff = 2,
alwaysvisible = true,
color = [[0.2, 0.1, 0.05]],
pos = [[r-10 r10, 0, r-10 r10]],
size = 20,
speed = [[r1.5 r-1.5, 2, r1.5 r-1.5]],
},
},
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 0.5,
circlegrowth = 8,
flashalpha = 0.9,
flashsize = 120,
ground = true,
ttl = 17,
water = true,
color = {
[1] = 1,
[2] = 0.30000001192093,
[3] = 0.5,
},
},
pillar = {
air = true,
class = [[heatcloud]],
count = 3,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 15,
heatfalloff = 2.5,
maxheat = 15,
pos = [[0,0 i5, 0]],
size = 90,
sizegrowth = -11,
speed = [[0, 10, 0]],
texture = [[pinknovaexplo]],
},
},
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.2,
alwaysvisible = true,
colormap = [[1.0 0.0 1.0 0.04 0.5 0.0 0.5 0.01 0.1 0.1 0.1 0.01]],
directional = false,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.005, 0]],
numparticles = 40,
particlelife = 5,
particlelifespread = 16,
particlesize = 20,
particlesizespread = 0,
particlespeed = 19,
particlespeedspread = 4,
pos = [[0, 2, 0]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[randdots]],
useairlos = false,
},
},
pop = {
air = true,
class = [[heatcloud]],
count = 1,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 0.5,
maxheat = 15,
pos = [[r-2 r2, 5, r-2 r2]],
size = 90,
sizegrowth = 0.9,
speed = [[0, 1 0, 0]],
texture = [[pinknovaexplo]],
},
},
},
}
| gpl-2.0 |
rafael/kong | spec/integration/admin_api/kong_routes_spec.lua | 20 | 2623 | local json = require "cjson"
local http_client = require "kong.tools.http_client"
local spec_helper = require "spec.spec_helpers"
local utils = require "kong.tools.utils"
describe("Admin API", function()
setup(function()
spec_helper.prepare_db()
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
describe("Kong routes", function()
describe("/", function()
local constants = require "kong.constants"
it("should return Kong's version and a welcome message", function()
local response, status = http_client.get(spec_helper.API_URL)
assert.are.equal(200, status)
local body = json.decode(response)
assert.truthy(body.version)
assert.truthy(body.tagline)
assert.are.same(constants.VERSION, body.version)
end)
it("should have a Server header", function()
local _, status, headers = http_client.get(spec_helper.API_URL)
assert.are.same(200, status)
assert.are.same(string.format("%s/%s", constants.NAME, constants.VERSION), headers.server)
assert.falsy(headers.via) -- Via is only set for proxied requests
end)
it("should return method not allowed", function()
local res, status = http_client.post(spec_helper.API_URL)
assert.are.same(405, status)
assert.are.same("Method not allowed", json.decode(res).message)
local res, status = http_client.delete(spec_helper.API_URL)
assert.are.same(405, status)
assert.are.same("Method not allowed", json.decode(res).message)
local res, status = http_client.put(spec_helper.API_URL)
assert.are.same(405, status)
assert.are.same("Method not allowed", json.decode(res).message)
local res, status = http_client.patch(spec_helper.API_URL)
assert.are.same(405, status)
assert.are.same("Method not allowed", json.decode(res).message)
end)
end)
end)
describe("/status", function()
it("should return status information", function()
local response, status = http_client.get(spec_helper.API_URL.."/status")
assert.are.equal(200, status)
local body = json.decode(response)
assert.truthy(body)
assert.are.equal(7, utils.table_size(body))
assert.truthy(body.connections_accepted)
assert.truthy(body.connections_active)
assert.truthy(body.connections_handled)
assert.truthy(body.connections_reading)
assert.truthy(body.connections_writing)
assert.truthy(body.connections_waiting)
assert.truthy(body.total_requests)
end)
end)
end)
| apache-2.0 |
TideSofDarK/DotaCraft | game/dota_addons/dotacraft/scripts/vscripts/units/undead/ghoul.lua | 1 | 6096 | require('units/undead/meat_wagon')
function cannibalize(keys)
local caster = keys.caster
local ability = keys.ability
local RADIUS = ability:GetSpecialValueFor("search_radius")
-- find all dota creatures within radius
local targets = Entities:FindAllByNameWithin("npc_dota_creature", caster:GetAbsOrigin(), RADIUS)
if caster:GetHealth() == caster:GetMaxHealth() then
caster:Stop()
return
end
for k,corpse in pairs(targets) do
local abilitylevel = ability:GetLevel()
local spawnlocation = corpse:GetAbsOrigin()
-- if corpse is on the floor
if not corpse.being_eaten then
-- if body on floor
if corpse.corpse_expiration ~= nil then
--print("actual corpse found")
corpse.being_eaten = true
keys.ability.corpse = corpse
ToggleOn(keys.ability)
keys.ability:ApplyDataDrivenModifier(caster, caster, "modifier_cannibalize_properties", nil)
search_cannibalize(keys)
return
end
-- if meatwagon and has stacks
if corpse:GetUnitName() == "undead_meat_wagon" and corpse:GetModifierStackCount("modifier_corpses", corpse) > 0 and caster:GetPlayerOwnerID() == corpse:GetPlayerOwnerID() then
local StackCount = corpse:GetModifierStackCount("modifier_corpses", corpse)
if StackCount > 0 then
--print("meatwagon found")
-- save corpse in keys so that it can be used to remove stackcount and generate body
keys.ability.corpse = corpse
-- save new corpse in keys
keys.ability.corpse = drop_single_corpse(keys)
-- toggle and cast eat
ToggleOn(keys.ability)
keys.ability:ApplyDataDrivenModifier(caster, caster, "modifier_cannibalize_properties", nil)
search_cannibalize(keys)
return
end
end
end
end
end
-- count will be set to 0 if it's a corpse, otherwise it will correlate to the StackCount
-- IsRealCorpse is to determine whether it's a catapult or actual body on the floor
-- corpse target is stored on caster under caster.corpseTarget
function search_cannibalize(keys)
local corpse = keys.ability.corpse
local caster = keys.caster
--print("moving to food")
keys.ability.MoveToFood = Timers:CreateTimer(caster:GetEntityIndex().."_cannibalizing", {
callback = function()
if not IsValidEntity(corpse) and not IsValidEntity(caster) then
return
end
local casterposition = Vector(caster:GetAbsOrigin().x, caster:GetAbsOrigin().y)
local corpseposition = Vector(corpse:GetAbsOrigin().x, corpse:GetAbsOrigin().y)
--local distance = UnitPosition - GoalPosition
local CalcDistance = (corpseposition - casterposition):Length2D()
if CalcDistance >= 150 then
caster:MoveToPosition(corpse:GetAbsOrigin())
elseif CalcDistance < 150 then
--print("close enough to eat corpse")
caster:Stop()
keys.ability:ApplyDataDrivenModifier(caster, caster, "modifier_cannibalize", nil)
eating(keys)
return
end
return 0.25
end})
end
function eating (keys)
local ability = keys.ability
local corpse = keys.ability.corpse
local caster = keys.caster
local HEALTH_GAIN = keys.ability:GetSpecialValueFor("health_per_second")
-- set corpse flags
corpse.volumeLeft = 33
corpse.corpse_expiration = nil
ability.eatingTimer = Timers:CreateTimer(1, function()
--print(corpse.volumeLeft)
if not IsValidEntity(corpse) and not IsValidEntity(caster) then
return
end
if corpse.volumeLeft ~= 0 then -- if the volume is not equal to 0 then remove a second
corpse.volumeLeft = corpse.volumeLeft - 1
else -- if 0 or full hp
stop_cannibalize(keys)
return
end
caster:SetHealth(caster:GetHealth() + HEALTH_GAIN)
caster:StartGesture(ACT_DOTA_ATTACK)
local particle
Timers:CreateTimer(0.2, function()
if IsValidEntity(corpse) then
particle = ParticleManager:CreateParticle("particles/items2_fx/soul_ring_blood.vpcf", 2, corpse)
ParticleManager:SetParticleControl(particle, 0, corpse:GetAbsOrigin() - Vector(0,0,70))
end
end)
Timers:CreateTimer(0.9, function() if IsValidEntity(corpse) then ParticleManager:DestroyParticle(particle, true) end end)
--if full hp
if caster:GetMaxHealth() == caster:GetHealth() or not IsValidEntity(corpse) then
stop_cannibalize(keys)
return
end
return 1
end)
end
-- called if units orders, this stops the current cannibalize instantly, or leaves the body if
function stop_cannibalize(keys)
--print("On Order")
if not IsValidEntity(keys.ability.corpse) then
return
end
local ability = keys.ability
local corpse = keys.ability.corpse
local count = keys.ability.corpse.count
local caster = keys.caster
local StackCount = corpse:GetModifierStackCount("modifier_corpses", corpse)
-- stop animation, and toggle off ability
caster:Stop()
caster:RemoveGesture(ACT_DOTA_ATTACK)
if keys.ability:GetToggleState() then
ToggleOff(keys.ability)
end
-- remove timers if found
if ability.MoveToFood ~= nil then
--print("[GHOUL STOP TIMER] moving to food")
Timers:RemoveTimer(ability.MoveToFood)
end
if ability.eatingTimer ~= nil then
--print("[GHOUL STOP TIMER] stop eating")
Timers:RemoveTimer(ability.eatingTimer)
end
-- remove modifiers if found
if caster:FindModifierByName("modifier_cannibalize") then
caster:RemoveModifierByName("modifier_cannibalize")
end
if caster:FindModifierByName("modifier_cannibalize_properties") then
caster:RemoveModifierByName("modifier_cannibalize_properties")
end
if corpse.volumeLeft == nil or corpse.volumeLeft == 33 then
corpse.being_eaten = false
else
-- if the corpse is not equal to nil then it's a meat wagon
if not corpse.meatwagon then
corpse.no_corpse = true
corpse:RemoveSelf()
else
corpse:SetModifierStackCount("modifier_corpses", corpse, StackCount - 1)
corpse.volumeLeft[count] = nil
end
end
end
function frenzy ( keys )
local caster = keys.caster
local base_attack_time = caster:GetBaseAttackTime()
local attack_speed_bonus = keys.ability:GetSpecialValueFor("attack_speed_bonus")
caster:SetBaseAttackTime(base_attack_time - attack_speed_bonus)
end | gpl-3.0 |
kbara/snabb | lib/ljsyscall/syscall/osx/syscalls.lua | 18 | 1899 | -- OSX specific syscalls
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local abi = require "syscall.abi"
return function(S, hh, c, C, types)
local ret64, retnum, retfd, retbool, retptr = hh.ret64, hh.retnum, hh.retfd, hh.retbool, hh.retptr
local ffi = require "ffi"
local errno = ffi.errno
local h = require "syscall.helpers"
local istype, mktype, getfd = h.istype, h.mktype, h.getfd
local t, pt, s = types.t, types.pt, types.s
-- TODO lutimes is implemented using setattrlist(2) in OSX
function S.grantpt(fd) return S.ioctl(fd, "TIOCPTYGRANT") end
function S.unlockpt(fd) return S.ioctl(fd, "TIOCPTYUNLK") end
function S.ptsname(fd)
local buf = t.buffer(128)
local ok, err = S.ioctl(fd, "TIOCPTYGNAME", buf)
if not ok then return nil, err end
return ffi.string(buf)
end
function S.mach_absolute_time() return C.mach_absolute_time() end
function S.mach_task_self() return C.mach_task_self_ end
function S.mach_host_self() return C.mach_host_self() end
function S.mach_port_deallocate(task, name) return retbool(C.mach_port_deallocate(task or S.mach_task_self(), name)) end
function S.host_get_clock_service(host, clock_id, clock_serv)
clock_serv = clock_serv or t.clock_serv1()
local ok, err = C.host_get_clock_service(host or S.mach_host_self(), c.CLOCKTYPE[clock_id or "SYSTEM"], clock_serv)
if not ok then return nil, err end
return clock_serv[0]
end
-- TODO when mach ports do gc, can add 'clock_serv or S.host_get_clock_service()'
function S.clock_get_time(clock_serv, cur_time)
cur_time = cur_time or t.mach_timespec()
local ok, err = C.clock_get_time(clock_serv, cur_time)
if not ok then return nil, err end
return cur_time
end
return S
end
| apache-2.0 |
kbara/snabb | src/apps/lwaftr/fragmentv4_test.lua | 3 | 17270 | -- Allow both importing this script as a module and running as a script
if type((...)) == "string" then module(..., package.seeall) end
local constants = require("apps.lwaftr.constants")
local fragmentv4 = require("apps.lwaftr.fragmentv4")
local fragv4_h = require("apps.lwaftr.fragmentv4_hardened")
local eth_proto = require("lib.protocol.ethernet")
local ip4_proto = require("lib.protocol.ipv4")
local lwutil = require("apps.lwaftr.lwutil")
local packet = require("core.packet")
local band = require("bit").band
local ffi = require("ffi")
local rd16, wr16, get_ihl_from_offset = lwutil.rd16, lwutil.wr16, lwutil.get_ihl_from_offset
--
-- Returns a new packet, which contains an Ethernet frame, with an IPv4 header,
-- followed by a payload of "payload_size" random bytes.
--
local function make_ipv4_packet(payload_size, vlan_id)
local eth_size = eth_proto:sizeof()
if vlan_id then
eth_size = eth_size + 4 -- VLAN tag takes 4 extra bytes
end
local pkt = packet.allocate()
pkt.length = eth_size + ip4_proto:sizeof() + payload_size
local eth_header = eth_proto:new_from_mem(pkt.data, pkt.length)
local ip4_header = ip4_proto:new_from_mem(pkt.data + eth_size,
pkt.length - eth_size)
assert(pkt.length == eth_size + ip4_header:sizeof() + payload_size)
-- Ethernet header. The leading bits of the MAC addresses are those for
-- "Intel Corp" devices, the rest are arbitrary.
eth_header:src(eth_proto:pton("5c:51:4f:8f:aa:ee"))
eth_header:dst(eth_proto:pton("5c:51:4f:8f:aa:ef"))
if vlan_id then
eth_header:type(constants.dotq_tpid)
wr16(pkt.data + eth_proto:sizeof(), vlan_id)
wr16(pkt.data + eth_proto:sizeof() + 2, constants.ethertype_ipv4)
else
eth_header:type(constants.ethertype_ipv4)
end
-- IPv4 header
ip4_header:ihl(ip4_header:sizeof() / 4)
ip4_header:dscp(0)
ip4_header:ecn(0)
ip4_header:total_length(ip4_header:sizeof() + payload_size)
ip4_header:id(0)
ip4_header:flags(0)
ip4_header:frag_off(0)
ip4_header:ttl(15)
ip4_header:protocol(0xFF)
ip4_header:src(ip4_proto:pton("192.168.10.10"))
ip4_header:dst(ip4_proto:pton("192.168.10.20"))
ip4_header:checksum()
-- We do not fill up the rest of the packet: random contents works fine
-- because we are testing IP fragmentation, so there's no need to care
-- about upper layers.
return pkt
end
local function eth_header_size(pkt)
local eth_size = eth_proto:sizeof()
local eth_header = eth_proto:new_from_mem(pkt.data, pkt.length)
if eth_header:type() == constants.dotq_tpid then
return eth_size + 4 -- Packet has VLAN tagging
else
return eth_size
end
end
local function pkt_payload_size(pkt)
assert(pkt.length >= (eth_proto:sizeof() + ip4_proto:sizeof()))
local eth_size = eth_header_size(pkt)
local ip4_header = ip4_proto:new_from_mem(pkt.data + eth_size,
pkt.length - eth_size)
local total_length = ip4_header:total_length()
local ihl = ip4_header:ihl() * 4
assert(ihl == get_ihl_from_offset(pkt, eth_size))
assert(ihl == ip4_header:sizeof())
assert(total_length - ihl >= 0)
assert(total_length == pkt.length - eth_size)
return total_length - ihl
end
local function pkt_frag_offset(pkt)
assert(pkt.length >= (eth_proto:sizeof() + ip4_proto:sizeof()))
local eth_size = eth_header_size(pkt)
local ip4_header = ip4_proto:new_from_mem(pkt.data + eth_size,
pkt.length - eth_size)
return ip4_header:frag_off() * 8
end
local function pkt_total_length(pkt)
assert(pkt.length >= (eth_proto:sizeof() + ip4_proto:sizeof()))
local eth_size = eth_header_size(pkt)
local ip4_header = ip4_proto:new_from_mem(pkt.data + eth_size,
pkt.length - eth_size)
return ip4_header:total_length()
end
--
-- Checks that "frag_pkt" is a valid fragment of the "orig_pkt" packet.
--
local function check_packet_fragment(orig_pkt, frag_pkt, is_last_fragment)
-- Ethernet fields
local orig_hdr = eth_proto:new_from_mem(orig_pkt.data, orig_pkt.length)
local frag_hdr = eth_proto:new_from_mem(frag_pkt.data, frag_pkt.length)
assert(orig_hdr:src_eq(frag_hdr:src()))
assert(orig_hdr:dst_eq(frag_hdr:dst()))
assert(orig_hdr:type() == frag_hdr:type())
-- Check for VLAN tagging and check the additional fields
local eth_size = eth_proto:sizeof()
if orig_hdr:type() == constants.dotq_tpid then
assert(rd16(orig_pkt.data + eth_size) == rd16(frag_pkt.data + eth_size)) -- VLAN id
assert(rd16(orig_pkt.data + eth_size + 2) == rd16(frag_pkt.data + eth_size + 2)) -- Protocol
eth_size = eth_size + 4
end
-- IPv4 fields
orig_hdr = ip4_proto:new_from_mem(orig_pkt.data + eth_size,
orig_pkt.length - eth_size)
frag_hdr = ip4_proto:new_from_mem(frag_pkt.data + eth_size,
frag_pkt.length - eth_size)
assert(orig_hdr:ihl() == frag_hdr:ihl())
assert(orig_hdr:dscp() == frag_hdr:dscp())
assert(orig_hdr:ecn() == frag_hdr:ecn())
assert(orig_hdr:ttl() == frag_hdr:ttl())
assert(orig_hdr:protocol() == frag_hdr:protocol())
assert(orig_hdr:src_eq(frag_hdr:src()))
assert(orig_hdr:dst_eq(frag_hdr:dst()))
assert(pkt_payload_size(frag_pkt) == frag_pkt.length - eth_size - ip4_proto:sizeof())
if is_last_fragment then
assert(band(frag_hdr:flags(), 0x1) == 0x0)
else
assert(band(frag_hdr:flags(), 0x1) == 0x1)
end
end
function test_payload_1200_mtu_1500()
print("test: payload=1200 mtu=1500")
local pkt = assert(make_ipv4_packet(1200))
local code, result = fragmentv4.fragment(pkt, 1500)
assert(code == fragmentv4.FRAGMENT_UNNEEDED)
assert(pkt == result)
end
function test_payload_1200_mtu_1000()
print("test: payload=1200 mtu=1000")
local pkt = assert(make_ipv4_packet(1200))
-- Keep a copy of the packet, for comparisons
local orig_pkt = packet.clone(pkt)
assert(pkt.length > 1200, "packet short than payload size")
local ehs = constants.ethernet_header_size
local code, result = fragmentv4.fragment(pkt, 1000 - ehs)
assert(code == fragmentv4.FRAGMENT_OK)
assert(#result == 2, "fragmentation returned " .. #result .. " packets (2 expected)")
for i = 1, #result do
assert(result[i].length <= 1000, "packet " .. i .. " longer than MTU")
local is_last = (i == #result)
check_packet_fragment(orig_pkt, result[i], is_last)
end
assert(pkt_payload_size(result[1]) + pkt_payload_size(result[2]) == 1200)
assert(pkt_payload_size(result[1]) == pkt_frag_offset(result[2]))
end
function test_payload_1200_mtu_400()
print("test: payload=1200 mtu=400")
local pkt = assert(make_ipv4_packet(1200))
-- Keep a copy of the packet, for comparisons
local orig_pkt = packet.clone(pkt)
local ehs = constants.ethernet_header_size
local code, result = fragmentv4.fragment(pkt, 400 - ehs)
assert(code == fragmentv4.FRAGMENT_OK)
assert(#result == 4,
"fragmentation returned " .. #result .. " packets (4 expected)")
for i = 1, #result do
assert(result[i].length <= 1000, "packet " .. i .. " longer than MTU")
local is_last = (i == #result)
check_packet_fragment(orig_pkt, result[i], is_last)
end
assert(pkt_payload_size(result[1]) + pkt_payload_size(result[2]) +
pkt_payload_size(result[3]) + pkt_payload_size(result[4]) == 1200)
assert(pkt_payload_size(result[1]) == pkt_frag_offset(result[2]))
assert(pkt_payload_size(result[1]) + pkt_payload_size(result[2]) ==
pkt_frag_offset(result[3]))
assert(pkt_payload_size(result[1]) + pkt_payload_size(result[2]) +
pkt_payload_size(result[3]) == pkt_frag_offset(result[4]))
end
function test_dont_fragment_flag()
print("test: packet with \"don't fragment\" flag")
-- Try to fragment a packet with the "don't fragment" flag set
local pkt = assert(make_ipv4_packet(1200))
local ip4_header = ip4_proto:new_from_mem(pkt.data + eth_proto:sizeof(),
pkt.length - eth_proto:sizeof())
ip4_header:flags(0x2) -- Set "don't fragment"
local code, result = fragmentv4.fragment(pkt, 500)
assert(code == fragmentv4.FRAGMENT_FORBIDDEN)
assert(type(result) == "nil")
end
local pattern_fill, pattern_check = (function ()
local pattern = { 0xCC, 0xAA, 0xFF, 0xEE, 0xBB, 0x11, 0xDD }
local function fill(array, length)
for i = 0, length-1 do
array[i] = pattern[(i % #pattern) + 1]
end
end
local function check(array, length)
for i = 0, length-1 do
assert(array[i], pattern[(i % #pattern) + 1], "pos: " .. i)
end
end
return fill, check
end)()
function test_reassemble_pattern_fragments()
print("test: length=1046 mtu=520 + reassembly")
local pkt = make_ipv4_packet(1046 - ip4_proto:sizeof() - eth_proto:sizeof())
pattern_fill(pkt.data + ip4_proto:sizeof() + eth_proto:sizeof(),
pkt.length - ip4_proto:sizeof() - eth_proto:sizeof())
local code, result = fragmentv4.fragment(pkt, 520)
assert(code == fragmentv4.FRAGMENT_OK)
assert(#result == 3)
assert(pkt_payload_size(result[1]) + pkt_payload_size(result[2]) +
pkt_payload_size(result[3]) == 1046 - ip4_proto:sizeof() - eth_proto:sizeof())
local size = pkt_payload_size(result[1]) + pkt_payload_size(result[2]) + pkt_payload_size(result[3])
local data = ffi.new("uint8_t[?]", size)
for i = 1, #result do
local ih = get_ihl_from_offset(result[i], constants.ethernet_header_size)
ffi.copy(data + pkt_frag_offset(result[i]),
result[i].data + eth_proto:sizeof() + ih,
pkt_payload_size(result[i]))
end
pattern_check(data, size)
end
function test_reassemble_two_missing_fragments(vlan_id)
print("test: two fragments (one missing)")
local pkt = assert(make_ipv4_packet(1200), vlan_id)
local code, fragments = fragmentv4.fragment(pkt, 1000)
assert(code == fragmentv4.FRAGMENT_OK)
assert(#fragments == 2)
local frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[1])))
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[2])))
end
function test_reassemble_three_missing_fragments(vlan_id)
print("test: three fragments (one/two missing)")
local pkt = assert(make_ipv4_packet(1000))
local code, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
assert(code == fragmentv4.FRAGMENT_OK)
assert(#fragments == 3)
local frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[1])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[2])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[3])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[1])))
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[2])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[1])))
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[3])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[2])))
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[3])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[2])))
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[1])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[3])))
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[1])))
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
frag_table = fragv4_h.initialize_frag_table(20, 5)
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[2])))
assert(fragv4_h.FRAGMENT_MISSING ==
(fragv4_h.cache_fragment(frag_table, fragments[3])))
end
function test_reassemble_two(vlan_id)
print("test: payload=1200 mtu=1000")
local pkt = assert(make_ipv4_packet(1200), vlan_id)
assert(pkt.length > 1200, "packet shorter than payload size")
-- Keep a copy of the packet, for comparisons
local orig_pkt = packet.clone(pkt)
-- A single error above this can lead to packets being on the freelist twice...
assert(pkt ~= orig_pkt, "packets must be different")
local code, fragments = fragmentv4.fragment(packet.clone(orig_pkt), 1000)
assert(code == fragmentv4.FRAGMENT_OK)
assert(#fragments == 2)
assert(fragments[1].length ~= 0, "fragment[1] length must not be 0")
assert(fragments[2].length ~= 0, "fragment[2] length must not be 0")
local function try(f)
local frag_table = fragv4_h.initialize_frag_table(20, 5)
local code, pkt
for i=1,#f do
code, pkt = fragv4_h.cache_fragment(frag_table, f[i])
end
assert(code == fragv4_h.REASSEMBLY_OK, "returned: " .. code)
assert(pkt.length == orig_pkt.length)
for i = 1, pkt.length do
if i ~= 24 and i ~= 25 then
assert(pkt.data[i] == orig_pkt.data[i],
"byte["..i.."] expected="..orig_pkt.data[i].." got="..pkt.data[i])
end
end
end
try { fragments[1], fragments[2] }
_, fragments = fragmentv4.fragment(packet.clone(orig_pkt), 1000)
assert(fragments[1].length ~= 0, "fragment[1] length must not be 0")
assert(fragments[2].length ~= 0, "fragment[2] length must not be 0")
try { fragments[2], fragments[1] }
end
function test_reassemble_three(vlan_id)
print("test: payload=1000 mtu=400")
local pkt = assert(make_ipv4_packet(1000), vlan_id)
-- Keep a copy of the packet, for comparisons
local orig_pkt = packet.clone(pkt)
local code, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
assert(code == fragmentv4.FRAGMENT_OK)
assert(#fragments == 3)
assert(orig_pkt.length == 1034, "wtf")
local function try(f)
local frag_table = fragv4_h.initialize_frag_table(20, 5)
local code, pkt
for i=1,#f do
code, pkt = fragv4_h.cache_fragment(frag_table, f[i])
end
assert(code == fragv4_h.REASSEMBLY_OK, "returned: " .. code)
assert(pkt.length == orig_pkt.length)
for i = 1, pkt.length do
if i ~= 24 and i ~= 25 then
assert(pkt.data[i] == orig_pkt.data[i],
"byte["..i.."] expected="..orig_pkt.data[i].." got="..pkt.data[i])
end
end
end
try { fragments[1], fragments[2], fragments[3] }
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
try { fragments[2], fragments[3], fragments[1] }
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
try { fragments[3], fragments[1], fragments[2] }
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
try { fragments[3], fragments[2], fragments[1] }
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
try { fragments[2], fragments[1], fragments[3] }
_, fragments = fragmentv4.fragment(packet.clone(pkt), 400)
try { fragments[1], fragments[3], fragments[2] }
end
function selftest()
print("test: lwaftr.fragmentv4.fragment_ipv4")
test_payload_1200_mtu_1500()
test_payload_1200_mtu_1000()
test_payload_1200_mtu_400()
test_dont_fragment_flag()
test_reassemble_pattern_fragments()
local function testall(vlan_id)
local suffix = " (no vlan tag)"
if vlan_id then
suffix = " (vlan id=" .. vlan_id .. ")"
end
print("test: lwaftr.fragv4_h.cache_fragment_ipv4" .. suffix)
test_reassemble_two_missing_fragments(vlan_id)
test_reassemble_three_missing_fragments(vlan_id)
test_reassemble_two(vlan_id)
test_reassemble_three(vlan_id)
end
testall(nil)
testall(42)
end
-- Run tests when being invoked as a script from the command line.
if type((...)) == "nil" then selftest() end
| apache-2.0 |
focusworld/nn | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
delram/seedup1 | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
zakariaRobot/TeleSeed | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
mattyx14/otxserver | data/monster/raids/arachir_the_ancient_one.lua | 2 | 3416 | local mType = Game.createMonsterType("Arachir The Ancient One")
local monster = {}
monster.description = "Arachir The Ancient One"
monster.experience = 1800
monster.outfit = {
lookType = 287,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 1600
monster.maxHealth = 1600
monster.race = "undead"
monster.corpse = 8109
monster.speed = 286
monster.manaCost = 0
monster.changeTarget = {
interval = 5000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.summon = {
maxSummons = 2,
summons = {
{name = "Lich", chance = 100, interval = 9000, count = 2},
}
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "I was the shadow that haunted the cradle of humanity!", yell = false},
{text = "I exist since eons and you want to defy me?", yell = false},
{text = "Can you feel the passage of time, mortal?", yell = false},
{text = "Your worthles existence will nourish something greater!", yell = false}
}
monster.loot = {
{id = 7416, chance = 1200}, -- bloody edge
{id = 236, chance = 10000}, -- strong health potion
{id = 3114, chance = 10000}, -- skull
{id = 3031, chance = 100000, maxCount = 98}, -- gold coin
{id = 8192, chance = 100000}, -- vampire lord token
{id = 3035, chance = 50000, maxCount = 5}, -- platinum coin
{id = 3434, chance = 6300}, -- vampire shield
{id = 3027, chance = 8980} -- black pearl
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, skill = 70, attack = 95},
{name ="combat", interval = 9000, chance = 100, type = COMBAT_DEATHDAMAGE, minDamage = -120, maxDamage = -300, radius = 3, effect = CONST_ME_MORTAREA, target = false},
{name ="combat", interval = 1000, chance = 12, type = COMBAT_DEATHDAMAGE, minDamage = 0, maxDamage = -120, shootEffect = CONST_ANI_SUDDENDEATH, effect = CONST_ME_MORTAREA, target = true}
}
monster.defenses = {
defense = 30,
armor = 30,
{name ="combat", interval = 1000, chance = 12, type = COMBAT_HEALING, minDamage = 100, maxDamage = 235, effect = CONST_ME_MAGIC_BLUE, target = false},
{name ="invisible", interval = 3000, chance = 25, effect = CONST_ME_MAGIC_BLUE},
{name ="outfit", interval = 4500, chance = 30, target = false, duration = 4000, outfitMonster = "bat"}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 20},
{type = COMBAT_ENERGYDAMAGE, percent = 0},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = -10},
{type = COMBAT_LIFEDRAIN, percent = 100},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = -15},
{type = COMBAT_DEATHDAMAGE , percent = 100}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
mattyx14/otxserver | data/monster/humans/pirate_buccaneer.lua | 2 | 3122 | local mType = Game.createMonsterType("Pirate Buccaneer")
local monster = {}
monster.description = "a pirate buccaneer"
monster.experience = 250
monster.outfit = {
lookType = 97,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 249
monster.Bestiary = {
class = "Human",
race = BESTY_RACE_HUMAN,
toKill = 1000,
FirstUnlock = 50,
SecondUnlock = 500,
CharmsPoints = 25,
Stars = 3,
Occurrence = 0,
Locations = "Nargor, Tyrsung (on the ship), Yalahar (Foreign Quarter), Krailos Steppe."
}
monster.health = 425
monster.maxHealth = 425
monster.race = "blood"
monster.corpse = 18190
monster.speed = 218
monster.manaCost = 595
monster.changeTarget = {
interval = 4000,
chance = 15
}
monster.strategiesTarget = {
nearest = 100,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = true,
pushable = false,
rewardBoss = false,
illusionable = true,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 50,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "Give up!", yell = false},
{text = "Hiyaa", yell = false},
{text = "Plundeeeeer!", yell = false}
}
monster.loot = {
{id = 2920, chance = 10190}, -- torch
{name = "gold coin", chance = 67740, maxCount = 59},
{name = "worn leather boots", chance = 9900},
{name = "sabre", chance = 10100},
{name = "throwing knife", chance = 9000, maxCount = 5},
{name = "plate armor", chance = 1130},
{name = "battle shield", chance = 3850},
{id = 5090, chance = 1000}, -- treasure map
{name = "rum flask", chance = 120},
{id = 5792, chance = 40}, -- die
{name = "pirate backpack", chance = 430},
{name = "pirate shirt", chance = 1200},
{name = "hook", chance = 450},
{name = "eye patch", chance = 420},
{name = "peg leg", chance = 510},
{name = "strong health potion", chance = 670},
{name = "compass", chance = 9780}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -160},
{name ="combat", interval = 2000, chance = 20, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -100, range = 4, shootEffect = CONST_ANI_THROWINGKNIFE, target = false}
}
monster.defenses = {
defense = 30,
armor = 30
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = -5},
{type = COMBAT_ENERGYDAMAGE, percent = -5},
{type = COMBAT_EARTHDAMAGE, percent = 10},
{type = COMBAT_FIREDAMAGE, percent = -5},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = -5},
{type = COMBAT_HOLYDAMAGE , percent = 10},
{type = COMBAT_DEATHDAMAGE , percent = -5}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
DL-Benchmarks/DL-Benchmarks | torch/LeNet/lenet.lua | 1 | 4312 | -- Copyright (c) 2016 Robert Bosch LLC, USA.
-- All rights reserved.
--
-- This source code is licensed under the MIT license found in the
-- LICENSE file in the root directory of this source tree.
-- Timing of LeNet
require 'sys'
require 'nn'
require 'torch'
-- Initialize and Configure variables for LeNet benchmarking
collectgarbage()
torch.setdefaulttensortype('torch.FloatTensor')
function config()
local conf = {}
conf.image_width = 28
conf.batch_size = 64
conf.num_measures = 200
conf.num_dry_runs = 200
conf.mode = 'GPU' -- 'CPU' or 'GPU'
conf.num_threads = 12
return conf
end
local conf = config()
assert(conf.mode == 'GPU' or conf.mode == 'CPU', 'Only GPU or CPU mode supported for LeNet')
-- Import required packages for 'GPU' mode or set number of threads for 'CPU' mode
if (conf.mode == 'GPU') then
require 'cudnn'
require 'cutorch'
require 'cunn'
else
torch.setnumthreads(conf.num_threads)
end
-- Define the model for both CPU and GPU modes for our benchmarking
model = nn.Sequential()
if (conf.mode == 'GPU') then
model:add(cudnn.SpatialConvolution(1,20,5,5,1,1))
model:add(cudnn.SpatialMaxPooling(2,2,2,2))
model:add(cudnn.Tanh())
model:add(cudnn.SpatialConvolution(20,50,5,5,1,1))
model:add(cudnn.SpatialMaxPooling(2,2,2,2))
model:add(cudnn.Tanh())
model:add(nn.View(50*4*4))
model:add(nn.Linear(50*4*4,500))
model:add(cudnn.ReLU())
model:add(nn.Linear(500,10))
model:add(nn.LogSoftMax())
elseif (conf.mode == 'CPU') then
model:add(nn.SpatialConvolution(1,20,5,5,1,1))
model:add(nn.SpatialMaxPooling(2,2,2,2))
model:add(nn.Tanh())
model:add(nn.SpatialConvolution(20,50,5,5,1,1))
model:add(nn.SpatialMaxPooling(2,2,2,2))
model:add(nn.Tanh())
model:add(nn.View(50*4*4))
model:add(nn.Linear(50*4*4,500))
model:add(nn.ReLU())
model:add(nn.Linear(500,10))
model:add(nn.LogSoftMax())
end
-- Choose a loss function for the output
criterion = nn.ClassNLLCriterion()
-- Generate input image and label batch
local num_classes = 10
local inputs = torch.rand(conf.batch_size,1,conf.image_width,conf.image_width)
local targets = torch.ceil(torch.rand(conf.batch_size)*num_classes)
-- Initialize variables to gather forward and backward time
forward_time = torch.zeros(conf.num_measures)
backward_time = torch.zeros(conf.num_measures)
-- Move the model and data to GPU for the 'GPU' mode
if (conf.mode == 'GPU') then
cutorch.synchronize()
model = model:cuda()
criterion = criterion:cuda()
inputs = inputs:cuda()
targets = targets:cuda()
end
-- Loop through forward and backward passes for measuring time
for step=1,(conf.num_measures + conf.num_dry_runs) do
if (conf.mode == 'GPU') then
cutorch.synchronize()
end
if (step > conf.num_dry_runs) then
sys.tic()
model:forward(inputs)
if (conf.mode == 'GPU') then
cutorch.synchronize()
end
forward_time[step-conf.num_dry_runs] = sys.toc()
criterion:forward(model.output, targets)
sys.tic()
-- Calculate gradients w.r.t the different layers using a backpropagation step
model:backward(inputs, criterion:backward(model.output, targets))
if (conf.mode == 'GPU') then
cutorch.synchronize()
end
backward_time[step-conf.num_dry_runs] = sys.toc()
else
-- Dry runs
criterion:forward(model:forward(inputs), targets)
model:backward(inputs, criterion:backward(model.output, targets))
if (conf.mode == 'GPU') then
cutorch.synchronize()
end
end -- dry run switch
end -- for loop
-- Print mean and standard deviation of forward and backward times
print('Printing time taken for forward and backward model execution')
print('All times are for one pass with one batch')
print('Mode: ', conf.mode)
print('Tot. number of batch runs: ', conf.num_measures)
print('Number of dry runs: ', conf.num_dry_runs)
print('Batch size: ', conf.batch_size)
print(string.format('forward: %.5f +/- %.5f sec per batch', torch.mean(forward_time), torch.std(forward_time)))
print(string.format('gradient computation: %.5f +/- %.5f sec per batch', torch.mean(backward_time + forward_time), torch.std(backward_time + forward_time)))
| mit |
CarabusX/Zero-K | LuaUI/Widgets/unit_marker.lua | 4 | 4339 | function widget:GetInfo() return {
name = "Unit Marker Zero-K",
desc = "[v1.3.10] Marks spotted buildings of interest and commander corpse.",
author = "Sprung",
date = "2015-04-11",
license = "GNU GPL v2",
layer = -1,
enabled = true,
} end
local knownUnits = {}
local unitList = {}
local markingActive = false
if VFS.FileExists("LuaUI/Configs/unit_marker_local.lua", nil, VFS.RAW) then
unitList = VFS.Include("LuaUI/Configs/unit_marker_local.lua", nil, VFS.RAW)
else
unitList = VFS.Include("LuaUI/Configs/unit_marker.lua")
end
options_path = 'Settings/Interface/Unit Marker'
options_order = { 'enableAll', 'disableAll', 'unitslabel'}
options = {
enableAll = {
type='button',
name= "Enable All",
desc = "Marks all listed units.",
path = options_path .. "/Presets",
OnChange = function ()
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_mark")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud then
options[opt].value = true
end
end
for unitDefID,_ in pairs(unitList) do
unitList[unitDefID].active = true
end
if not markingActive then
widgetHandler:UpdateCallIn('UnitEnteredLos')
markingActive = true
end
end,
noHotkey = true,
},
disableAll = {
type='button',
name= "Disable All",
desc = "Mark nothing.",
path = options_path .. "/Presets",
OnChange = function ()
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_mark")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud then
options[opt].value = false
end
end
for unitDefID,_ in pairs(unitList) do
unitList[unitDefID].active = false
end
if markingActive then
widgetHandler:RemoveCallIn('UnitEnteredLos')
markingActive = false
end
end,
noHotkey = true,
},
unitslabel = {name = "unitslabel", type = 'label', value = "Individual Toggles", path = options_path},
}
for unitDefID,_ in pairs(unitList) do
local ud = (not unitDefID) or UnitDefs[unitDefID]
if ud then
options[ud.name .. "_mark"] = {
name = " " .. Spring.Utilities.GetHumanName(ud) or "",
type = 'bool',
value = false,
OnChange = function (self)
unitList[unitDefID].active = self.value
if self.value and not markingActive then
widgetHandler:UpdateCallIn('UnitEnteredLos')
markingActive = true
end
end,
noHotkey = true,
}
options_order[#options_order+1] = ud.name .. "_mark"
end
end
function widget:Initialize()
if not markingActive then
widgetHandler:RemoveCallIn("UnitEnteredLos")
end
if Spring.GetSpectatingState() then
widgetHandler:RemoveCallIn("UnitEnteredLos")
elseif markingActive then
widgetHandler:UpdateCallIn('UnitEnteredLos')
end
end
function widget:PlayerChanged ()
widget:Initialize ()
end
function widget:TeamDied ()
widget:Initialize ()
end
function widget:UnitEnteredLos (unitID, teamID)
if Spring.IsUnitAllied(unitID) or Spring.GetSpectatingState() then return end
local unitDefID = Spring.GetUnitDefID (unitID)
if not unitDefID then return end -- safety just in case
if unitList[unitDefID] and unitList[unitDefID].active and ((not knownUnits[unitID]) or (knownUnits[unitID] ~= unitDefID)) then
local x, y, z = Spring.GetUnitPosition(unitID)
local markerText = unitList[unitDefID].markerText or Spring.Utilities.GetHumanName(UnitDefs[unitDefID])
if not unitList[unitDefID].mark_each_appearance then
knownUnits[unitID] = unitDefID
end
if unitList[unitDefID].show_owner then
local _,playerID,_,isAI = Spring.GetTeamInfo(teamID, false)
local owner_name
if isAI then
local _,botName,_,botType = Spring.GetAIInfo(teamID)
owner_name = (botType or "AI") .." - " .. (botName or "unnamed")
else
owner_name = Spring.GetPlayerInfo(playerID, false) or "nobody"
end
markerText = markerText .. " (" .. owner_name .. ")"
end
local _, _, _, _, buildProgress = Spring.GetUnitHealth(unitID)
if buildProgress < 1 then
markerText = markerText .. " (" .. math.floor(100 * buildProgress) .. "%)"
end
Spring.MarkerAddPoint (x, y, z, markerText, true)
end
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
knownUnits[unitID] = nil
end
| gpl-2.0 |
mumuqz/luci | modules/luci-base/luasrc/sys/zoneinfo/tzoffset.lua | 11 | 4099 | -- Licensed to the public under the Apache License 2.0.
module "luci.sys.zoneinfo.tzoffset"
OFFSET = {
gmt = 0, -- GMT
eat = 10800, -- EAT
cet = 3600, -- CET
wat = 3600, -- WAT
cat = 7200, -- CAT
eet = 7200, -- EET
wet = 0, -- WET
sast = 7200, -- SAST
hst = -36000, -- HST
hdt = -32400, -- HDT
akst = -32400, -- AKST
akdt = -28800, -- AKDT
ast = -14400, -- AST
brt = -10800, -- BRT
art = -10800, -- ART
pyt = -14400, -- PYT
pyst = -10800, -- PYST
est = -18000, -- EST
cst = -21600, -- CST
cdt = -18000, -- CDT
amt = -14400, -- AMT
cot = -18000, -- COT
mst = -25200, -- MST
mdt = -21600, -- MDT
vet = -16200, -- VET
gft = -10800, -- GFT
pst = -28800, -- PST
pdt = -25200, -- PDT
act = -18000, -- ACT
wgt = -10800, -- WGT
wgst = -7200, -- WGST
ect = -18000, -- ECT
gyt = -14400, -- GYT
bot = -14400, -- BOT
pet = -18000, -- PET
pmst = -10800, -- PMST
pmdt = -7200, -- PMDT
uyt = -10800, -- UYT
fnt = -7200, -- FNT
srt = -10800, -- SRT
clt = -14400, -- CLT
clst = -10800, -- CLST
egt = -3600, -- EGT
egst = 0, -- EGST
nst = -12600, -- NST
ndt = -9000, -- NDT
awst = 28800, -- AWST
davt = 25200, -- DAVT
ddut = 36000, -- DDUT
mist = 39600, -- MIST
mawt = 18000, -- MAWT
nzst = 43200, -- NZST
nzdt = 46800, -- NZDT
rott = -10800, -- ROTT
syot = 10800, -- SYOT
utc = 0, -- UTC
vost = 21600, -- VOST
almt = 21600, -- ALMT
anat = 43200, -- ANAT
aqtt = 18000, -- AQTT
tmt = 18000, -- TMT
azt = 14400, -- AZT
ict = 25200, -- ICT
kgt = 21600, -- KGT
bnt = 28800, -- BNT
yakt = 32400, -- YAKT
chot = 28800, -- CHOT
chost = 32400, -- CHOST
ist = 19800, -- IST
bdt = 21600, -- BDT
tlt = 32400, -- TLT
gst = 14400, -- GST
tjt = 18000, -- TJT
hkt = 28800, -- HKT
hovt = 25200, -- HOVT
hovst = 28800, -- HOVST
irkt = 28800, -- IRKT
wib = 25200, -- WIB
wit = 32400, -- WIT
aft = 16200, -- AFT
pett = 43200, -- PETT
pkt = 18000, -- PKT
npt = 20700, -- NPT
krat = 25200, -- KRAT
myt = 28800, -- MYT
magt = 36000, -- MAGT
wita = 28800, -- WITA
pht = 28800, -- PHT
novt = 21600, -- NOVT
omst = 21600, -- OMST
orat = 18000, -- ORAT
kst = 30600, -- KST
qyzt = 21600, -- QYZT
mmt = 23400, -- MMT
sakt = 39600, -- SAKT
uzt = 18000, -- UZT
sgt = 28800, -- SGT
sret = 39600, -- SRET
get = 14400, -- GET
irst = 12600, -- IRST
irdt = 16200, -- IRDT
btt = 21600, -- BTT
jst = 32400, -- JST
ulat = 28800, -- ULAT
ulast = 32400, -- ULAST
xjt = 21600, -- XJT
vlat = 36000, -- VLAT
yekt = 18000, -- YEKT
azot = -3600, -- AZOT
azost = 0, -- AZOST
cvt = -3600, -- CVT
fkst = -10800, -- FKST
acst = 34200, -- ACST
acdt = 37800, -- ACDT
aest = 36000, -- AEST
acwst = 31500, -- ACWST
lhst = 37800, -- LHST
lhdt = 39600, -- LHDT
msk = 10800, -- MSK
samt = 14400, -- SAMT
iot = 21600, -- IOT
cxt = 25200, -- CXT
cct = 23400, -- CCT
tft = 18000, -- TFT
sct = 14400, -- SCT
mvt = 18000, -- MVT
mut = 14400, -- MUT
ret = 14400, -- RET
wsst = 46800, -- WSST
wsdt = 50400, -- WSDT
bst = 39600, -- BST
chast = 45900, -- CHAST
chadt = 49500, -- CHADT
chut = 36000, -- CHUT
east = -21600, -- EAST
easst = -18000, -- EASST
vut = 39600, -- VUT
phot = 46800, -- PHOT
tkt = 46800, -- TKT
fjt = 43200, -- FJT
fjst = 46800, -- FJST
tvt = 43200, -- TVT
galt = -21600, -- GALT
gamt = -32400, -- GAMT
sbt = 39600, -- SBT
lint = 50400, -- LINT
kost = 39600, -- KOST
mht = 43200, -- MHT
mart = -34200, -- MART
sst = -39600, -- SST
nrt = 43200, -- NRT
nut = -39600, -- NUT
nft = 39600, -- NFT
nct = 39600, -- NCT
pwt = 32400, -- PWT
pont = 39600, -- PONT
pgt = 36000, -- PGT
ckt = -36000, -- CKT
taht = -36000, -- TAHT
gilt = 43200, -- GILT
tot = 46800, -- TOT
wakt = 43200, -- WAKT
wft = 43200, -- WFT
}
| apache-2.0 |
garrysmodlua/wire | lua/entities/gmod_wire_digitalscreen/cl_init.lua | 3 | 7494 | include('shared.lua')
function ENT:Initialize()
self.Memory1 = {}
self.Memory2 = {}
self.LastClk = true
self.NewClk = true
self.Memory1[1048575] = 1
self.Memory2[1048575] = 1
self.NeedRefresh = true
self.IsClear = true
self.ClearQueued = false
self.RefreshPixels = {}
self.RefreshRows = {}
self.ScreenWidth = 32
self.ScreenHeight = 32
for i=1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
//0..786431 - RGB data
//1048569 - Color mode (0: RGBXXX; 1: R G B)
//1048570 - Clear row
//1048571 - Clear column
//1048572 - Screen Height
//1048573 - Screen Width
//1048574 - Hardware Clear Screen
//1048575 - CLK
self.GPU = WireGPU(self)
self.buffer = {}
WireLib.netRegister(self)
end
function ENT:OnRemove()
self.GPU:Finalize()
self.NeedRefresh = true
end
local function stringToNumber(index, str, bytes)
local newpos = index+bytes
str = str:sub(index,newpos-1)
local n = 0
for j=1,bytes do
n = n + str:byte(j)*(256^(j-1))
end
return n, newpos
end
local pixelbits = {3, 1, 3, 4, 1}
net.Receive("wire_digitalscreen", function()
local ent = Entity(net.ReadUInt(16))
if IsValid(ent) and ent.Memory1 and ent.Memory2 then
local pixelbit = pixelbits[net.ReadUInt(5)]
local len = net.ReadUInt(32)
local datastr = util.Decompress(net.ReadData(len))
if #datastr>0 then
ent:AddBuffer(datastr,pixelbit)
end
end
end)
function ENT:AddBuffer(datastr,pixelbit)
self.buffer[#self.buffer+1] = {datastr=datastr,readIndex=1,pixelbit=pixelbit}
end
function ENT:ProcessBuffer()
if not self.buffer[1] then return end
local datastr = self.buffer[1].datastr
local readIndex = self.buffer[1].readIndex
local pixelbit = self.buffer[1].pixelbit
local length
length, readIndex = stringToNumber(readIndex,datastr,3)
if length == 0 then
table.remove( self.buffer, 1 )
return
end
local address
address, readIndex = stringToNumber(readIndex,datastr,3)
for i = address, address + length - 1 do
if i>=1048500 then
local data
data, readIndex = stringToNumber(readIndex,datastr,2)
self:WriteCell(i, data)
else
local data
data, readIndex = stringToNumber(readIndex,datastr,pixelbit)
self:WriteCell(i, data)
end
end
self.buffer[1].readIndex = readIndex
end
function ENT:Think()
if self.buffer[1] ~= nil then
local maxtime = SysTime() + (1/RealFrameTime()) * 0.0001 -- do more depending on client FPS. Higher fps = more work
while SysTime() < maxtime and self.buffer[1] do
self:ProcessBuffer()
end
end
self:NextThink(CurTime()+0.1)
return true
end
function ENT:ReadCell(Address,value)
Address = math.floor(Address)
if Address < 0 then return nil end
if Address >= 1048577 then return nil end
return self.Memory2[Address]
end
function ENT:WriteCell(Address,value)
Address = math.floor(Address)
if Address < 0 then return false end
if Address >= 1048577 then return false end
if Address == 1048575 then
self.NewClk = value ~= 0
elseif Address < 1048500 then
self.IsClear = false
end
if (self.NewClk) then
self.Memory1[Address] = value -- visible buffer
self.NeedRefresh = true
if self.Memory1[1048569] == 1 then -- R G B mode
local pixelno = math.floor(Address/3)
if self.RefreshPixels[#self.RefreshPixels] ~= pixelno then
self.RefreshPixels[#self.RefreshPixels+1] = pixelno
end
else -- other modes
self.RefreshPixels[#self.RefreshPixels+1] = Address
end
end
self.Memory2[Address] = value -- invisible buffer
if Address == 1048574 then -- Hardware Clear Screen
local mem1,mem2 = {},{}
for addr = 1048500,1048575 do
mem1[addr] = self.Memory1[addr]
mem2[addr] = self.Memory2[addr]
end
self.Memory1,self.Memory2 = mem1,mem2
self.IsClear = true
self.ClearQueued = true
self.NeedRefresh = true
elseif Address == 1048572 then
self.ScreenHeight = value
if not self.IsClear then
self.NeedRefresh = true
for i = 1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
elseif Address == 1048573 then
self.ScreenWidth = value
if not self.IsClear then
self.NeedRefresh = true
for i = 1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
end
if self.LastClk ~= self.NewClk then
-- swap the memory if clock changes
self.LastClk = self.NewClk
self.Memory1 = table.Copy(self.Memory2)
self.NeedRefresh = true
for i=1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
return true
end
local transformcolor = {}
transformcolor[0] = function(c) -- RGBXXX
local crgb = math.floor(c / 1000)
local cgray = c - math.floor(c / 1000)*1000
cb = cgray+28*math.fmod(crgb, 10)
cg = cgray+28*math.fmod(math.floor(crgb / 10), 10)
cr = cgray+28*math.fmod(math.floor(crgb / 100), 10)
return cr, cg, cb
end
transformcolor[2] = function(c) -- 24 bit mode
cb = math.fmod(c, 256)
cg = math.fmod(math.floor(c / 256), 256)
cr = math.fmod(math.floor(c / 65536), 256)
return cr, cg, cb
end
transformcolor[3] = function(c) -- RRRGGGBBB
cb = math.fmod(c, 1000)
cg = math.fmod(math.floor(c / 1e3), 1000)
cr = math.fmod(math.floor(c / 1e6), 1000)
return cr, cg, cb
end
transformcolor[4] = function(c) -- XXX
return c, c, c
end
local floor = math.floor
function ENT:RedrawPixel(a)
if a >= self.ScreenWidth*self.ScreenHeight then return end
local cr,cg,cb
local x = a % self.ScreenWidth
local y = math.floor(a / self.ScreenWidth)
local colormode = self.Memory1[1048569] or 0
if colormode == 1 then
cr = self.Memory1[a*3 ] or 0
cg = self.Memory1[a*3+1] or 0
cb = self.Memory1[a*3+2] or 0
else
local c = self.Memory1[a] or 0
cr, cg, cb = (transformcolor[colormode] or transformcolor[0])(c)
end
local xstep = (512/self.ScreenWidth)
local ystep = (512/self.ScreenHeight)
surface.SetDrawColor(cr,cg,cb,255)
local tx, ty = floor(x*xstep), floor(y*ystep)
surface.DrawRect( tx, ty, floor((x+1)*xstep-tx), floor((y+1)*ystep-ty) )
end
function ENT:RedrawRow(y)
local xstep = (512/self.ScreenWidth)
local ystep = (512/self.ScreenHeight)
if y >= self.ScreenHeight then return end
local a = y*self.ScreenWidth
local colormode = self.Memory1[1048569] or 0
for x = 0,self.ScreenWidth-1 do
local cr,cg,cb
if (colormode == 1) then
cr = self.Memory1[(a+x)*3 ] or 0
cg = self.Memory1[(a+x)*3+1] or 0
cb = self.Memory1[(a+x)*3+2] or 0
else
local c = self.Memory1[a+x] or 0
cr, cg, cb = (transformcolor[colormode] or transformcolor[0])(c)
end
surface.SetDrawColor(cr,cg,cb,255)
local tx, ty = floor(x*xstep), floor(y*ystep)
surface.DrawRect( tx, ty, floor((x+1)*xstep-tx), floor((y+1)*ystep-ty) )
end
end
function ENT:Draw()
self:DrawModel()
if self.NeedRefresh then
self.NeedRefresh = false
self.GPU:RenderToGPU(function()
local pixels = 0
local idx = 0
if self.ClearQueued then
surface.SetDrawColor(0,0,0,255)
surface.DrawRect(0,0, 512,512)
self.ClearQueued = false
end
if (#self.RefreshRows > 0) then
idx = #self.RefreshRows
while ((idx > 0) and (pixels < 8192)) do
self:RedrawRow(self.RefreshRows[idx])
self.RefreshRows[idx] = nil
idx = idx - 1
pixels = pixels + self.ScreenWidth
end
else
idx = #self.RefreshPixels
while ((idx > 0) and (pixels < 8192)) do
self:RedrawPixel(self.RefreshPixels[idx])
self.RefreshPixels[idx] = nil
idx = idx - 1
pixels = pixels + 1
end
end
if idx ~= 0 then
self.NeedRefresh = true
end
end)
end
self.GPU:Render()
Wire_Render(self)
end
function ENT:IsTranslucent()
return true
end
| apache-2.0 |
fo369/luci-1505 | modules/luci-base/luasrc/sys.lua | 40 | 15171 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local io = require "io"
local os = require "os"
local table = require "table"
local nixio = require "nixio"
local fs = require "nixio.fs"
local uci = require "luci.model.uci"
local luci = {}
luci.util = require "luci.util"
luci.ip = require "luci.ip"
local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select =
tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select
module "luci.sys"
function call(...)
return os.execute(...) / 256
end
exec = luci.util.exec
function mounts()
local data = {}
local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"}
local ps = luci.util.execi("df")
if not ps then
return
else
ps()
end
for line in ps do
local row = {}
local j = 1
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
if row[k[1]] then
-- this is a rather ugly workaround to cope with wrapped lines in
-- the df output:
--
-- /dev/scsi/host0/bus0/target0/lun0/part3
-- 114382024 93566472 15005244 86% /mnt/usb
--
if not row[k[2]] then
j = 2
line = ps()
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
end
table.insert(data, row)
end
end
return data
end
-- containing the whole environment is returned otherwise this function returns
-- the corresponding string value for the given name or nil if no such variable
-- exists.
getenv = nixio.getenv
function hostname(newname)
if type(newname) == "string" and #newname > 0 then
fs.writefile( "/proc/sys/kernel/hostname", newname )
return newname
else
return nixio.uname().nodename
end
end
function httpget(url, stream, target)
if not target then
local source = stream and io.popen or luci.util.exec
return source("wget -qO- '"..url:gsub("'", "").."'")
else
return os.execute("wget -qO '%s' '%s'" %
{target:gsub("'", ""), url:gsub("'", "")})
end
end
function reboot()
return os.execute("reboot >/dev/null 2>&1")
end
function syslog()
return luci.util.exec("logread")
end
function dmesg()
return luci.util.exec("dmesg")
end
function uniqueid(bytes)
local rand = fs.readfile("/dev/urandom", bytes)
return rand and nixio.bin.hexlify(rand)
end
function uptime()
return nixio.sysinfo().uptime
end
net = {}
-- The following fields are defined for arp entry objects:
-- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" }
function net.arptable(callback)
local arp = (not callback) and {} or nil
local e, r, v
if fs.access("/proc/net/arp") then
for e in io.lines("/proc/net/arp") do
local r = { }, v
for v in e:gmatch("%S+") do
r[#r+1] = v
end
if r[1] ~= "IP" then
local x = {
["IP address"] = r[1],
["HW type"] = r[2],
["Flags"] = r[3],
["HW address"] = r[4],
["Mask"] = r[5],
["Device"] = r[6]
}
if callback then
callback(x)
else
arp = arp or { }
arp[#arp+1] = x
end
end
end
end
return arp
end
local function _nethints(what, callback)
local _, k, e, mac, ip, name
local cur = uci.cursor()
local ifn = { }
local hosts = { }
local function _add(i, ...)
local k = select(i, ...)
if k then
if not hosts[k] then hosts[k] = { } end
hosts[k][1] = select(1, ...) or hosts[k][1]
hosts[k][2] = select(2, ...) or hosts[k][2]
hosts[k][3] = select(3, ...) or hosts[k][3]
hosts[k][4] = select(4, ...) or hosts[k][4]
end
end
if fs.access("/proc/net/arp") then
for e in io.lines("/proc/net/arp") do
ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+")
if ip and mac then
_add(what, mac:upper(), ip, nil, nil)
end
end
end
if fs.access("/etc/ethers") then
for e in io.lines("/etc/ethers") do
mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
if mac and ip then
_add(what, mac:upper(), ip, nil, nil)
end
end
end
if fs.access("/var/dhcp.leases") then
for e in io.lines("/var/dhcp.leases") do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
if mac and ip then
_add(what, mac:upper(), ip, nil, name ~= "*" and name)
end
end
end
cur:foreach("dhcp", "host",
function(s)
for mac in luci.util.imatch(s.mac) do
_add(what, mac:upper(), s.ip, nil, s.name)
end
end)
for _, e in ipairs(nixio.getifaddrs()) do
if e.name ~= "lo" then
ifn[e.name] = ifn[e.name] or { }
if e.family == "packet" and e.addr and #e.addr == 17 then
ifn[e.name][1] = e.addr:upper()
elseif e.family == "inet" then
ifn[e.name][2] = e.addr
elseif e.family == "inet6" then
ifn[e.name][3] = e.addr
end
end
end
for _, e in pairs(ifn) do
if e[what] and (e[2] or e[3]) then
_add(what, e[1], e[2], e[3], e[4])
end
end
for _, e in luci.util.kspairs(hosts) do
callback(e[1], e[2], e[3], e[4])
end
end
-- Each entry contains the values in the following order:
-- [ "mac", "name" ]
function net.mac_hints(callback)
if callback then
_nethints(1, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
if name and name ~= mac then
callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4)
end
end)
else
local rv = { }
_nethints(1, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
if name and name ~= mac then
rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 }
end
end)
return rv
end
end
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv4_hints(callback)
if callback then
_nethints(2, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4, nil, 100) or mac
if name and name ~= v4 then
callback(v4, name)
end
end)
else
local rv = { }
_nethints(2, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4, nil, 100) or mac
if name and name ~= v4 then
rv[#rv+1] = { v4, name }
end
end)
return rv
end
end
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv6_hints(callback)
if callback then
_nethints(3, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v6, nil, 100) or mac
if name and name ~= v6 then
callback(v6, name)
end
end)
else
local rv = { }
_nethints(3, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v6, nil, 100) or mac
if name and name ~= v6 then
rv[#rv+1] = { v6, name }
end
end)
return rv
end
end
function net.conntrack(callback)
local connt = {}
if fs.access("/proc/net/nf_conntrack", "r") then
for line in io.lines("/proc/net/nf_conntrack") do
line = line:match "^(.-( [^ =]+=).-)%2"
local entry, flags = _parse_mixed_record(line, " +")
if flags[6] ~= "TIME_WAIT" then
entry.layer3 = flags[1]
entry.layer4 = flags[3]
for i=1, #entry do
entry[i] = nil
end
if callback then
callback(entry)
else
connt[#connt+1] = entry
end
end
end
elseif fs.access("/proc/net/ip_conntrack", "r") then
for line in io.lines("/proc/net/ip_conntrack") do
line = line:match "^(.-( [^ =]+=).-)%2"
local entry, flags = _parse_mixed_record(line, " +")
if flags[4] ~= "TIME_WAIT" then
entry.layer3 = "ipv4"
entry.layer4 = flags[1]
for i=1, #entry do
entry[i] = nil
end
if callback then
callback(entry)
else
connt[#connt+1] = entry
end
end
end
else
return nil
end
return connt
end
function net.devices()
local devs = {}
for k, v in ipairs(nixio.getifaddrs()) do
if v.family == "packet" then
devs[#devs+1] = v.name
end
end
return devs
end
function net.deviceinfo()
local devs = {}
for k, v in ipairs(nixio.getifaddrs()) do
if v.family == "packet" then
local d = v.data
d[1] = d.rx_bytes
d[2] = d.rx_packets
d[3] = d.rx_errors
d[4] = d.rx_dropped
d[5] = 0
d[6] = 0
d[7] = 0
d[8] = d.multicast
d[9] = d.tx_bytes
d[10] = d.tx_packets
d[11] = d.tx_errors
d[12] = d.tx_dropped
d[13] = 0
d[14] = d.collisions
d[15] = 0
d[16] = 0
devs[v.name] = d
end
end
return devs
end
-- The following fields are defined for route entry tables:
-- { "dest", "gateway", "metric", "refcount", "usecount", "irtt",
-- "flags", "device" }
function net.routes(callback)
local routes = { }
for line in io.lines("/proc/net/route") do
local dev, dst_ip, gateway, flags, refcnt, usecnt, metric,
dst_mask, mtu, win, irtt = line:match(
"([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" ..
"(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)"
)
if dev then
gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 )
dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 )
dst_ip = luci.ip.Hex(
dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4
)
local rt = {
dest = dst_ip,
gateway = gateway,
metric = tonumber(metric),
refcount = tonumber(refcnt),
usecount = tonumber(usecnt),
mtu = tonumber(mtu),
window = tonumber(window),
irtt = tonumber(irtt),
flags = tonumber(flags, 16),
device = dev
}
if callback then
callback(rt)
else
routes[#routes+1] = rt
end
end
end
return routes
end
-- The following fields are defined for route entry tables:
-- { "source", "dest", "nexthop", "metric", "refcount", "usecount",
-- "flags", "device" }
function net.routes6(callback)
if fs.access("/proc/net/ipv6_route", "r") then
local routes = { }
for line in io.lines("/proc/net/ipv6_route") do
local dst_ip, dst_prefix, src_ip, src_prefix, nexthop,
metric, refcnt, usecnt, flags, dev = line:match(
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) +([^%s]+)"
)
if dst_ip and dst_prefix and
src_ip and src_prefix and
nexthop and metric and
refcnt and usecnt and
flags and dev
then
src_ip = luci.ip.Hex(
src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false
)
dst_ip = luci.ip.Hex(
dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false
)
nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false )
local rt = {
source = src_ip,
dest = dst_ip,
nexthop = nexthop,
metric = tonumber(metric, 16),
refcount = tonumber(refcnt, 16),
usecount = tonumber(usecnt, 16),
flags = tonumber(flags, 16),
device = dev,
-- lua number is too small for storing the metric
-- add a metric_raw field with the original content
metric_raw = metric
}
if callback then
callback(rt)
else
routes[#routes+1] = rt
end
end
end
return routes
end
end
function net.pingtest(host)
return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1")
end
process = {}
function process.info(key)
local s = {uid = nixio.getuid(), gid = nixio.getgid()}
return not key and s or s[key]
end
function process.list()
local data = {}
local k
local ps = luci.util.execi("/bin/busybox top -bn1")
if not ps then
return
end
for line in ps do
local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
"^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)"
)
local idx = tonumber(pid)
if idx then
data[idx] = {
['PID'] = pid,
['PPID'] = ppid,
['USER'] = user,
['STAT'] = stat,
['VSZ'] = vsz,
['%MEM'] = mem,
['%CPU'] = cpu,
['COMMAND'] = cmd
}
end
end
return data
end
function process.setgroup(gid)
return nixio.setgid(gid)
end
function process.setuser(uid)
return nixio.setuid(uid)
end
process.signal = nixio.kill
user = {}
-- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" }
user.getuser = nixio.getpw
function user.getpasswd(username)
local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username)
local pwh = pwe and (pwe.pwdp or pwe.passwd)
if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then
return nil, pwe
else
return pwh, pwe
end
end
function user.checkpasswd(username, pass)
local pwh, pwe = user.getpasswd(username)
if pwe then
return (pwh == nil or nixio.crypt(pass, pwh) == pwh)
end
return false
end
function user.setpasswd(username, password)
if password then
password = password:gsub("'", [['"'"']])
end
if username then
username = username:gsub("'", [['"'"']])
end
return os.execute(
"(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " ..
"passwd '" .. username .. "' >/dev/null 2>&1"
)
end
wifi = {}
function wifi.getiwinfo(ifname)
local stat, iwinfo = pcall(require, "iwinfo")
if ifname then
local c = 0
local u = uci.cursor_state()
local d, n = ifname:match("^(%w+)%.network(%d+)")
if d and n then
ifname = d
n = tonumber(n)
u:foreach("wireless", "wifi-iface",
function(s)
if s.device == d then
c = c + 1
if c == n then
ifname = s.ifname or s.device
return false
end
end
end)
elseif u:get("wireless", ifname) == "wifi-device" then
u:foreach("wireless", "wifi-iface",
function(s)
if s.device == ifname and s.ifname then
ifname = s.ifname
return false
end
end)
end
local t = stat and iwinfo.type(ifname)
local x = t and iwinfo[t] or { }
return setmetatable({}, {
__index = function(t, k)
if k == "ifname" then
return ifname
elseif x[k] then
return x[k](ifname)
end
end
})
end
end
init = {}
init.dir = "/etc/init.d/"
function init.names()
local names = { }
for name in fs.glob(init.dir.."*") do
names[#names+1] = fs.basename(name)
end
return names
end
function init.index(name)
if fs.access(init.dir..name) then
return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null"
%{ init.dir, name })
end
end
local function init_action(action, name)
if fs.access(init.dir..name) then
return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action })
end
end
function init.enabled(name)
return (init_action("enabled", name) == 0)
end
function init.enable(name)
return (init_action("enable", name) == 1)
end
function init.disable(name)
return (init_action("disable", name) == 0)
end
function init.start(name)
return (init_action("start", name) == 0)
end
function init.stop(name)
return (init_action("stop", name) == 0)
end
-- Internal functions
function _parse_mixed_record(cnt, delimiter)
delimiter = delimiter or " "
local data = {}
local flags = {}
for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do
for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do
local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*')
if k then
if x == "" then
table.insert(flags, k)
else
data[k] = v
end
end
end
end
return data, flags
end
| apache-2.0 |
fo369/luci-1505 | build/luadoc/luadoc/init.lua | 172 | 1333 | -------------------------------------------------------------------------------
-- LuaDoc main function.
-- @release $Id: init.lua,v 1.4 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
local require = require
local util = require "luadoc.util"
logger = {}
module ("luadoc")
-------------------------------------------------------------------------------
-- LuaDoc version number.
_COPYRIGHT = "Copyright (c) 2003-2007 The Kepler Project"
_DESCRIPTION = "Documentation Generator Tool for the Lua language"
_VERSION = "LuaDoc 3.0.1"
-------------------------------------------------------------------------------
-- Main function
-- @see luadoc.doclet.html, luadoc.doclet.formatter, luadoc.doclet.raw
-- @see luadoc.taglet.standard
function main (files, options)
logger = util.loadlogengine(options)
-- load config file
if options.config ~= nil then
-- load specified config file
dofile(options.config)
else
-- load default config file
require("luadoc.config")
end
local taglet = require(options.taglet)
local doclet = require(options.doclet)
-- analyze input
taglet.options = options
taglet.logger = logger
local doc = taglet.start(files)
-- generate output
doclet.options = options
doclet.logger = logger
doclet.start(doc)
end
| apache-2.0 |
mattyx14/otxserver | data/monster/quests/wrath_of_the_emperor/snake_god_essence.lua | 2 | 2493 | local mType = Game.createMonsterType("Snake God Essence")
local monster = {}
monster.description = "Snake God Essence"
monster.experience = 7410
monster.outfit = {
lookType = 356,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 65000
monster.maxHealth = 65000
monster.race = "blood"
monster.corpse = 0
monster.speed = 300
monster.manaCost = 0
monster.changeTarget = {
interval = 2000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "AHHH ZHE POWER...", yell = true},
{text = "ZHE TIME OF ZHE SNAKE HAZ COME!", yell = true}
}
monster.loot = {
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -600},
{name ="combat", interval = 2000, chance = 40, type = COMBAT_LIFEDRAIN, minDamage = 0, maxDamage = -300, length = 8, spread = 3, effect = CONST_ME_MAGIC_RED, target = false},
{name ="combat", interval = 2000, chance = 50, type = COMBAT_EARTHDAMAGE, minDamage = -150, maxDamage = -270, radius = 6, effect = CONST_ME_MAGIC_GREEN, target = false}
}
monster.defenses = {
defense = 65,
armor = 70,
{name ="combat", interval = 2000, chance = 25, type = COMBAT_HEALING, minDamage = 150, maxDamage = 450, effect = CONST_ME_MAGIC_BLUE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 10},
{type = COMBAT_ENERGYDAMAGE, percent = -10},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = -10},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 20},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 0}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
EvilHero90/tfstemp | data/actions/scripts/other/windows.lua | 12 | 2054 | local windows = {
[5303] = 6448, [5304] = 6449, [6438] = 6436, [6436] = 6438,
[6439] = 6437, [6437] = 6439, [6442] = 6440, [6440] = 6442,
[6443] = 6441, [6441] = 6443, [6446] = 6444, [6444] = 6446,
[6447] = 6445, [6445] = 6447, [6448] = 5303, [6449] = 5304,
[6452] = 6450, [6450] = 6452, [6453] = 6451, [6451] = 6453,
[6456] = 6454, [6454] = 6456, [6457] = 6455, [6455] = 6457,
[6460] = 6458, [6458] = 6460, [6461] = 6459, [6459] = 6461,
[6464] = 6462, [6462] = 6464, [6465] = 6463, [6463] = 6465,
[6468] = 6466, [6466] = 6468, [6469] = 6467, [6467] = 6469,
[6472] = 6470, [6470] = 6472, [6473] = 6471, [6471] = 6473,
[6790] = 6788, [6788] = 6790, [6791] = 6789, [6789] = 6791,
[7027] = 7025, [7025] = 7027, [7028] = 7026, [7026] = 7028,
[7031] = 7029, [7029] = 7031, [7032] = 7030, [7030] = 7032,
[10264] = 10266, [10266] = 10264, [10265] = 10267, [10267] = 10265,
[10488] = 10490, [10490] = 10488, [10489] = 10491, [10491] = 10489,
[19427] = 19447, [19428] = 19448, [19441] = 19450, [19440] = 19449,
[19443] = 20180, [19444] = 20181, [19445] = 20183, [19446] = 20184,
[19447] = 19427, [19448] = 19428, [19449] = 19440, [19450] = 19441,
[19974] = 20182, [19975] = 20185, [20180] = 19443, [20181] = 19444,
[20182] = 19974, [20183] = 19445, [20184] = 19446, [20185] = 19975
}
function onUse(cid, item, fromPosition, itemEx, toPosition)
local window = windows[item.itemid]
if window == nil then
return false
end
local tile = fromPosition:getTile()
local house = tile and tile:getHouse()
if not house then
fromPosition.y = fromPosition.y - 1
tile = fromPosition:getTile()
house = tile and tile:getHouse()
if not house then
fromPosition.y = fromPosition.y + 1
fromPosition.x = fromPosition.x - 1
tile = fromPosition:getTile()
house = tile and tile:getHouse()
end
end
if house then
local player = Player(cid)
if player:getPosition():getTile():getHouse() ~= house and player:getAccountType() < ACCOUNT_TYPE_GAMEMASTER then
return false
end
end
Item(item.uid):transform(window)
return true
end
| gpl-2.0 |
matinbot/telewebamoz | plugins/admin.lua | 230 | 6382 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function user_info_callback(cb_extra, success, result)
result.access_hash = nil
result.flags = nil
result.phone = nil
if result.username then
result.username = '@'..result.username
end
result.print_name = result.print_name:gsub("_","")
local text = serpent.block(result, {comment=false})
text = text:gsub("[{}]", "")
text = text:gsub('"', "")
text = text:gsub(",","")
if cb_extra.msg.to.type == "chat" then
send_large_msg("chat#id"..cb_extra.msg.to.id, text)
else
send_large_msg("user#id"..cb_extra.msg.to.id, text)
end
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairs(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
local function run(msg,matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local group = msg.to.id
if not is_admin(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "Msg sent"
end
if matches[1] == "block" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent dialog list with both json and text format to your private"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
return
end
return {
patterns = {
"^[!/](pm) (%d+) (.*)$",
"^[!/](import) (.*)$",
"^[!/](unblock) (%d+)$",
"^[!/](block) (%d+)$",
"^[!/](markread) (on)$",
"^[!/](markread) (off)$",
"^[!/](setbotphoto)$",
"%[(photo)%]",
"^[!/](contactlist)$",
"^[!/](dialoglist)$",
"^[!/](delcontact) (%d+)$",
"^[!/](whois) (%d+)$"
},
run = run,
}
--By @imandaneshi :)
--https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
| gpl-2.0 |
mattyx14/otxserver | data/startup/tables/chest.lua | 2 | 1216 | --[[
Look README.md for see the reserved action/unique numbers
From range 5000 to 6000 is reserved for keys chest
From range 6001 to 472 is reserved for script reward
Path: data\scripts\actions\system\quest_reward_common.lua
From range 473 to 15000 is reserved for others scripts (varied rewards)
There is no need to tamper with the chests scripts, just register a new table and configure correctly
So the quest will work in-game
Example:
[xxxx] = {
-- For use of the map
itemId = xxxx,
itemPos = {x = xxxxx, y = xxxxx, z = x},
-- For use of the script
container = xxxx (it's for use reward in a container, only put the id of the container here)
keyAction = xxxx, (it's for use one key in the chest and is reward in container, only put the key in reward and action here)
reward = {{xxxx, x}},
storage = xxxxx
},
Note:
The "for use of the map" variables are only used to create the action or unique on the map during startup
If the reward is an key, do not need to use "keyAction", only set the storage as same action id
The "for use of the script" variables are used by the scripts
To allow a single script to manage all rewards
]]
ChestAction = {
--
}
ChestUnique = {
--
}
| gpl-2.0 |
kbara/snabb | lib/luajit/src/jit/v.lua | 78 | 5755 | ----------------------------------------------------------------------------
-- Verbose mode of the LuaJIT compiler.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module shows verbose information about the progress of the
-- JIT compiler. It prints one line for each generated trace. This module
-- is useful to see which code has been compiled or where the compiler
-- punts and falls back to the interpreter.
--
-- Example usage:
--
-- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end"
-- luajit -jv=myapp.out myapp.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the
-- module is started.
--
-- The output from the first example should look like this:
--
-- [TRACE 1 (command line):1 loop]
-- [TRACE 2 (1/3) (command line):1 -> 1]
--
-- The first number in each line is the internal trace number. Next are
-- the file name ('(command line)') and the line number (':1') where the
-- trace has started. Side traces also show the parent trace number and
-- the exit number where they are attached to in parentheses ('(1/3)').
-- An arrow at the end shows where the trace links to ('-> 1'), unless
-- it loops to itself.
--
-- In this case the inner loop gets hot and is traced first, generating
-- a root trace. Then the last exit from the 1st trace gets hot, too,
-- and triggers generation of the 2nd trace. The side trace follows the
-- path along the outer loop and *around* the inner loop, back to its
-- start, and then links to the 1st trace. Yes, this may seem unusual,
-- if you know how traditional compilers work. Trace compilers are full
-- of surprises like this -- have fun! :-)
--
-- Aborted traces are shown like this:
--
-- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50]
--
-- Don't worry -- trace aborts are quite common, even in programs which
-- can be fully compiled. The compiler may retry several times until it
-- finds a suitable trace.
--
-- Of course this doesn't work with features that are not-yet-implemented
-- (NYI error messages). The VM simply falls back to the interpreter. This
-- may not matter at all if the particular trace is not very high up in
-- the CPU usage profile. Oh, and the interpreter is quite fast, too.
--
-- Also check out the -jdump module, which prints all the gory details.
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo
local type, format = type, string.format
local stdout, stderr = io.stdout, io.stderr
-- Active flag and output file handle.
local active, out
------------------------------------------------------------------------------
local startloc, startex
local function fmtfunc(func, pc)
local fi = funcinfo(func, pc)
if fi.loc then
return fi.loc
elseif fi.ffid then
return vmdef.ffnames[fi.ffid]
elseif fi.addr then
return format("C:%x", fi.addr)
else
return "(?)"
end
end
-- Format trace error message.
local function fmterr(err, info)
if type(err) == "number" then
if type(info) == "function" then info = fmtfunc(info) end
err = format(vmdef.traceerr[err], info)
end
return err
end
-- Dump trace states.
local function dump_trace(what, tr, func, pc, otr, oex)
if what == "start" then
startloc = fmtfunc(func, pc)
startex = otr and "("..otr.."/"..oex..") " or ""
else
if what == "abort" then
local loc = fmtfunc(func, pc)
if loc ~= startloc then
out:write(format("[TRACE --- %s%s -- %s at %s]\n",
startex, startloc, fmterr(otr, oex), loc))
else
out:write(format("[TRACE --- %s%s -- %s]\n",
startex, startloc, fmterr(otr, oex)))
end
elseif what == "stop" then
local info = traceinfo(tr)
local link, ltype = info.link, info.linktype
if ltype == "interpreter" then
out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n",
tr, startex, startloc))
elseif ltype == "stitch" then
out:write(format("[TRACE %3s %s%s %s %s]\n",
tr, startex, startloc, ltype, fmtfunc(func, pc)))
elseif link == tr or link == 0 then
out:write(format("[TRACE %3s %s%s %s]\n",
tr, startex, startloc, ltype))
elseif ltype == "root" then
out:write(format("[TRACE %3s %s%s -> %d]\n",
tr, startex, startloc, link))
else
out:write(format("[TRACE %3s %s%s -> %d %s]\n",
tr, startex, startloc, link, ltype))
end
else
out:write(format("[TRACE %s]\n", what))
end
out:flush()
end
end
------------------------------------------------------------------------------
-- Detach dump handlers.
local function dumpoff()
if active then
active = false
jit.attach(dump_trace)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach dump handlers.
local function dumpon(outfile)
if active then dumpoff() end
if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(dump_trace, "trace")
active = true
end
-- Public module functions.
return {
on = dumpon,
off = dumpoff,
start = dumpon -- For -j command line option.
}
| apache-2.0 |
CarabusX/Zero-K | effects/feature_poof.lua | 22 | 1425 | -- feature_poof
return {
["feature_poof_spawner"] = {
poof01 = {
air = true,
class = [[CExpGenSpawner]],
count = [[10]],
ground = true,
properties = {
delay = [[i1 x0.1d]],
damage = [[d1]],
explosionGenerator = [[custom:feature_poof]],
},
},
},
["feature_poof"] = {
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = [[1]],
ground = true,
properties = {
airdrag = 0.975,
alwaysvisible = false,
colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]],
directional = true,
emitrot = 180,
emitrotspread = 180,
emitvector = [[0, 1, 0]],
gravity = [[r-0.05 r0.05, -0.2 r0.05, r-0.05 r0.05]],
numparticles = [[1 d0.05]],
particlelife = 30,
particlelifespread = 10,
particlesize = [[1 d0.25]],
particlesizespread = [[d0.4]],
particlespeed = [[d0.05 r1]],
particlespeedspread = 1,
pos = [[r-5d r10d, r-5d r10d, r-5d r10d]],
sizegrowth = 1.2,
sizemod = 0.995,
texture = [[dirt]],
},
},
},
}
| gpl-2.0 |
mattyx14/otxserver | data/monster/mammals/skunk.lua | 2 | 2348 | local mType = Game.createMonsterType("Skunk")
local monster = {}
monster.description = "a skunk"
monster.experience = 3
monster.outfit = {
lookType = 106,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 106
monster.Bestiary = {
class = "Mammal",
race = BESTY_RACE_MAMMAL,
toKill = 250,
FirstUnlock = 10,
SecondUnlock = 100,
CharmsPoints = 5,
Stars = 1,
Occurrence = 0,
Locations = "Unannounced raid in Edron outside the depot, Tiquanda, Shattered Isles, \z
Liberty Bay, south gate of Thais."
}
monster.health = 20
monster.maxHealth = 20
monster.race = "blood"
monster.corpse = 6035
monster.speed = 120
monster.manaCost = 200
monster.changeTarget = {
interval = 4000,
chance = 0
}
monster.strategiesTarget = {
nearest = 100,
}
monster.flags = {
summonable = true,
attackable = true,
hostile = true,
convinceable = true,
pushable = true,
rewardBoss = false,
illusionable = true,
canPushItems = false,
canPushCreatures = false,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 8,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
{name = "bulb of garlic", chance = 4910},
{name = "skunk tail", chance = 920}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -5},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_EARTHDAMAGE, minDamage = -1, maxDamage = -3, range = 1, target = true}
}
monster.defenses = {
defense = 5,
armor = 5
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 0},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = 0},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 0}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = false},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
imeteora/cocos2d-x-3.x-Qt | tests/lua-tests/src/ParticleTest/ParticleTest.lua | 10 | 43736 |
local SceneIdx = -1
local MAX_LAYER = 42
local emitter = nil
local background = nil
local labelAtlas = nil
local titleLabel = nil
local subtitleLabel = nil
local baseLayer_entry = nil
local s = cc.Director:getInstance():getWinSize()
local function backAction()
SceneIdx = SceneIdx - 1
if SceneIdx < 0 then
SceneIdx = SceneIdx + MAX_LAYER
end
return CreateParticleLayer()
end
local function restartAction()
return CreateParticleLayer()
end
local function nextAction()
SceneIdx = SceneIdx + 1
SceneIdx = math.mod(SceneIdx, MAX_LAYER)
return CreateParticleLayer()
end
local function backCallback(sender)
local scene = cc.Scene:create()
scene:addChild(backAction())
scene:addChild(CreateBackMenuItem())
cc.Director:getInstance():replaceScene(scene)
end
local function restartCallback(sender)
local scene = cc.Scene:create()
scene:addChild(restartAction())
scene:addChild(CreateBackMenuItem())
cc.Director:getInstance():replaceScene(scene)
end
local function nextCallback(sender)
local scene = cc.Scene:create()
scene:addChild(nextAction())
scene:addChild(CreateBackMenuItem())
cc.Director:getInstance():replaceScene(scene)
end
local function toggleCallback(sender)
if emitter ~= nil then
if emitter:getPositionType() == cc.POSITION_TYPE_GROUPED then
emitter:setPositionType(cc.POSITION_TYPE_FREE)
elseif emitter:getPositionType() == cc.POSITION_TYPE_FREE then
emitter:setPositionType(cc.POSITION_TYPE_RELATIVE)
elseif emitter:getPositionType() == cc.POSITION_TYPE_RELATIVE then
emitter:setPositionType(cc.POSITION_TYPE_GROUPED)
end
end
end
local function setEmitterPosition()
if emitter ~= nil then
emitter:setPosition(s.width / 2, s.height / 2)
end
end
local function update(dt)
if emitter ~= nil then
local str = "" .. emitter:getParticleCount()
-- labelAtlas:setString("" .. str)
end
end
local function baseLayer_onEnterOrExit(tag)
local scheduler = cc.Director:getInstance():getScheduler()
if tag == "enter" then
baseLayer_entry = scheduler:scheduleScriptFunc(update, 0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(baseLayer_entry)
end
end
local function getBaseLayer()
local layer = cc.LayerColor:create(cc.c4b(127,127,127,255))
emitter = nil
titleLabel = cc.Label:createWithTTF("", s_arialPath, 28)
layer:addChild(titleLabel, 100, 1000)
titleLabel:setAnchorPoint(cc.p(0.5, 0.5))
titleLabel:setPosition(s.width / 2, s.height - 50)
subtitleLabel = cc.Label:createWithTTF("", s_arialPath, 16)
layer:addChild(subtitleLabel, 100)
subtitleLabel:setAnchorPoint(cc.p(0.5, 0.5))
subtitleLabel:setPosition(s.width / 2, s.height - 80)
local item1 = cc.MenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = cc.MenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = cc.MenuItemImage:create(s_pPathF1, s_pPathF2)
local item4 = cc.MenuItemToggle:create(cc.MenuItemFont:create("Free Movement"))
item4:addSubItem(cc.MenuItemFont:create("Relative Movement"))
item4:addSubItem(cc.MenuItemFont:create("Grouped Movement"))
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
item4:registerScriptTapHandler(toggleCallback)
local menu = cc.Menu:create()
menu:addChild(item1)
menu:addChild(item2)
menu:addChild(item3)
menu:addChild(item4)
menu:setPosition(cc.p(0, 0))
item1:setPosition(cc.p(s.width/2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item2:setPosition(cc.p(s.width/2, item2:getContentSize().height / 2))
item3:setPosition(cc.p(s.width/2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item4:setPosition(cc.p(0, 100))
item4:setAnchorPoint(cc.p(0, 0))
layer:addChild(menu, 100)
labelAtlas = cc.LabelAtlas:_create("0000", "fps_images.png", 12, 32, string.byte('.'))
layer:addChild(labelAtlas, 100)
labelAtlas:setPosition(cc.p(s.width - 66, 50))
-- moving background
background = cc.Sprite:create(s_back3)
layer:addChild(background, 5)
background:setPosition(cc.p(s.width / 2, s.height - 180))
local move = cc.MoveBy:create(4, cc.p(300, 0))
local move_back = move:reverse()
local seq = cc.Sequence:create(move, move_back)
background:runAction(cc.RepeatForever:create(seq))
local function onTouchesEnded(touches, event)
local location = touches[1]:getLocation()
local pos = cc.p(0, 0)
if background ~= nil then
pos = background:convertToWorldSpace(cc.p(0, 0))
end
if emitter ~= nil then
local newPos = cc.pSub(location, pos)
emitter:setPosition(newPos.x, newPos.y)
end
end
local function onTouchesBegan(touches, event)
onTouchesEnded(touches, event);
end
local function onTouchesMoved(touches, event)
onTouchesEnded(touches, event);
end
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN )
listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED )
listener:registerScriptHandler(onTouchesEnded,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer)
layer:registerScriptHandler(baseLayer_onEnterOrExit)
return layer
end
---------------------------------
-- ParticleReorder
---------------------------------
local ParticleReorder_Order = nil
local ParticleReorder_entry = nil
local ParticleReorder_layer = nil
local function reorderParticles(dt)
update(dt)
for i = 0, 1 do
local parent = ParticleReorder_layer:getChildByTag(1000 + i)
local child1 = parent:getChildByTag(1)
local child2 = parent:getChildByTag(2)
local child3 = parent:getChildByTag(3)
if math.mod(ParticleReorder_Order, 3) == 0 then
parent:reorderChild(child1, 1)
parent:reorderChild(child2, 2)
parent:reorderChild(child3, 3)
elseif math.mod(ParticleReorder_Order, 3) == 1 then
parent:reorderChild(child1, 3)
parent:reorderChild(child2, 1)
parent:reorderChild(child3, 2)
elseif math.mod(ParticleReorder_Order, 3) == 2 then
parent:reorderChild(child1, 2)
parent:reorderChild(child2, 3)
parent:reorderChild(child3, 1)
end
end
ParticleReorder_Order = ParticleReorder_Order + 1
end
local function ParticleReorder_onEnterOrExit(tag)
local scheduler = cc.Director:getInstance():getScheduler()
if tag == "enter" then
ParticleReorder_entry = scheduler:scheduleScriptFunc(reorderParticles, 1.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(ParticleReorder_entry)
end
end
local function ParticleReorder()
ParticleReorder_layer = getBaseLayer()
ParticleReorder_Order = 0
ParticleReorder_layer:setColor(cc.c3b(0, 0, 0))
ParticleReorder_layer:removeChild(background, true)
background = nil
local ignore = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
local parent1 = cc.Node:create()
local parent2 = cc.ParticleBatchNode:createWithTexture(ignore:getTexture())
ignore:unscheduleUpdate()
for i = 0, 1 do
local parent = nil
if i == 0 then
parent = parent1
else
parent = parent2
end
local emitter1 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
emitter1:setStartColor(cc.c4f(1,0,0,1))
emitter1:setBlendAdditive(false)
local emitter2 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
emitter2:setStartColor(cc.c4f(0,1,0,1))
emitter2:setBlendAdditive(false)
local emitter3 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
emitter3:setStartColor(cc.c4f(0,0,1,1))
emitter3:setBlendAdditive(false)
local neg = nil
if i == 0 then
neg = 1
else
neg = -1
end
emitter1:setPosition(cc.p( s.width / 2 - 30, s.height / 2 + 60 * neg))
emitter2:setPosition(cc.p( s.width / 2, s.height / 2 + 60 * neg))
emitter3:setPosition(cc.p( s.width / 2 + 30, s.height / 2 + 60 * neg))
parent:addChild(emitter1, 0, 1)
parent:addChild(emitter2, 0, 2)
parent:addChild(emitter3, 0, 3)
ParticleReorder_layer:addChild(parent, 10, 1000 + i)
end
ParticleReorder_layer:registerScriptHandler(ParticleReorder_onEnterOrExit)
titleLabel:setString("Reordering particles")
subtitleLabel:setString("Reordering particles with and without batches batches")
return ParticleReorder_layer
end
---------------------------------
-- ParticleBatchHybrid
---------------------------------
local ParticleBatchHybrid_entry = nil
local ParticleBatchHybrid_parent1 = nil
local ParticleBatchHybrid_parent2 = nil
local function switchRender(dt)
update(dt)
local cond = (emitter:getBatchNode() ~= nil)
emitter:removeFromParent(false)
local str = "Particle: Using new parent: "
local newParent = nil
if cond == true then
newParent = ParticleBatchHybrid_parent2
str = str .. "Node"
else
newParent = ParticleBatchHybrid_parent1
str = str .. "ParticleBatchNode"
end
newParent:addChild(emitter)
cclog(str)
end
local function ParticleBatchHybrid_onEnterOrExit(tag)
local scheduler = cc.Director:getInstance():getScheduler()
if tag == "enter" then
ParticleBatchHybrid_entry = scheduler:scheduleScriptFunc(switchRender, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(ParticleBatchHybrid_entry)
emitter:release()
end
end
local function ParticleBatchHybrid()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = cc.ParticleSystemQuad:create("Particles/LavaFlow.plist")
emitter:retain()
local batch = cc.ParticleBatchNode:createWithTexture(emitter:getTexture())
batch:addChild(emitter)
layer:addChild(batch, 10)
local node = cc.Node:create()
layer:addChild(node)
ParticleBatchHybrid_parent1 = batch
ParticleBatchHybrid_parent2 = node
layer:registerScriptHandler(ParticleBatchHybrid_onEnterOrExit)
titleLabel:setString("Particle Batch")
subtitleLabel:setString("Hybrid: batched and non batched every 2 seconds")
return layer
end
---------------------------------
-- ParticleBatchMultipleEmitters
---------------------------------
local function ParticleBatchMultipleEmitters()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
local emitter1 = cc.ParticleSystemQuad:create("Particles/LavaFlow.plist")
emitter1:setStartColor(cc.c4f(1,0,0,1))
local emitter2 = cc.ParticleSystemQuad:create("Particles/LavaFlow.plist")
emitter2:setStartColor(cc.c4f(0,1,0,1))
local emitter3 = cc.ParticleSystemQuad:create("Particles/LavaFlow.plist")
emitter3:setStartColor(cc.c4f(0,0,1,1))
emitter1:setPosition(cc.p(s.width / 1.25, s.height / 1.25))
emitter2:setPosition(cc.p(s.width / 2, s.height / 2))
emitter3:setPosition(cc.p(s.width / 4, s.height / 4))
local batch = cc.ParticleBatchNode:createWithTexture(emitter1:getTexture())
batch:addChild(emitter1, 0)
batch:addChild(emitter2, 0)
batch:addChild(emitter3, 0)
layer:addChild(batch, 10)
titleLabel:setString("Particle Batch")
subtitleLabel:setString("Multiple emitters. One Batch")
return layer
end
---------------------------------
-- DemoFlower
---------------------------------
local function DemoFlower()
local layer = getBaseLayer()
emitter = cc.ParticleFlower:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1))
setEmitterPosition()
titleLabel:setString("ParticleFlower")
return layer
end
---------------------------------
-- DemoGalaxy
---------------------------------
local function DemoGalaxy()
local layer = getBaseLayer()
emitter = cc.ParticleGalaxy:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleGalaxy")
return layer
end
---------------------------------
-- DemoFirework
---------------------------------
local function DemoFirework()
local layer = getBaseLayer()
emitter = cc.ParticleFireworks:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1))
setEmitterPosition()
titleLabel:setString("ParticleFireworks")
return layer
end
---------------------------------
-- DemoSpiral
---------------------------------
local function DemoSpiral()
local layer = getBaseLayer()
emitter = cc.ParticleSpiral:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleSpiral")
return layer
end
---------------------------------
-- DemoSun
---------------------------------
local function DemoSun()
local layer = getBaseLayer()
emitter = cc.ParticleSun:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleSun")
return layer
end
---------------------------------
-- DemoMeteor
---------------------------------
local function DemoMeteor()
local layer = getBaseLayer()
emitter = cc.ParticleMeteor:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleMeteor")
return layer
end
---------------------------------
-- DemoFire
---------------------------------
local function DemoFire()
local layer = getBaseLayer()
emitter = cc.ParticleFire:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, 100)
titleLabel:setString("ParticleFire")
return layer
end
---------------------------------
-- DemoSmoke
---------------------------------
local function DemoSmoke()
local layer = getBaseLayer()
emitter = cc.ParticleSmoke:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, 100)
setEmitterPosition()
titleLabel:setString("ParticleSmoke")
return layer
end
---------------------------------
-- DemoExplosion
---------------------------------
local function DemoExplosion()
local layer = getBaseLayer()
emitter = cc.ParticleExplosion:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1))
emitter:setAutoRemoveOnFinish(true)
setEmitterPosition()
titleLabel:setString("ParticleExplosion")
return layer
end
---------------------------------
-- DemoSnow
---------------------------------
local function DemoSnow()
local layer = getBaseLayer()
emitter = cc.ParticleSnow:create()
-- emitter:retain()
background:addChild(emitter, 10)
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, pos_y - 110)
emitter:setLife(3)
emitter:setLifeVar(1)
-- gravity
emitter:setGravity(cc.p(0, -10))
-- speed of particles
emitter:setSpeed(130)
emitter:setSpeedVar(30)
local startColor = emitter:getStartColor()
startColor.r = 0.9
startColor.g = 0.9
startColor.b = 0.9
emitter:setStartColor(startColor)
local startColorVar = emitter:getStartColorVar()
startColorVar.b = 0.1
emitter:setStartColorVar(startColorVar)
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_snow))
setEmitterPosition()
titleLabel:setString("ParticleSnow")
return layer
end
---------------------------------
-- DemoRain
---------------------------------
local function DemoRain()
local layer = getBaseLayer()
emitter = cc.ParticleRain:create()
-- emitter:retain()
background:addChild(emitter, 10)
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, pos_y - 100)
emitter:setLife(4)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleRain")
return layer
end
---------------------------------
-- DemoBigFlower
---------------------------------
local function DemoBigFlower()
local layer = getBaseLayer()
emitter = cc.ParticleSystemQuad:createWithTotalParticles(50)
background:addChild(emitter, 10)
----emitter:release() -- win32 : use this line or remove this line and use autorelease()
emitter:setTexture( cc.Director:getInstance():getTextureCache():addImage(s_stars1) )
emitter:setDuration(-1)
-- gravity
emitter:setGravity(cc.p(0, 0))
-- angle
emitter:setAngle(90)
emitter:setAngleVar(360)
-- speed of particles
emitter:setSpeed(160)
emitter:setSpeedVar(20)
-- radial
emitter:setRadialAccel(-120)
emitter:setRadialAccelVar(0)
-- tagential
emitter:setTangentialAccel(30)
emitter:setTangentialAccelVar(0)
-- emitter position
emitter:setPosition(160, 240)
emitter:setPosVar(cc.p(0, 0))
-- life of particles
emitter:setLife(4)
emitter:setLifeVar(1)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSizeVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(cc.c4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(cc.c4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(80.0)
emitter:setStartSizeVar(40.0)
emitter:setEndSize(cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE )
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(true)
setEmitterPosition()
titleLabel:setString("ParticleBigFlower")
return layer
end
---------------------------------
-- DemoRotFlower
---------------------------------
local function DemoRotFlower()
local layer = getBaseLayer()
emitter = cc.ParticleSystemQuad:createWithTotalParticles(300)
background:addChild(emitter, 10)
----emitter:release() -- win32 : Remove this line
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars2))
-- duration
emitter:setDuration(-1)
-- gravity
emitter:setGravity(cc.p(0, 0))
-- angle
emitter:setAngle(90)
emitter:setAngleVar(360)
-- speed of particles
emitter:setSpeed(160)
emitter:setSpeedVar(20)
-- radial
emitter:setRadialAccel(-120)
emitter:setRadialAccelVar(0)
-- tagential
emitter:setTangentialAccel(30)
emitter:setTangentialAccelVar(0)
-- emitter position
emitter:setPosition(160, 240)
emitter:setPosVar(cc.p(0, 0))
-- life of particles
emitter:setLife(3)
emitter:setLifeVar(1)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(2000)
-- color of particles
emitter:setStartColor(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(cc.c4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(cc.c4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(30.0)
emitter:setStartSizeVar(0)
emitter:setEndSize(cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE )
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
setEmitterPosition()
titleLabel:setString("ParticleRotFlower")
return layer
end
---------------------------------
-- DemoModernArt
---------------------------------
local function DemoModernArt()
local layer = getBaseLayer()
emitter = cc.ParticleSystemQuad:createWithTotalParticles(1000)
background:addChild(emitter, 10)
----emitter:release()
-- duration
emitter:setDuration(-1)
-- gravity
emitter:setGravity(cc.p(0,0))
-- angle
emitter:setAngle(0)
emitter:setAngleVar(360)
-- radial
emitter:setRadialAccel(70)
emitter:setRadialAccelVar(10)
-- tagential
emitter:setTangentialAccel(80)
emitter:setTangentialAccelVar(0)
-- speed of particles
emitter:setSpeed(50)
emitter:setSpeedVar(10)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(cc.p(0, 0))
-- life of particles
emitter:setLife(2.0)
emitter:setLifeVar(0.3)
-- emits per frame
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- color of particles
emitter:setStartColor(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(cc.c4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(cc.c4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(1.0)
emitter:setStartSizeVar(1.0)
emitter:setEndSize(32.0)
emitter:setEndSizeVar(8.0)
-- texture
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
-- additive
emitter:setBlendAdditive(false)
setEmitterPosition()
titleLabel:setString("Varying size")
return layer
end
---------------------------------
-- DemoRing
---------------------------------
local function DemoRing()
local layer = getBaseLayer()
emitter = cc.ParticleFlower:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1))
emitter:setLifeVar(0)
emitter:setLife(10)
emitter:setSpeed(100)
emitter:setSpeedVar(0)
emitter:setEmissionRate(10000)
setEmitterPosition()
titleLabel:setString("Ring Demo")
return layer
end
---------------------------------
-- ParallaxParticle
---------------------------------
local function ParallaxParticle()
local layer = getBaseLayer()
background:getParent():removeChild(background, true)
background = nil
local p = cc.ParallaxNode:create()
layer:addChild(p, 5)
local p1 = cc.Sprite:create(s_back3)
local p2 = cc.Sprite:create(s_back3)
p:addChild(p1, 1, cc.p(0.5, 1), cc.p(0, 250))
p:addChild(p2, 2, cc.p(1.5, 1), cc.p(0, 50))
emitter = cc.ParticleFlower:create()
-- emitter:retain()
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
p1:addChild(emitter, 10)
emitter:setPosition(250, 200)
local par = cc.ParticleSun:create()
p2:addChild(par, 10)
par:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire))
local move = cc.MoveBy:create(4, cc.p(300,0))
local move_back = move:reverse()
local seq = cc.Sequence:create(move, move_back)
p:runAction(cc.RepeatForever:create(seq))
titleLabel:setString("Parallax + Particles")
return layer
end
---------------------------------
-- DemoParticleFromFile
---------------------------------
local function DemoParticleFromFile(name)
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
local filename = "Particles/" .. name .. ".plist"
emitter = cc.ParticleSystemQuad:create(filename)
layer:addChild(emitter, 10)
setEmitterPosition()
titleLabel:setString(name)
return layer
end
---------------------------------
-- RadiusMode1
---------------------------------
local function RadiusMode1()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = cc.ParticleSystemQuad:createWithTotalParticles(200)
layer:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/stars-grayscale.png"))
-- duration
emitter:setDuration(cc.PARTICLE_DURATION_INFINITY)
-- radius mode
emitter:setEmitterMode(cc.PARTICLE_MODE_RADIUS)
-- radius mode: start and end radius in pixels
emitter:setStartRadius(0)
emitter:setStartRadiusVar(0)
emitter:setEndRadius(160)
emitter:setEndRadiusVar(0)
-- radius mode: degrees per second
emitter:setRotatePerSecond(180)
emitter:setRotatePerSecondVar(0)
-- angle
emitter:setAngle(90)
emitter:setAngleVar(0)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(cc.p(0, 0))
-- life of particles
emitter:setLife(5)
emitter:setLifeVar(0)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(cc.c4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(cc.c4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(32)
emitter:setStartSizeVar(0)
emitter:setEndSize(cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE )
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
titleLabel:setString("Radius Mode: Spiral")
return layer
end
---------------------------------
-- RadiusMode2
---------------------------------
local function RadiusMode2()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = cc.ParticleSystemQuad:createWithTotalParticles(200)
layer:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/stars-grayscale.png"))
-- duration
emitter:setDuration(cc.PARTICLE_DURATION_INFINITY )
-- radius mode
emitter:setEmitterMode(cc.PARTICLE_MODE_RADIUS)
-- radius mode: start and end radius in pixels
emitter:setStartRadius(100)
emitter:setStartRadiusVar(0)
emitter:setEndRadius(cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS)
emitter:setEndRadiusVar(0)
-- radius mode: degrees per second
emitter:setRotatePerSecond(45)
emitter:setRotatePerSecondVar(0)
-- angle
emitter:setAngle(90)
emitter:setAngleVar(0)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(cc.p(0, 0))
-- life of particles
emitter:setLife(4)
emitter:setLifeVar(0)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(cc.c4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(cc.c4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(32)
emitter:setStartSizeVar(0)
emitter:setEndSize(cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE)
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
titleLabel:setString("Radius Mode: Semi Circle")
return layer
end
---------------------------------
-- Issue704
---------------------------------
local function Issue704()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = cc.ParticleSystemQuad:createWithTotalParticles(100)
layer:addChild(emitter, 10)
emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png"))
-- duration
emitter:setDuration(cc.PARTICLE_DURATION_INFINITY)
-- radius mode
emitter:setEmitterMode(cc.PARTICLE_MODE_RADIUS)
-- radius mode: start and end radius in pixels
emitter:setStartRadius(50)
emitter:setStartRadiusVar(0)
emitter:setEndRadius(cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS )
emitter:setEndRadiusVar(0)
-- radius mode: degrees per second
emitter:setRotatePerSecond(0)
emitter:setRotatePerSecondVar(0)
-- angle
emitter:setAngle(90)
emitter:setAngleVar(0)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(cc.p(0, 0))
-- life of particles
emitter:setLife(5)
emitter:setLifeVar(0)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(cc.c4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(cc.c4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(cc.c4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(16)
emitter:setStartSizeVar(0)
emitter:setEndSize(cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE)
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
local rot = cc.RotateBy:create(16, 360)
emitter:runAction(cc.RepeatForever:create(rot))
titleLabel:setString("Issue 704. Free + Rot")
subtitleLabel:setString("Emitted particles should not rotate")
return layer
end
---------------------------------
-- Issue870
---------------------------------
local Issue870_index = nil
local Issue870_entry = nil
local function updateQuads(dt)
update(dt)
Issue870_index = math.mod(Issue870_index + 1, 4)
local rect = cc.rect(Issue870_index * 32, 0, 32, 32)
emitter:setTextureWithRect(emitter:getTexture(), rect)
end
local function Issue870_onEnterOrExit(tag)
local scheduler = cc.Director:getInstance():getScheduler()
if tag == "enter" then
Issue870_entry = scheduler:scheduleScriptFunc(updateQuads, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(Issue870_entry)
end
end
local function Issue870()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
local system = cc.ParticleSystemQuad:create("Particles/SpinningPeas.plist")
system:setTextureWithRect(cc.Director:getInstance():getTextureCache():addImage("Images/particles.png"), cc.rect(0,0,32,32))
layer:addChild(system, 10)
emitter = system
Issue870_index = 0
layer:registerScriptHandler(Issue870_onEnterOrExit)
titleLabel:setString("Issue 870. SubRect")
subtitleLabel:setString("Every 2 seconds the particle should change")
return layer
end
---------------------------------
-- MultipleParticleSystems
---------------------------------
local function MultipleParticleSystems()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
cc.Director:getInstance():getTextureCache():addImage("Images/particles.png")
for i = 0, 4 do
local particleSystem = cc.ParticleSystemQuad:create("Particles/SpinningPeas.plist")
particleSystem:setPosition(i * 50, i * 50)
particleSystem:setPositionType(cc.POSITION_TYPE_GROUPED )
layer:addChild(particleSystem)
end
emitter = nil
titleLabel:setString("Multiple particle systems")
subtitleLabel:setString("v1.1 test: FPS should be lower than next test")
return layer
end
---------------------------------
-- MultipleParticleSystemsBatched
---------------------------------
local function MultipleParticleSystemsBatched()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
local batchNode = cc.ParticleBatchNode:createWithTexture(nil, 3000)
layer:addChild(batchNode, 1, 2)
for i = 0, 4 do
local particleSystem = cc.ParticleSystemQuad:create("Particles/SpinningPeas.plist")
particleSystem:setPositionType(cc.POSITION_TYPE_GROUPED )
particleSystem:setPosition(i * 50, i * 50)
batchNode:setTexture(particleSystem:getTexture())
batchNode:addChild(particleSystem)
end
emitter = nil
titleLabel:setString("Multiple particle systems batched")
subtitleLabel:setString("v1.1 test: should perform better than previous test")
return layer
end
---------------------------------
-- AddAndDeleteParticleSystems
---------------------------------
local AddAndDeleteParticleSystems_entry = nil
local AddAndDeleteParticleSystems_batchNode = nil
local function removeSystem(dt)
update(dt)
local ChildrenCount = table.getn(AddAndDeleteParticleSystems_batchNode:getChildren())
if ChildrenCount > 0 then
cclog("remove random system")
local rand = math.mod(math.random(1, 999999), ChildrenCount - 1)
AddAndDeleteParticleSystems_batchNode:removeChild(AddAndDeleteParticleSystems_batchNode:getChildren()[(rand)], true)
--add new
local particleSystem = cc.ParticleSystemQuad:create("Particles/Spiral.plist")
particleSystem:setPositionType(cc.POSITION_TYPE_GROUPED )
particleSystem:setTotalParticles(200)
particleSystem:setPosition(math.mod(math.random(1, 999999), 300) ,math.mod(math.random(1, 999999), 400))
cclog("add a new system")
local randZ = math.floor(math.random() * 100)
AddAndDeleteParticleSystems_batchNode:addChild(particleSystem, randZ, -1)
end
end
local function AddAndDeleteParticleSystems_onEnterOrExit(tag)
local scheduler = cc.Director:getInstance():getScheduler()
if tag == "enter" then
AddAndDeleteParticleSystems_entry = scheduler:scheduleScriptFunc(removeSystem, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(AddAndDeleteParticleSystems_entry)
end
end
local function AddAndDeleteParticleSystems()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
--adds the texture inside the plist to the texture cache
AddAndDeleteParticleSystems_batchNode = cc.ParticleBatchNode:createWithTexture(nil, 16000)
layer:addChild(AddAndDeleteParticleSystems_batchNode, 1, 2)
for i = 0, 5 do
local particleSystem = cc.ParticleSystemQuad:create("Particles/Spiral.plist")
AddAndDeleteParticleSystems_batchNode:setTexture(particleSystem:getTexture())
particleSystem:setPositionType(cc.POSITION_TYPE_GROUPED )
particleSystem:setTotalParticles(200)
particleSystem:setPosition(i * 15 + 100, i * 15 + 100)
local randZ = math.floor(math.random() * 100)
AddAndDeleteParticleSystems_batchNode:addChild(particleSystem, randZ, -1)
end
layer:registerScriptHandler(AddAndDeleteParticleSystems_onEnterOrExit)
emitter = nil
titleLabel:setString("Add and remove Particle System")
subtitleLabel:setString("v1.1 test: every 2 sec 1 system disappear, 1 appears")
return layer
end
---------------------------------
-- ReorderParticleSystems *
-- problem
---------------------------------
local ReorderParticleSystems_entry = nil
local ReorderParticleSystems_batchNode = nil
local function reorderSystem(dt)
update(dt)
local childArray = ReorderParticleSystems_batchNode:getChildren()
local random = math.random(1,table.getn(childArray))
local child = childArray[random]
-- problem: there's no getLocalZOrder() for cc.Object
-- ReorderParticleSystems_batchNode:reorderChild(child, child:getLocalZOrder() - 1)
ReorderParticleSystems_batchNode:reorderChild(child, math.random(0, 99999))
end
local function ReorderParticleSystems_onEnterOrExit(tag)
local scheduler = cc.Director:getInstance():getScheduler()
if tag == "enter" then
ReorderParticleSystems_entry = scheduler:scheduleScriptFunc(reorderSystem, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(ReorderParticleSystems_entry)
end
end
local function ReorderParticleSystems()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background ,true)
background = nil
ReorderParticleSystems_batchNode = cc.ParticleBatchNode:create("Images/stars-grayscale.png", 3000)
layer:addChild(ReorderParticleSystems_batchNode, 1, 2)
for i = 0, 2 do
local particleSystem = cc.ParticleSystemQuad:createWithTotalParticles(200)
particleSystem:setTexture(ReorderParticleSystems_batchNode:getTexture())
-- duration
particleSystem:setDuration(cc.PARTICLE_DURATION_INFINITY)
-- radius mode
particleSystem:setEmitterMode(cc.PARTICLE_MODE_RADIUS)
-- radius mode: 100 pixels from center
particleSystem:setStartRadius(100)
particleSystem:setStartRadiusVar(0)
particleSystem:setEndRadius(cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS )
particleSystem:setEndRadiusVar(0) -- not used when start == end
-- radius mode: degrees per second
-- 45 * 4 seconds of life = 180 degrees
particleSystem:setRotatePerSecond(45)
particleSystem:setRotatePerSecondVar(0)
-- angle
particleSystem:setAngle(90)
particleSystem:setAngleVar(0)
-- emitter position
particleSystem:setPosVar(cc.p(0, 0))
-- life of particles
particleSystem:setLife(4)
particleSystem:setLifeVar(0)
-- spin of particles
particleSystem:setStartSpin(0)
particleSystem:setStartSpinVar(0)
particleSystem:setEndSpin(0)
particleSystem:setEndSpinVar(0)
-- color of particles
local startColor = cc.c4f(0, 0, 0, 1)
if i == 0 then startColor.r = 1
elseif i == 1 then startColor.g = 1
elseif i == 2 then startColor.b = 1
end
particleSystem:setStartColor(startColor)
particleSystem:setStartColorVar(cc.c4f(0, 0, 0, 0))
local endColor = startColor
particleSystem:setEndColor(endColor)
particleSystem:setEndColorVar(cc.c4f(0, 0, 0, 0))
-- size, in pixels
particleSystem:setStartSize(32)
particleSystem:setStartSizeVar(0)
particleSystem:setEndSize(cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE)
-- emits per second
particleSystem:setEmissionRate(particleSystem:getTotalParticles() / particleSystem:getLife())
-- additive
particleSystem:setPosition(i * 10 + 120, 200)
ReorderParticleSystems_batchNode:addChild(particleSystem)
particleSystem:setPositionType(cc.POSITION_TYPE_FREE )
--particleSystem:release()
end
layer:registerScriptHandler(ReorderParticleSystems_onEnterOrExit)
emitter = nil
titleLabel:setString("reorder systems")
subtitleLabel:setString("changes every 2 seconds")
return layer
end
---------------------------------
-- PremultipliedAlphaTest
---------------------------------
local function PremultipliedAlphaTest()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 255))
layer:removeChild(background, true)
background = nil
emitter = cc.ParticleSystemQuad:create("Particles/BoilingFoam.plist")
emitter:setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
--assert(emitter:getOpacityModifyRGB(), "Particle texture does not have premultiplied alpha, test is useless")
emitter:setStartColor(cc.c4f(1, 1, 1, 1))
emitter:setEndColor(cc.c4f(1, 1, 1, 0))
emitter:setStartColorVar(cc.c4f(0, 0, 0, 0))
emitter:setEndColorVar(cc.c4f(0, 0, 0, 0))
layer:addChild(emitter, 10)
titleLabel:setString("premultiplied alpha")
subtitleLabel:setString("no black halo, particles should fade out")
return layer
end
---------------------------------
-- PremultipliedAlphaTest2
---------------------------------
local function PremultipliedAlphaTest2()
local layer = getBaseLayer()
layer:setColor(cc.c3b(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = cc.ParticleSystemQuad:create("Particles/TestPremultipliedAlpha.plist")
layer:addChild(emitter ,10)
titleLabel:setString("premultiplied alpha 2")
subtitleLabel:setString("Arrows should be faded")
return layer
end
---------------------------------
-- Particle Test
---------------------------------
function CreateParticleLayer()
if SceneIdx == 0 then return ParticleReorder()
elseif SceneIdx == 1 then return ParticleBatchHybrid()
elseif SceneIdx == 2 then return ParticleBatchMultipleEmitters()
elseif SceneIdx == 3 then return DemoFlower()
elseif SceneIdx == 4 then return DemoGalaxy()
elseif SceneIdx == 5 then return DemoFirework()
elseif SceneIdx == 6 then return DemoSpiral()
elseif SceneIdx == 7 then return DemoSun()
elseif SceneIdx == 8 then return DemoMeteor()
elseif SceneIdx == 9 then return DemoFire()
elseif SceneIdx == 10 then return DemoSmoke()
elseif SceneIdx == 11 then return DemoExplosion()
elseif SceneIdx == 12 then return DemoSnow()
elseif SceneIdx == 13 then return DemoRain()
elseif SceneIdx == 14 then return DemoBigFlower()
elseif SceneIdx == 15 then return DemoRotFlower()
elseif SceneIdx == 16 then return DemoModernArt()
elseif SceneIdx == 17 then return DemoRing()
elseif SceneIdx == 18 then return ParallaxParticle()
elseif SceneIdx == 19 then return DemoParticleFromFile("BoilingFoam")
elseif SceneIdx == 20 then return DemoParticleFromFile("BurstPipe")
elseif SceneIdx == 21 then return DemoParticleFromFile("Comet")
elseif SceneIdx == 22 then return DemoParticleFromFile("debian")
elseif SceneIdx == 23 then return DemoParticleFromFile("ExplodingRing")
elseif SceneIdx == 24 then return DemoParticleFromFile("LavaFlow")
elseif SceneIdx == 25 then return DemoParticleFromFile("SpinningPeas")
elseif SceneIdx == 26 then return DemoParticleFromFile("SpookyPeas")
elseif SceneIdx == 27 then return DemoParticleFromFile("Upsidedown")
elseif SceneIdx == 28 then return DemoParticleFromFile("Flower")
elseif SceneIdx == 29 then return DemoParticleFromFile("Spiral")
elseif SceneIdx == 30 then return DemoParticleFromFile("Galaxy")
elseif SceneIdx == 31 then return DemoParticleFromFile("Phoenix")
elseif SceneIdx == 32 then return DemoParticleFromFile("lines")
elseif SceneIdx == 33 then return RadiusMode1()
elseif SceneIdx == 34 then return RadiusMode2()
elseif SceneIdx == 35 then return Issue704()
elseif SceneIdx == 36 then return Issue870()
--elseif SceneIdx == 36 then return Issue1201()
-- v1.1 tests
elseif SceneIdx == 37 then return MultipleParticleSystems()
elseif SceneIdx == 38 then return MultipleParticleSystemsBatched()
elseif SceneIdx == 39 then return AddAndDeleteParticleSystems()
elseif SceneIdx == 40 then return ReorderParticleSystems()
elseif SceneIdx == 41 then return PremultipliedAlphaTest()
elseif SceneIdx == 42 then return PremultipliedAlphaTest2()
end
end
function ParticleTest()
cclog("ParticleTest")
local scene = cc.Scene:create()
SceneIdx = -1
scene:addChild(nextAction())
scene:addChild(CreateBackMenuItem())
return scene
end
| gpl-2.0 |
CarabusX/Zero-K | LuaUI/Widgets/chili/Skins/Carbon/skin.lua | 8 | 5888 | --// =============================================================================
--// Skin
local skin = {
info = {
name = "Carbon",
version = "1.0",
author = "luckywaldo7",
}
}
--// =============================================================================
--//
skin.general = {
focusColor = {0.0, 0.6, 1.0, 1.0},
borderColor = {1.0, 1.0, 1.0, 1.0},
font = {
--font = "FreeSansBold.ttf",
color = {1, 1, 1, 1},
outlineColor = {0.05, 0.05, 0.05, 0.9},
outline = false,
shadow = true,
size = 13,
},
}
skin.icons = {
imageplaceholder = ":cl:placeholder.png",
}
skin.button = {
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {32, 32, 32, 32}, --// tile widths: left, top, right, bottom
padding = {10, 10, 10, 10},
backgroundColor = {1, 1, 1, 1.0},
DrawControl = DrawButton,
}
skin.button_disabled = {
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {32, 32, 32, 32}, --// tile widths: left, top, right, bottom
padding = {10, 10, 10, 10},
color = {0.3, .3, .3, 1},
backgroundColor = {0.1, 0.1, 0.1, 0.8},
DrawControl = DrawButton,
}
skin.checkbox = {
TileImageFG = ":cl:tech_checkbox_checked.png",
TileImageBK = ":cl:tech_checkbox_unchecked.png",
tiles = {8, 8, 8, 8},
boxsize = 12,
DrawControl = DrawCheckbox,
}
skin.editbox = {
backgroundColor = {0.1, 0.1, 0.1, 0},
cursorColor = {1.0, 0.7, 0.1, 0.8},
focusColor = {1, 1, 1, 1},
borderColor = {1, 1, 1, 0.6},
padding = {6, 2, 2, 3},
TileImageBK = ":cl:panel2_bg.png",
TileImageFG = ":cl:panel2.png",
tiles = {8, 8, 8, 8},
DrawControl = DrawEditBox,
}
skin.imagelistview = {
imageFolder = "folder.png",
imageFolderUp = "folder_up.png",
--DrawControl = DrawBackground,
colorBK = {1, 1, 1, 0.3},
colorBK_selected = {1, 0.7, 0.1, 0.8},
colorFG = {0, 0, 0, 0},
colorFG_selected = {1, 1, 1, 1},
imageBK = ":cl:node_selected_bw.png",
imageFG = ":cl:node_selected.png",
tiles = {9, 9, 9, 9},
--tiles = {17, 15, 17, 20},
DrawItemBackground = DrawItemBkGnd,
}
--[[
skin.imagelistviewitem = {
imageFG = ":cl:glassFG.png",
imageBK = ":cl:glassBK.png",
tiles = {17, 15, 17, 20},
padding = {12, 12, 12, 12},
DrawSelectionItemBkGnd = DrawSelectionItemBkGnd,
}
--]]
skin.panel = {
--TileImageFG = ":cl:glassFG.png",
--TileImageBK = ":cl:glassBK.png",
--tiles = {17, 15, 17, 20},
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {32, 32, 32, 32},
backgroundColor = {1, 1, 1, 0.8},
DrawControl = DrawPanel,
}
skin.panelSmall = {
--TileImageFG = ":cl:glassFG.png",
--TileImageBK = ":cl:glassBK.png",
--tiles = {17, 15, 17, 20},
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {16, 16, 16, 16},
backgroundColor = {1, 1, 1, 0.8},
DrawControl = DrawPanel,
}
local fancyPanels = {
"0100",
"0110",
"1100",
"0011",
"1120",
"2100",
"0120",
"0001",
"0021",
"2001",
"2021",
"2120",
"1011",
"2011",
"1021",
}
local fancyPanelsSmall = {
"0011_small",
"1001_small",
"0001_small",
}
for i = 1, #fancyPanels do
local name = "panel_" .. fancyPanels[i]
skin[name] = Spring.Utilities.CopyTable(skin.panel)
skin[name].TileImageBK = ":cl:" .. name .. ".png"
end
for i = 1, #fancyPanelsSmall do
local name = "panel_" .. fancyPanelsSmall[i]
skin[name] = Spring.Utilities.CopyTable(skin.panelSmall)
skin[name].TileImageBK = ":cl:" .. name .. ".png"
end
skin.progressbar = {
TileImageFG = ":cl:tech_progressbar_full.png",
TileImageBK = ":cl:tech_progressbar_empty.png",
tiles = {16, 16, 16, 16},
fillPadding = {4, 3, 4, 3},
font = {
shadow = true,
},
DrawControl = DrawProgressbar,
}
skin.multiprogressbar = {
fillPadding = {4, 3, 4, 3},
}
skin.scrollpanel = {
BorderTileImage = ":cl:panel2_border.png",
bordertiles = {16, 16, 16, 16},
BackgroundTileImage = ":cl:panel2_bg.png",
bkgndtiles = {16, 16, 16, 16},
TileImage = ":cl:tech_scrollbar.png",
tiles = {8, 8, 8, 8},
KnobTileImage = ":cl:tech_scrollbar_knob.png",
KnobTiles = {8, 8, 8, 8},
HTileImage = ":cl:tech_scrollbar.png",
htiles = {8, 8, 8, 8},
HKnobTileImage = ":cl:tech_scrollbar_knob.png",
HKnobTiles = {8, 8, 8, 8},
KnobColorSelected = {0.0, 0.6, 1.0, 1.0},
padding = {2, 2, 2, 2},
scrollbarSize = 12,
DrawControl = DrawScrollPanel,
DrawControlPostChildren = DrawScrollPanelBorder,
}
skin.trackbar = {
TileImage = ":cl:trackbar.png",
tiles = {16, 16, 16, 16}, --// tile widths: left, top, right, bottom
ThumbImage = ":cl:trackbar_thumb.png",
StepImage = ":cl:trackbar_step.png",
hitpadding = {4, 4, 5, 4},
DrawControl = DrawTrackbar,
}
skin.treeview = {
--ImageNode = ":cl:node.png",
ImageNodeSelected = ":cl:node_selected.png",
tiles = {16, 16, 16, 16},
ImageExpanded = ":cl:treeview_node_expanded.png",
ImageCollapsed = ":cl:treeview_node_collapsed.png",
treeColor = {1, 1, 1, 0.1},
DrawNode = DrawTreeviewNode,
DrawNodeTree = DrawTreeviewNodeTree,
}
skin.window = {
TileImage = ":cl:tech_dragwindow.png",
--TileImage = ":cl:tech_window.png",
--TileImage = ":cl:window_tooltip.png",
--tiles = {25, 25, 25, 25}, --// tile widths: left, top, right, bottom
tiles = {64, 64, 64, 64}, --// tile widths: left, top, right, bottom
padding = {13, 13, 13, 13},
hitpadding = {4, 4, 4, 4},
color = {1, 1, 1, 1.0},
captionColor = {1, 1, 1, 0.45},
boxes = {
resize = {-21, -21, -10, -10},
drag = {0, 0, "100%", 10},
},
NCHitTest = NCHitTestWithPadding,
NCMouseDown = WindowNCMouseDown,
NCMouseDownPostChildren = WindowNCMouseDownPostChildren,
DrawControl = DrawWindow,
DrawDragGrip = function() end,
DrawResizeGrip = DrawResizeGrip,
}
skin.control = skin.general
--// =============================================================================
--//
return skin
| gpl-2.0 |
CarabusX/Zero-K | lups/headers/tablebin.lua | 8 | 3185 | -- $Id: tablebin.lua 3171 2008-11-06 09:06:29Z det $
--[[
Binary Search a Table
Binary Insert into Table (faster than table.insert and table.sort combined)
v 0.3
Lua 5.1 compatible
]]--
--[[
table.binsearch( table, value [, compval [, reversed] ] )
Searches the table through BinarySearch for the given value.
If the value is found:
it returns a table holding all the mathing indices (e.g. { startindice,endindice } )
endindice may be the same as startindice if only one matching indice was found
If compval is given:
then it must be a function that takes one value and returns a second value2,
to be compared with the input value, e.g.:
compvalue = function( value ) return value[1] end
If reversed is set to true:
then the search assumes that the table is sorted in reverse order (largest value at position 1)
note when reversed is given compval must be given as well, it can be nil/_ in this case
Return value:
on success: a table holding matching indices (e.g. { startindice,endindice } )
on failure: nil
]]--
do
-- Avoid heap allocs for performance
local default_fcompval = function( value ) return value end
local fcompf = function( a,b ) return a < b end
local fcompr = function( a,b ) return a > b end
function table.binsearch( t,value,fcompval,reversed )
-- Initialise functions
local fcompval = fcompval or default_fcompval
local fcomp = reversed and fcompr or fcompf
-- Initialise numbers
local iStart,iEnd,iMid = 1,#t,0
-- Binary Search
while iStart <= iEnd do
-- calculate middle
iMid = math.floor( (iStart+iEnd)/2 )
-- get compare value
local value2 = fcompval( t[iMid] )
-- get all values that match
if value == value2 then
local tfound,num = { iMid,iMid },iMid - 1
while value == fcompval( t[num] ) do
tfound[1],num = num,num - 1
end
num = iMid + 1
while value == fcompval( t[num] ) do
tfound[2],num = num,num + 1
end
return tfound
-- keep searching
elseif fcomp( value,value2 ) then
iEnd = iMid - 1
else
iStart = iMid + 1
end
end
end
end
--[[
table.bininsert( table, value [, comp] )
Inserts a given value through BinaryInsert into the table sorted by [, comp].
If 'comp' is given, then it must be a function that receives
two table elements, and returns true when the first is less
than the second, e.g. comp = function(a, b) return a > b end,
will give a sorted table, with the biggest value on position 1.
[, comp] behaves as in table.sort(table, value [, comp])
returns the index where 'value' was inserted
]]--
do
-- Avoid heap allocs for performance
local fcomp_default = function( a,b ) return a < b end
function table.bininsert(t, value, fcomp)
-- Initialise compare function
local fcomp = fcomp or fcomp_default
-- Initialise numbers
local iStart,iEnd,iMid,iState = 1,#t,1,0
-- Get insert position
while iStart <= iEnd do
-- calculate middle
iMid = math.floor( (iStart+iEnd)/2 )
-- compare
if fcomp( value,t[iMid] ) then
iEnd,iState = iMid - 1,0
else
iStart,iState = iMid + 1,1
end
end
table.insert( t,(iMid+iState),value )
return (iMid+iState)
end
end
-- CHILLCODE
| gpl-2.0 |
dani-sj/komyl | plugins/google.lua | 94 | 1176 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
clandmeter/aports-turbo | controller.lua | 1 | 7056 | local turbo = require("turbo")
-- we use lustache instead of turbo's limited mustache engine
local lustache = require("lustache")
local conf = require("config")
local db = require("db")
local mail = require("mail")
local model = require("model")
local cntrl = class("cntrl")
-- move all model parts to model.lua
function cntrl:packages(args)
local m = {}
-- get packages
local offset = (args.page - 1) * conf.pager.limit
local pkgs = db:getPackages(args, offset)
m.pkgs = model:packages(pkgs)
local distinct = {
branch = db:getDistinct("packages", "branch"),
repo = db:getDistinct("packages", "repo"),
arch = db:getDistinct("packages", "arch"),
maintainer = db:getDistinct("maintainer", "name"),
}
table.insert(distinct.maintainer, 1, "None")
-- navigation bar
m.nav = {package="active"}
-- create form
m.form = model:packagesForm(args, distinct)
-- create pager
local qty = db:countPackages(args)
local pager = self:createPager(qty, conf.pager.limit, args.page, conf.pager.offset)
m.pager = model:pagerModel(args, pager)
-- render templates
m.header = lustache:render(self:tpl("header.tpl"), m)
m.footer = lustache:render(self:tpl("footer.tpl"), m)
return lustache:render(self:tpl("packages.tpl"), m)
end
function cntrl:getPackage(ops)
return db:getPackage(ops)
end
function cntrl:package(pkg, m)
local m = m or {}
-- package
pkg.size = self:humanBytes(pkg.size)
pkg.installed_size = self:humanBytes(pkg.installed_size)
m.pkg = model:package(pkg)
-- depends
local depends = db:getDepends(pkg)
m.deps = model:packageRelations(depends)
m.deps_qty = #depends or 0
-- provides
local provides = db:getProvides(pkg)
m.reqbys = model:packageRelations(provides)
m.reqbys_qty = #provides or 0
-- origins
local origins = db:getOrigins(pkg)
m.subpkgs = model:packageRelations(origins)
m.subpkgs_qty = #origins or 0
-- navigation bar
m.nav = {package="active"}
-- templates
m.header = lustache:render(self:tpl("header.tpl"), m)
m.footer = lustache:render(self:tpl("footer.tpl"), m)
return lustache:render(self:tpl("package.tpl"), m)
end
function cntrl:contents(args)
local m = {}
local distinct = {
branch = db:getDistinct("packages", "branch"),
repo = db:getDistinct("packages", "repo"),
arch = db:getDistinct("packages", "arch"),
}
-- navigation menu
m.nav = {content="active"}
-- search form
m.form = model:contentsForm(args, distinct)
-- do not run any queries without any terms.
if not (args.file == "" and args.path == "" and args.name == "") then
-- get contents
local offset = (args.page - 1) * conf.pager.limit
local contents = db:getContents(args, offset)
m.contents = model:contents(contents)
-- pager
local qty = db:countContents(args)
local pager = self:createPager(qty, conf.pager.limit, args.page, conf.pager.offset)
m.pager = model:pagerModel(args, pager)
end
-- render templates
m.header = lustache:render(self:tpl("header.tpl"), m)
m.footer = lustache:render(self:tpl("footer.tpl"), m)
return lustache:render(self:tpl("contents.tpl"), m)
end
function cntrl:flag(pkg, m)
if pkg and not pkg.fid then
local m = model:flag(pkg, m)
m.header = lustache:render(self:tpl("header.tpl"), m)
m.footer = lustache:render(self:tpl("footer.tpl"), m)
if pkg.branch == "edge" then
return lustache:render(self:tpl("flag.tpl"), m)
else
return lustache:render(self:tpl("reject_flag.tpl"), m)
end
end
end
function cntrl:flagMail(args, pkg)
local subject = string.format(
"Alpine aport %s has been flagged out of date",
pkg.origin
)
local m = model:flagMail(pkg, args)
mail:initialize(conf)
mail:set_to(pkg.memail)
mail:set_subject(subject)
local body = lustache:render(self:tpl("mail_body.tpl"), m)
mail:set_body(body)
return mail:send()
end
function cntrl:flagged(args)
local m = {}
-- get packages
local offset = (args.page - 1) * conf.pager.limit
local pkgs, qty = db:getFlagged(args, offset)
m.pkgs = model:flagged(pkgs)
local distinct = {
branch = db:getDistinct("packages", "branch"),
repo = db:getDistinct("packages", "repo"),
arch = db:getDistinct("packages", "arch"),
maintainer = db:getDistinct("maintainer", "name"),
}
table.insert(distinct.maintainer, 1, "None")
-- create form
m.form = model:flaggedForm(args, distinct)
-- navigation menu
m.nav = {flagged="active"}
-- create pager
local pager = self:createPager(qty, conf.pager.limit, args.page, conf.pager.offset)
m.pager = model:pagerModel(args, pager)
-- render templates
m.header = lustache:render(self:tpl("header.tpl"), m)
m.footer = lustache:render(self:tpl("footer.tpl"), m)
return lustache:render(self:tpl("flagged.tpl"), m)
end
----
-- get non flagged package based on options
----
function cntrl:getNotFlagged(ops)
local pkg = db:getPackage(ops)
if pkg and not pkg.fid then
return pkg
end
end
-- create a array with pager page numbers
-- (total) total amount of results
-- (limit) results per page/query
-- (current) the current page
-- (offset) the left and right offset from current page
function cntrl:createPager(total, limit, current, offset)
local r = {}
local pages = math.ceil(total/limit)
local pagers = math.min(offset*2+1, pages)
local first = math.max(1, current - offset)
local last = math.min(pages, (pagers + first - 1))
local size = (last-first+1)
if size < pagers then
first = first - (pagers - size)
end
for p = first, last do
table.insert(r, p)
end
r.last = pages
return r
end
----
-- verify recaptch responce
----
function cntrl:verifyRecaptcha(response)
local uri = "https://www.google.com/recaptcha/api/siteverify"
local kwargs = {}
kwargs.method = "POST"
kwargs.params = {
secret = conf.rc.secret,
response = response
}
local res = coroutine.yield(turbo.async.HTTPClient():fetch(uri, kwargs))
if res.error then
return false
end
local result = turbo.escape.json_decode(res.body)
return result.success
end
-- convert bytes to human readable
function cntrl:humanBytes(bytes)
local mult = 10^(2)
local size = { 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' }
local factor = math.floor((string.len(bytes) -1) /3)
local result = bytes/math.pow(1024, factor)
return math.floor(result * mult + 0.5) / mult.." "..size[factor+1]
end
-- read the tpl file into a string and return it
function cntrl:tpl(tpl)
local tpl = string.format("%s/%s", conf.tpl, tpl)
local f = io.open(tpl, "rb")
local r = f:read("*all")
f:close()
return r
end
return cntrl
| mit |
mattyx14/otxserver | data/scripts/movements/others/closing_door.lua | 2 | 3349 | -- Level and quests closing door (onStepIn).
-- This prevents a player who has not yet done the quest, from crossing the player who has already done so, skipping the entire quest and going straight to the final reward.
local closingDoor = MoveEvent()
local doorIds = {}
for index, value in ipairs(QuestDoorTable) do
if not table.contains(doorIds, value.openDoor) then
table.insert(doorIds, value.openDoor)
end
end
for index, value in ipairs(LevelDoorTable) do
if not table.contains(doorIds, value.openDoor) then
table.insert(doorIds, value.openDoor)
end
end
function closingDoor.onStepIn(creature, item, position, fromPosition)
local player = creature:getPlayer()
if not player then
return
end
for index, value in ipairs(QuestDoorTable) do
if value.openDoor == item.itemid then
if player:getStorageValue(item.actionid) ~= -1 then
return true
else
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "The door seems to be sealed against unwanted intruders.")
player:teleportTo(fromPosition, true)
return false
end
end
end
for index, value in ipairs(LevelDoorTable) do
if value.openDoor == item.itemid then
if item.actionid > 0 and player:getLevel() >= item.actionid - 1000 then
return true
else
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Only the worthy may pass.")
player:teleportTo(fromPosition, true)
return false
end
end
end
return true
end
for index, value in ipairs(doorIds) do
closingDoor:id(value)
end
closingDoor:register()
-- Level and quests closing door (onStepOut).
-- This closes the door after the player passes through it.
local closingDoor = MoveEvent()
local doorIds = {}
for index, value in ipairs(QuestDoorTable) do
if not table.contains(doorIds, value.openDoor) then
table.insert(doorIds, value.openDoor)
end
end
for index, value in ipairs(LevelDoorTable) do
if not table.contains(doorIds, value.openDoor) then
table.insert(doorIds, value.openDoor)
end
end
function closingDoor.onStepOut(creature, item, position, fromPosition)
local player = creature:getPlayer()
if not player then
return
end
local tile = Tile(position)
if tile:getCreatureCount() > 0 then
return true
end
local newPosition = {x = position.x + 1, y = position.y, z = position.z}
local query = Tile(newPosition):queryAdd(creature)
if query ~= RETURNVALUE_NOERROR or query == RETURNVALUE_NOTENOUGHROOM then
newPosition.x = newPosition.x - 1
newPosition.y = newPosition.y + 1
query = Tile(newPosition):queryAdd(creature)
end
if query == RETURNVALUE_NOERROR or query ~= RETURNVALUE_NOTENOUGHROOM then
position:relocateTo(newPosition)
end
local i, tileItem, tileCount = 1, true, tile:getThingCount()
while tileItem and i < tileCount do
tileItem = tile:getThing(i)
if tileItem and tileItem:getUniqueId() ~= item.uid and tileItem:getType():isMovable() then
tileItem:remove()
else
i = i + 1
end
end
for index, value in ipairs(LevelDoorTable) do
if value.openDoor == item.itemid then
item:transform(value.closedDoor)
end
end
for index, value in ipairs(QuestDoorTable) do
if value.openDoor == item.itemid then
item:transform(value.closedDoor)
end
end
return true
end
for index, value in ipairs(doorIds) do
closingDoor:id(value)
end
closingDoor:register()
| gpl-2.0 |
hust921/dotfiles | config/nvim/lua/user/alpha.lua | 1 | 1056 | local alpha = require('alpha')
local startify = require('alpha.themes.startify')
startify.section.header.val = {
[[ __ ]],
[[ ___ ___ ___ __ __ /\_\ ___ ___ ]],
[[ / _ `\ / __`\ / __`\/\ \/\ \\/\ \ / __` __`\ ]],
[[ /\ \/\ \/\ __//\ \_\ \ \ \_/ |\ \ \/\ \/\ \/\ \ ]],
[[ \ \_\ \_\ \____\ \____/\ \___/ \ \_\ \_\ \_\ \_\]],
[[ \/_/\/_/\/____/\/___/ \/__/ \/_/\/_/\/_/\/_/]],
}
startify.section.top_buttons.val = {
startify.button( "e", " New file" , ":ene <BAR> startinsert <CR>"),
startify.button( "cc", " Clipboard OPEN" , ':enew<CR>:normal "+p<CR>'),
startify.button( "cj", " Clipboard JSON" , ':enew<CR>:normal "+p<CR>:FormatJson<CR>'),
startify.button( "cx", "謹 Clipboard XML" , ':enew<CR>:normal "+p<CR>:FormatXml<CR>'),
startify.button( "ch", " Clipboard HTML" , ':enew<CR>:normal "+p<CR>:FormatHtml<CR>'),
}
alpha.setup(startify.opts)
| mit |
CarabusX/Zero-K | LuaUI/callins.lua | 4 | 2350 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: callins.lua
-- brief: array and map of call-ins
-- author: Dave Rodgers
--
-- Copyright (C) 2007.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
CallInsList = {
"Shutdown",
"LayoutButtons",
"ConfigureLayout",
"CommandNotify",
"UnitCommandNotify",
"KeyPress",
"KeyRelease",
"TextInput",
"TextEditing",
"MouseMove",
"MousePress",
"MouseRelease",
"JoyAxis",
"JoyHat",
"JoyButtonDown",
"JoyButtonUp",
"IsAbove",
"GetTooltip",
"AddConsoleLine",
"GroupChanged",
"WorldTooltip",
"GameLoadLua",
"GameStartPlaying",
"GameOver",
"TeamDied",
"UnitCreated",
"UnitFinished",
"UnitFromFactory",
"UnitReverseBuilt",
"UnitDestroyed",
"RenderUnitDestroyed",
"UnitTaken",
"UnitGiven",
"UnitIdle",
"UnitCommand",
"UnitSeismicPing",
"UnitEnteredRadar",
"UnitEnteredLos",
"UnitLeftRadar",
"UnitLeftLos",
"UnitLoaded",
"UnitUnloaded",
"UnitHarvestStorageFull",
"UnitEnteredWater",
"UnitEnteredAir",
"UnitLeftWater",
"UnitLeftAir",
"FeatureCreated",
"FeatureDestroyed",
"DrawGenesis",
"DrawWater",
"DrawSky",
"DrawSun",
"DrawGrass",
"DrawTrees",
"DrawWorld",
"DrawWorldPreUnit",
"DrawWorldPreParticles",
"DrawWorldShadow",
"DrawWorldReflection",
"DrawWorldRefraction",
"DrawScreenEffects",
"DrawScreenPost",
"DrawScreen",
"DrawInMiniMap",
"Explosion",
"ShockFront",
"RecvSkirmishAIMessage",
"GameFrame",
"CobCallback",
"AllowCommand",
"CommandFallback",
"AllowUnitCreation",
"AllowUnitTransfer",
"AllowUnitBuildStep",
"AllowFeatureCreation",
"AllowFeatureBuildStep",
"AllowResourceLevel",
"AllowResourceTransfer",
"GameProgress",
"DownloadQueued",
"DownloadStarted",
"DownloadFinished",
"DownloadFailed",
"DownloadProgress",
"Save",
"Load",
}
-- make the map
CallInsMap = {}
for _, callin in ipairs(CallInsList) do
CallInsMap[callin] = true
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
mojo2012/factorio-mojo-resource-processing | prototypes/item/ore-processing/ore-tin.lua | 1 | 1114 | require("ore-general")
-- item definitions
data:extend({
{
type= "item",
name= "ore-tin-crushed",
icon = "__mojo-resource-processing__/graphics/icons/ore-tin/crushed-ore-tin.png",
flags= { "goes-to-main-inventory" },
subgroup = "tin",
order = "f[ore-tin-crushed]",
stack_size= 50,
},
{
type= "item",
name= "ore-tin-pulverized",
icon = "__mojo-resource-processing__/graphics/icons/ore-tin/pulverized-ore-tin.png",
flags= { "goes-to-main-inventory" },
subgroup = "tin",
order = "f[ore-tin-pulverized]",
stack_size= 50,
}
})
-- item subgroup definition
data:extend({
{
type = "item-subgroup",
name = "tin",
group = "intermediate-products",
order = "b2"
}
})
data.raw.item["tin-ore"].subgroup = "tin"
-- Minable ressources
data.raw["resource"]["tin-ore"].minable.result = nil
data.raw["resource"]["tin-ore"].minable.results = {
ressourceItemMinMaxProb("tin-ore", 1, 1, 0.9), -- 1 item at percentage 0.9 --
ressourceItemMinMaxProb("gravel", 1, 1, 0.45),
ressourceItemMinMaxProb("dirt", 1, 1, 0.4)
}
| gpl-3.0 |
mattyx14/otxserver | data/monster/quests/cults_of_tibia/bosses/wine_cask.lua | 2 | 1714 | local mType = Game.createMonsterType("Wine Cask")
local monster = {}
monster.description = "a wine cask"
monster.experience = 0
monster.outfit = {
lookTypeEx = 2521
}
monster.health = 30000
monster.maxHealth = 30000
monster.race = "blood"
monster.corpse = 0
monster.speed = 0
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 20
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = false,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = false,
canPushCreatures = false,
staticAttackChance = 95,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.events = {
"Splash"
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
}
monster.defenses = {
defense = 35,
armor = 35
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = -20},
{type = COMBAT_ENERGYDAMAGE, percent = 50},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = 50},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 50},
{type = COMBAT_HOLYDAMAGE , percent = 50},
{type = COMBAT_DEATHDAMAGE , percent = 50}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
houqp/koreader-base | ffi/linux_input_h.lua | 1 | 1320 | local ffi = require("ffi")
ffi.cdef[[
static const int EVIOCGRAB = 1074021776;
static const int EV_SYN = 0;
static const int EV_KEY = 1;
static const int EV_REL = 2;
static const int EV_ABS = 3;
static const int EV_MSC = 4;
static const int EV_SW = 5;
static const int EV_LED = 17;
static const int EV_SND = 18;
static const int EV_REP = 20;
static const int EV_FF = 21;
static const int EV_PWR = 22;
static const int EV_FF_STATUS = 23;
static const int EV_MAX = 31;
static const int SYN_REPORT = 0;
static const int SYN_CONFIG = 1;
static const int SYN_MT_REPORT = 2;
static const int SYN_DROPPED = 3;
static const int ABS_MT_SLOT = 47;
static const int ABS_MT_TOUCH_MAJOR = 48;
static const int ABS_MT_TOUCH_MINOR = 49;
static const int ABS_MT_WIDTH_MAJOR = 50;
static const int ABS_MT_WIDTH_MINOR = 51;
static const int ABS_MT_ORIENTATION = 52;
static const int ABS_MT_POSITION_X = 53;
static const int ABS_MT_POSITION_Y = 54;
static const int ABS_MT_TOOL_TYPE = 55;
static const int ABS_MT_BLOB_ID = 56;
static const int ABS_MT_TRACKING_ID = 57;
static const int ABS_MT_PRESSURE = 58;
static const int ABS_MT_DISTANCE = 59;
static const int ABS_MT_TOOL_X = 60;
static const int ABS_MT_TOOL_Y = 61;
struct input_event {
struct timeval time;
short unsigned int type;
short unsigned int code;
int value;
};
]]
| agpl-3.0 |
mattyx14/otxserver | data/monster/magicals/feversleep.lua | 2 | 3873 | local mType = Game.createMonsterType("Feversleep")
local monster = {}
monster.description = "a feversleep"
monster.experience = 4400
monster.outfit = {
lookType = 593,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 1021
monster.Bestiary = {
class = "Magical",
race = BESTY_RACE_MAGICAL,
toKill = 1000,
FirstUnlock = 50,
SecondUnlock = 500,
CharmsPoints = 25,
Stars = 3,
Occurrence = 0,
Locations = "Roshamuul Mines, Roshamuul Cistern."
}
monster.health = 5900
monster.maxHealth = 5900
monster.race = "blood"
monster.corpse = 20163
monster.speed = 360
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = true
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
{name = "gold coin", chance = 100000, maxCount = 100},
{name = "small emerald", chance = 11000, maxCount = 2},
{name = "small amethyst", chance = 12000, maxCount = 3},
{name = "platinum coin", chance = 100000, maxCount = 9},
{name = "blue robe", chance = 1500},
{name = "great mana potion", chance = 40000, maxCount = 2},
{name = "ultimate health potion", chance = 18000},
{name = "small topaz", chance = 16000, maxCount = 2},
{name = "blue crystal shard", chance = 11000},
{name = "blue crystal splinter", chance = 13000},
{name = "cyan crystal fragment", chance = 18000},
{name = "trapped bad dream monster", chance = 17000},
{name = "bowl of terror sweat", chance = 14000}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -450},
-- poison
{name ="condition", type = CONDITION_POISON, interval = 2000, chance = 20, minDamage = -800, maxDamage = -1000, radius = 7, effect = CONST_ME_YELLOW_RINGS, target = false},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_MANADRAIN, minDamage = -70, maxDamage = -100, radius = 5, effect = CONST_ME_MAGIC_RED, target = false},
{name ="feversleep skill reducer", interval = 2000, chance = 10, target = false},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_LIFEDRAIN, minDamage = -250, maxDamage = -300, length = 6, spread = 3, effect = CONST_ME_YELLOWENERGY, target = true},
{name ="combat", interval = 2000, chance = 15, type = COMBAT_DEATHDAMAGE, minDamage = -150, maxDamage = -300, radius = 1, shootEffect = CONST_ANI_SUDDENDEATH, effect = CONST_ME_MORTAREA, target = true}
}
monster.defenses = {
defense = 45,
armor = 45,
{name ="combat", interval = 2000, chance = 20, type = COMBAT_HEALING, minDamage = 250, maxDamage = 425, effect = CONST_ME_MAGIC_BLUE, target = false},
{name ="invisible", interval = 2000, chance = 10, effect = CONST_ME_HITAREA}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 15},
{type = COMBAT_ENERGYDAMAGE, percent = 10},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = 35},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 20},
{type = COMBAT_HOLYDAMAGE , percent = -10},
{type = COMBAT_DEATHDAMAGE , percent = 55}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
mattyx14/otxserver | data/monster/event_creatures/memory_creatures/memory_of_a_golem.lua | 2 | 2959 | local mType = Game.createMonsterType("Memory Of A Golem")
local monster = {}
monster.description = "a memory of a golem"
monster.experience = 1620
monster.outfit = {
lookType = 600,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 3660
monster.maxHealth = 3660
monster.race = "venom"
monster.corpse = 20972
monster.speed = 260
monster.manaCost = 0
monster.changeTarget = {
interval = 5000,
chance = 8
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = true,
canWalkOnFire = false,
canWalkOnPoison = true
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "*slosh*", yell = false},
{text = "*clank*", yell = false}
}
monster.loot = {
{name = "gold coin", chance = 100000, maxCount = 160},
{name = "small topaz", chance = 7000, maxCount = 2},
{name = "great mana potion", chance = 18830, maxCount = 2},
{name = "bronze gear wheel", chance = 3000},
{name = "small emerald", chance = 7430, maxCount = 2},
{id = 37531, chance = 5155}, -- candy floss
{name = "special fx box", chance = 1500},
{name = "heat core", chance = 5155}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, skill = 60, attack = 50},
{name ="melee", interval = 2000, chance = 2, skill = 86, attack = 100},
{name ="combat", interval = 2000, chance = 25, type = COMBAT_ENERGYDAMAGE, minDamage = -50, maxDamage = -150, range = 7, shootEffect = CONST_ANI_ENERGY, target = false},
{name ="war golem skill reducer", interval = 2000, chance = 16, target = false},
}
monster.defenses = {
defense = 45,
armor = 40,
{name ="speed", interval = 2000, chance = 13, speedChange = 404, effect = CONST_ME_MAGIC_RED, target = false, duration = 4000},
{name ="combat", interval = 2000, chance = 20, type = COMBAT_HEALING, minDamage = 200, maxDamage = 250, effect = CONST_ME_MAGIC_BLUE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 10},
{type = COMBAT_ENERGYDAMAGE, percent = 5},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = 10},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = 15},
{type = COMBAT_DEATHDAMAGE , percent = 30}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
CarabusX/Zero-K | gamedata/modularcomms/weapons/hparticlebeam.lua | 6 | 1100 | local name = "commweapon_hparticlebeam"
local weaponDef = {
name = [[Heavy Particle Beam]],
beamDecay = 0.9,
beamTime = 1/30,
beamttl = 75,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
is_unit_weapon = 1,
slot = [[5]],
light_color = [[0.4 1.6 0.4]],
light_radius = 120,
reaim_time = 1,
},
damage = {
default = 800,
},
explosionGenerator = [[custom:flash2green_large]],
fireStarter = 100,
impactOnly = true,
impulseFactor = 0,
interceptedByShieldType = 1,
laserFlareSize = 10,
minIntensity = 1,
range = 390,
reloadtime = 3.1,
rgbColor = [[0 1 0]],
soundStart = [[weapon/laser/small_laser_fire4]],
soundStartVolume = 5,
thickness = 8,
tolerance = 8192,
turret = true,
weaponType = [[BeamLaser]],
}
return name, weaponDef
| gpl-2.0 |
piccaso/debian-luakit | config/modes.lua | 15 | 5034 | -------------------------------
-- luakit mode configuration --
-------------------------------
-- Table of modes and their callback hooks
local modes = {}
local lousy = require "lousy"
local join = lousy.util.table.join
local order = 0
-- Add new mode table (optionally merges with original mode)
function new_mode(name, desc, mode, replace)
assert(string.match(name, "^[%w-_]+$"), "invalid mode name: " .. name)
-- Detect optional description
if type(desc) == "table" then
desc, mode, replace = nil, desc, mode
end
local traceback = debug.traceback("Creation traceback:", 2)
order = order + 1
modes[name] = join({ order = order, traceback = traceback },
(not replace and modes[name]) or {}, mode or {},
{ name = name, desc = desc })
end
-- Get mode table
function get_mode(name) return modes[name] end
function get_modes() return lousy.util.table.clone(modes) end
-- Attach window & input bar signals for mode hooks
window.init_funcs.modes_setup = function (w)
-- Calls the `enter` and `leave` mode hooks.
w:add_signal("mode-changed", function (_, name, ...)
local leave = (w.mode or {}).leave
-- Get new modes functions/hooks/data
local mode = assert(modes[name], "invalid mode: " .. name)
-- Call last modes leave hook.
if leave then leave(w) end
-- Create w.mode object
w.mode = mode
-- Update window binds
w:update_binds(name)
-- Call new modes enter hook.
if mode.enter then mode.enter(w, ...) end
w:emit_signal("mode-entered", mode)
end)
local input = w.ibar.input
-- Calls the changed hook on input widget changed.
input:add_signal("changed", function ()
local changed = w.mode.changed
if changed then changed(w, input.text) end
end)
input:add_signal("property::position", function ()
local move_cursor = w.mode.move_cursor
if move_cursor then move_cursor(w, input.position) end
end)
-- Calls the `activate` hook on input widget activate.
input:add_signal("activate", function ()
local mode = w.mode
if mode and mode.activate then
local text, hist = input.text, mode.history
if mode.activate(w, text) == false then return end
-- Check if last history item is identical
if hist and hist.items and hist.items[hist.len or -1] ~= text then
table.insert(hist.items, text)
end
end
end)
end
-- Add mode related window methods
window.methods.set_mode = lousy.mode.set
local mget = lousy.mode.get
window.methods.is_mode = function (w, name) return name == mget(w) end
-- Setup normal mode
new_mode("normal", [[When luakit first starts you will find yourself in this
mode.]], {
enter = function (w)
w:set_prompt()
w:set_input()
end,
})
new_mode("all", [[Special meta-mode in which the bindings for this mode are
present in all modes.]])
-- Setup insert mode
new_mode("insert", [[When clicking on form fields luakit will enter the insert
mode which allows you to enter text in form fields without accidentally
triggering normal mode bindings.]], {
enter = function (w)
w:set_prompt("-- INSERT --")
w:set_input()
w.view:focus()
end,
-- Send key events to webview
passthrough = true,
})
new_mode("passthrough", [[Luakit will pass every key event to the WebView
until the user presses Escape.]], {
enter = function (w)
w:set_prompt("-- PASS THROUGH --")
w:set_input()
end,
-- Send key events to webview
passthrough = true,
-- Don't exit mode when clicking outside of form fields
reset_on_focus = false,
-- Don't exit mode on navigation
reset_on_navigation = false,
})
-- Setup command mode
new_mode("command", [[Enter commands.]], {
enter = function (w)
w:set_prompt()
w:set_input(":")
end,
changed = function (w, text)
-- Auto-exit command mode if user backspaces ":" in the input bar.
if not string.match(text, "^:") then w:set_mode() end
end,
activate = function (w, text)
w:set_mode()
local cmd = string.sub(text, 2)
if not string.find(cmd, "%S") then return end
local success, match = xpcall(
function () return w:match_cmd(cmd) end,
function (err) w:error(debug.traceback(err, 3)) end)
if success and not match then
w:error(string.format("Not a browser command: %q", cmd))
end
end,
history = {maxlen = 50},
})
new_mode("lua", [[Execute arbitrary Lua commands within the luakit
environment.]], {
enter = function (w)
w:set_prompt(">")
w:set_input("")
end,
activate = function (w, text)
w:set_input("")
local ret = assert(loadstring("return function(w) return "..text.." end"))()(w)
if ret then print(ret) end
end,
history = {maxlen = 50},
})
| gpl-3.0 |
fo369/luci-1505 | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-pbx.lua | 68 | 1923 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
pbx_ael = module:option(ListValue, "pbx_ael", "Asterisk Extension Language Compiler", "")
pbx_ael:value("yes", "Load")
pbx_ael:value("no", "Do Not Load")
pbx_ael:value("auto", "Load as Required")
pbx_ael.rmempty = true
pbx_config = module:option(ListValue, "pbx_config", "Text Extension Configuration", "")
pbx_config:value("yes", "Load")
pbx_config:value("no", "Do Not Load")
pbx_config:value("auto", "Load as Required")
pbx_config.rmempty = true
pbx_functions = module:option(ListValue, "pbx_functions", "load => .so ; Builtin dialplan functions", "")
pbx_functions:value("yes", "Load")
pbx_functions:value("no", "Do Not Load")
pbx_functions:value("auto", "Load as Required")
pbx_functions.rmempty = true
pbx_loopback = module:option(ListValue, "pbx_loopback", "Loopback Switch", "")
pbx_loopback:value("yes", "Load")
pbx_loopback:value("no", "Do Not Load")
pbx_loopback:value("auto", "Load as Required")
pbx_loopback.rmempty = true
pbx_realtime = module:option(ListValue, "pbx_realtime", "Realtime Switch", "")
pbx_realtime:value("yes", "Load")
pbx_realtime:value("no", "Do Not Load")
pbx_realtime:value("auto", "Load as Required")
pbx_realtime.rmempty = true
pbx_spool = module:option(ListValue, "pbx_spool", "Outgoing Spool Support", "")
pbx_spool:value("yes", "Load")
pbx_spool:value("no", "Do Not Load")
pbx_spool:value("auto", "Load as Required")
pbx_spool.rmempty = true
pbx_wilcalu = module:option(ListValue, "pbx_wilcalu", "Wil Cal U (Auto Dialer)", "")
pbx_wilcalu:value("yes", "Load")
pbx_wilcalu:value("no", "Do Not Load")
pbx_wilcalu:value("auto", "Load as Required")
pbx_wilcalu.rmempty = true
return cbimap
| apache-2.0 |
ReclaimYourPrivacy/cloak-luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-pbx.lua | 68 | 1923 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
pbx_ael = module:option(ListValue, "pbx_ael", "Asterisk Extension Language Compiler", "")
pbx_ael:value("yes", "Load")
pbx_ael:value("no", "Do Not Load")
pbx_ael:value("auto", "Load as Required")
pbx_ael.rmempty = true
pbx_config = module:option(ListValue, "pbx_config", "Text Extension Configuration", "")
pbx_config:value("yes", "Load")
pbx_config:value("no", "Do Not Load")
pbx_config:value("auto", "Load as Required")
pbx_config.rmempty = true
pbx_functions = module:option(ListValue, "pbx_functions", "load => .so ; Builtin dialplan functions", "")
pbx_functions:value("yes", "Load")
pbx_functions:value("no", "Do Not Load")
pbx_functions:value("auto", "Load as Required")
pbx_functions.rmempty = true
pbx_loopback = module:option(ListValue, "pbx_loopback", "Loopback Switch", "")
pbx_loopback:value("yes", "Load")
pbx_loopback:value("no", "Do Not Load")
pbx_loopback:value("auto", "Load as Required")
pbx_loopback.rmempty = true
pbx_realtime = module:option(ListValue, "pbx_realtime", "Realtime Switch", "")
pbx_realtime:value("yes", "Load")
pbx_realtime:value("no", "Do Not Load")
pbx_realtime:value("auto", "Load as Required")
pbx_realtime.rmempty = true
pbx_spool = module:option(ListValue, "pbx_spool", "Outgoing Spool Support", "")
pbx_spool:value("yes", "Load")
pbx_spool:value("no", "Do Not Load")
pbx_spool:value("auto", "Load as Required")
pbx_spool.rmempty = true
pbx_wilcalu = module:option(ListValue, "pbx_wilcalu", "Wil Cal U (Auto Dialer)", "")
pbx_wilcalu:value("yes", "Load")
pbx_wilcalu:value("no", "Do Not Load")
pbx_wilcalu:value("auto", "Load as Required")
pbx_wilcalu.rmempty = true
return cbimap
| apache-2.0 |
PAC3-Server/ServerContent | lua/notagain/creatures/autorun/seagull.lua | 2 | 10134 | local ENT = {}
ENT.Type = "anim"
ENT.ClassName = "creature_seagull"
ENT.Base = "creature_base"
ENT.PrintName = "seagull"
ENT.Model = "models/seagull.mdl"
ENT.DefaultSize = 50
ENT.AlternateNetworking = true
function ENT:OnSizeChanged(size)
if CLIENT then
self.model:SetColor(Color(255, 255, Lerp(size/20, 100, 255), 255))
local m = Matrix()
m:Translate(Vector(0,0,-size))
m:Scale(Vector(1,1,1) * size / self.model:GetModelRadius() * 4)
self.model:SetLOD(8)
self.model:EnableMatrix("RenderMultiply", m)
end
end
if CLIENT then
ENT.Cycle = 0
ENT.Noise = 0
local ambient_sounds = {
"ambient/creatures/seagull_idle1.wav",
"ambient/creatures/seagull_idle2.wav",
"ambient/creatures/seagull_idle3.wav",
}
local footstep_sounds = {}
for i = 1, 5 do
footstep_sounds[i] = "seagull_step_" .. i .. "_" .. util.CRC(os.clock())
sound.Generate(footstep_sounds[i], 22050, 0.25, function(t)
local f = (t/22050) * (1/0.25)
f = -f + 1
f = f ^ 10
return ((math.random()*2-1) * math.sin(t*1005) * math.cos(t*0.18)) * f
end)
end
function ENT:OnUpdate(dt)
local scale = self:GetSize()
local vel = self.Velocity / scale
local len = vel:Length()
if not self:InAir() then
self.takeoff = false
local mult = 1
if len < 1 then
self:SetAnim("Idle01")
len = 15 * (self.Noise * 0.25)
else
if CLIENT then
self:StepSoundThink()
end
if len > 4 then
self:SetAnim("Run")
else
self:SetAnim("Walk")
end
mult = math.Clamp(self:GetForward():Dot(vel), -1, 1) * 0.25
end
self.Noise = (self.Noise + (math.Rand(-1,1) - self.Noise) * dt)
self.Cycle = (self.Cycle + len * dt * mult) % 1
self.model:SetCycle(self.Cycle)
else
local len2d = vel:Length2D()
if len2d < 10 and vel.z < 0 then
self:SetAnim("Land")
self.Cycle = Lerp(RealTime()%1, 0.3, 0.69)
elseif vel.z < 0 then
self:SetAnim("Soar")
self.Cycle = RealTime()
else
self:SetAnim("Fly")
if vel.z > 0 then
self.Cycle = self.Cycle + FrameTime() * 2
else
self.Cycle = Lerp(math.Clamp((-vel.z/100), 0, 1), 0.1, 1)
end
end
self.Cycle = self.Cycle%1
self.model:SetCycle(self.Cycle)
end
if math.random() > 0.999 then
sound.Play(ambient_sounds[math.random(1, #ambient_sounds)], self:GetPos(), 75, math.Clamp((1000 / self:GetSize()) + math.Rand(-10, 10), 1, 255), 1)
end
end
function ENT:StepSoundThink()
local siz = self:GetSize()
local stepped = self.Cycle%0.5
if stepped < 0.3 then
if not self.stepped then
--[[sound.Play(
table.Random(sounds),
self:GetPos(),
math.Clamp(10 * siz, 70, 160),
math.Clamp(100 / (siz/3) + math.Rand(-20,20), 40, 255)
)]]
EmitSound(
table.Random(footstep_sounds),
self:GetPos(),
self:EntIndex(),
CHAN_AUTO,
1,
--math.Clamp(10 * siz, 70, 160),
55,
0,
--math.Clamp(100 / (siz/3) + math.Rand(-20,20), 40, 255)
math.Clamp(700/siz + math.Rand(-15, 15), 10, 255)
)
self.stepped = true
end
else
self.stepped = false
end
end
end
if SERVER then
local temp_vec = Vector()
local function VectorTemp(x,y,z)
temp_vec.x = x
temp_vec.y = y
temp_vec.z = z
return temp_vec
end
local flock_radius = 2000
local flock_pos
local food = {}
local tallest_points = {}
local all_seagulls = ents.FindByClass(ENT.ClassName)
local function global_update()
all_seagulls = ents.FindByClass(ENT.ClassName)
local found = all_seagulls
local count = #found
local pos = VectorTemp(0,0,0)
for _, ent in ipairs(found) do
local p = ent.Position or ent:GetPos()
pos = pos + p
end
if count > 1 then
pos = pos / count
flock_vel = (flock_pos or pos) - pos
flock_pos = pos
if creatures.DEBUG then
debugoverlay.Sphere(pos, flock_radius, 1, Color(0, 255, 0, 5))
if me:KeyDown(IN_JUMP) then
tallest_points = {}
end
end
local up = physenv.GetGravity():GetNormalized()
local top = util.QuickTrace(pos + Vector(0,0,flock_radius/2), up*-10000).HitPos
top.z = math.min(pos.z + flock_radius, top.z)
local bottom = util.QuickTrace(top, up*10000).HitPos
if creatures.DEBUG then
debugoverlay.Text(top, "TOP", 1)
debugoverlay.Text(bottom, "BOTTOM", 1)
debugoverlay.Text(LerpVector(0.5, top, bottom), "POINTS: " .. #tallest_points, 1)
end
top.z = math.min(flock_pos.z + flock_radius, top.z)
local max = 30
if not tallest_points[max] then
for i = 1, max do
if tallest_points[max] then
break
end
local start_pos = LerpVector(i/max, bottom, top)
if DBEUG then
debugoverlay.Cross(start_pos, 100, 1)
end
--if not util.IsInWorld(start_pos) then break end
local tr = util.TraceLine({
start = start_pos,
endpos = start_pos + VectorTemp(math.Rand(-1, 1), math.Rand(-1, 1), math.Rand(-1, -0.2))*flock_radius,
})
if tr.Hit and math.abs(tr.HitNormal.z) > 0.8 and (not tr.Entity:IsValid() or tr.Entity.ClassName ~= ENT.ClassName) then
if tr.HitPos.z > flock_pos.z then
for _,v in ipairs(tallest_points) do
if v:Distance(tr.HitPos) < 50 then
return
end
end
table.insert(tallest_points, tr.HitPos)
end
end
if creatures.DEBUG then
debugoverlay.Line(tr.StartPos, tr.HitPos, 1, tr.Hit and Color(0,255,0, 255) or Color(255,0,0, 255))
end
end
if creatures.DEBUG then
for _,v in ipairs(tallest_points) do
debugoverlay.Cross(v, 5, 1, Color(0,0,255, 255))
end
end
table.sort(tallest_points, function(a, b) return a.z > b.z end)
for i = #tallest_points, 1, -1 do
local v = tallest_points[i]
if v:Distance(flock_pos) > flock_radius then
table.remove(tallest_points, i)
end
end
end
else
flock_pos = nil
end
end
local function entity_create(ent)
timer.Simple(0.25, function()
if not ent:IsValid() then return end
local phys = ent:GetPhysicsObject()
if phys:IsValid() and (
phys:GetMaterial():lower():find("flesh") or
phys:GetMaterial() == "watermelon" or
phys:GetMaterial() == "antlion"
) then
ent.seagull_food = true
table.insert(food, ent)
end
end)
end
local function entity_remove(ent)
if ent.seagull_food then
for i,v in ipairs(food) do
if v == ent then
table.remove(food, i)
end
end
end
end
timer.Create(ENT.ClassName, 1, 0, function()
global_update()
end)
hook.Add("OnEntityCreated", ENT.ClassName, function(ent)
entity_create(ent)
end)
hook.Add("EntityRemoved", ENT.ClassName, function(ent)
entity_remove(ent)
end)
function ENT:OnUpdate()
if not self.standing_still then
local avoid = self:AvoidOthers()
if avoid then
local mult = self:InAir() and 0.25 or 0.25
self.Physics:AddVelocity(avoid*self:GetSize() * mult)
end
end
if flock_pos then
if not self.tallest_point_target or (self.reached_target and math.random() > 0.2 and self.tallest_point_target.z < flock_pos.z - 100) then
if tallest_points[1] then
local point = table.remove(tallest_points, 1)
self.tallest_point_target = point
self:MoveTo({
pos = point,
waiting_time = 0.25,
finish = function()
self:GetPhysicsObject():Sleep()
end
})
end
end
if math.random() > 0.9 and flock_pos:Distance(self:GetPos()) > flock_radius then
self:MoveTo({
get_pos = function()
return flock_pos
end,
check = function()
return flock_pos:Distance(self:GetPos()) > flock_radius
end,
id = "flock",
})
end
end
if math.random() > 0.9 and not self.finding_food and not IsValid(self.weld) then
local ent = food[math.random(1, #food)] or NULL
if ent:IsValid() then
self.finding_food = true
local radius = self:BoundingRadius()
self:MoveTo({
check = function()
return
ent:IsValid() and
(
not IsValid(ent.seagull_weld) or
not IsValid(ent.seagull_weld.seagull) or
(ent.seagull_weld.seagull ~= self and ent.seagull_weld.seagull:GetSize() < self:GetSize())
)
end,
get_pos = function()
return ent:GetPos()
end,
priority = 1,
id = "food",
fail = function()
self.finding_food = nil
end,
finish = function()
self.finding_food = nil
local s = self:GetSize()
ent:SetPos(self:GetPos() + self:GetForward() * (s + 2) + self:GetUp() * s)
ent:GetPhysicsObject():EnableMotion(true)
local weld = constraint.Weld(self, ent, 0, 0, radius*500, true, false)
if weld then
ent:SetOwner(self)
self.weld = weld
self.weld.seagull = self
self.food = ent
ent.seagull_weld = weld
end
end,
})
end
end
end
function ENT:AvoidOthers()
if self.TargetPosition then return end
local pos = self.Position
local radius = self:GetSize() * (self:InAir() and 3 or 0.6)
local average_pos = Vector()
local count = 0
for _, v in ipairs(ents.FindInSphere(pos, radius)) do
if v.ClassName == self.ClassName and v ~= self then
average_pos = average_pos + (v.Position or v:GetPos())
count = count + 1
end
end
if count > 1 then
average_pos = average_pos / count
return pos - average_pos
end
end
function ENT:MoveToPoint(pos)
if creatures.DEBUG then
debugoverlay.Line(pos, self.Position, 0.1)
end
local size = self:GetSize()
local dir = pos - self.Position
local len = dir:Length()
local len2d = dir:Length2D()
local vel = dir:GetNormalized()
vel.z = 0
vel = vel * size * 0.8
local what = math.min(dir.z + (size * 3) / len, 30)
if what > 0 then
vel.z = vel.z + what *2
end
if dir.z > -size*2 and len2d > size*2 then
vel.z = vel.z + size
end
self.DesiredAngle = nil
local m = self.Physics:GetMass()
if self:InAir() then
if len2d < size*5 then
self.DesiredAngle = vel:Angle()
end
self.Physics:SetDamping(m * (1/len) * 100 + 2,0)
else
self.Physics:SetDamping(m * 7, m * 5)
end
return vel
end
end
scripted_ents.Register(ENT, ENT.ClassName) | mit |
CarabusX/Zero-K | effects/annabelle.lua | 25 | 4477 | -- annabelle
-- annabelle_smokejet
return {
["annabelle"] = {
boom = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = [[0 i1]],
explosiongenerator = [[custom:ANNABELLE_SMOKEJET]],
pos = [[0, 30, 0]],
},
},
},
["annabelle_smokejet"] = {
intense_center1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 20,
ground = true,
water = true,
properties = {
airdrag = [[0.9995 i+0.00125]],
colormap = [[1 0.6 0 0.1 0.4 0.4 0.4 1 0.05 0.05 0.05 0.1]],
directional = true,
emitrot = 0,
emitrotspread = 0,
emitvector = [[-0.5, 1.5, 0]],
gravity = [[0, -0.3 i+0.015,0]],
numparticles = 1,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 1,
particlespeed = [[5 i-0.25]],
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[smoke]],
},
},
intense_center2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 20,
ground = true,
water = true,
properties = {
airdrag = [[0.9995 i+0.00125]],
colormap = [[1 0.6 0 0.1 0.4 0.4 0.4 1 0.05 0.05 0.05 0.1]],
directional = true,
emitrot = 0,
emitrotspread = 0,
emitvector = [[0.5, 1, 0.5]],
gravity = [[0, -0.3 i+0.015,0]],
numparticles = 1,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 1,
particlespeed = [[5 i-0.25]],
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[smoke]],
},
},
intense_center3 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 20,
ground = true,
water = true,
properties = {
airdrag = [[0.99995 i+0.000125]],
colormap = [[1 0.6 0 0.1 0.4 0.4 0.4 1 0.05 0.05 0.05 0.1]],
directional = true,
emitrot = 0,
emitrotspread = 0,
emitvector = [[0.6, 1.3, -0.4]],
gravity = [[0, -0.3 i+0.015,0]],
numparticles = 1,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 1,
particlespeed = [[5 i-0.25]],
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[smoke]],
},
},
intense_center4 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 20,
ground = true,
water = true,
properties = {
airdrag = [[0.9995 i+0.00125]],
colormap = [[1 0.6 0 0.1 0.4 0.4 0.4 1 0.05 0.05 0.05 0.1]],
directional = true,
emitrot = 0,
emitrotspread = 0,
emitvector = [[-0.6, 1.7, 0.0.4]],
gravity = [[0, -0.3 i+0.015,0]],
numparticles = 1,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 1,
particlespeed = [[5 i-0.25]],
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[smoke]],
},
},
},
}
| gpl-2.0 |
PeqNP/GameKit | src/shim/HTTP.lua | 1 | 1821 | --
-- Provides convenience wrapper for Cocos2d-x XMLHttpRequest.
--
-- @copyright (c) 2016 Upstart Illustration LLC. All rights reserved.
--
require "Logger"
require "HTTPResponseType"
local Promise = require("Promise")
local HTTP = Class()
function HTTP.new(self)
--
-- Query endpoint using GET as the given response type.
--
-- @param string - HTTP query string
-- @param string - HTTPResponseType. Default: String
-- @param fn - Callback made whenever status changes on network call.
-- @return Promise - Resolves when status is between 200 and 299. Rejects otherwise.
--
function self.get(query, responseType, statusCallback)
if not responseType then
resopnseType = HTTPResponseType.String
end
Log.d("HTTP:get() - GET (%s) as (%s)", query, responseType)
local promise = Promise()
local request = cc.XMLHttpRequest:new()
local function callback__complete()
-- @todo statusCallback
if request.status < 200 or request.status > 299 then
promise.reject(request.status, request.statusText)
else
promise.resolve(request.status, request.response)
end
end
request.responseType = HTTP.getMappedResponseType(responseType)
request:registerScriptHandler(callback__complete)
request:open("GET", query, true)
request:send()
return promise
end
end
function HTTP.getMappedResponseType(_type)
if _type == HTTPResponseType.Blob then
return cc.XMLHTTPREQUEST_RESPONSE_BLOB
elseif _type == HTTPResponseType.String then
return cc.XMLHTTPREQUEST_RESPONSE_STRING
end
Log.w("Response type (%s) is not mapped to a known response type!", _type)
return nil
end
return HTTP
| mit |
EvilHero90/tfstemp | data/talkactions/scripts/kills.lua | 14 | 1396 | function onSay(cid, words, param)
local player = Player(cid)
local fragTime = configManager.getNumber(configKeys.FRAG_TIME)
if fragTime <= 0 then
player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You do not have any unjustified kill.")
return false
end
local skullTime = player:getSkullTime()
if skullTime <= 0 then
player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You do not have any unjustified kill.")
return false
end
local kills = math.ceil(skullTime / fragTime)
local remainingSeconds = math.floor((skullTime % fragTime) / 1000)
local hours = math.floor(remainingSeconds / 3600)
local minutes = math.floor((remainingSeconds % 3600) / 60)
local seconds = remainingSeconds % 60
local message = "You have " .. kills .. " unjustified kill" .. (kills > 1 and "s" or "") .. ". The amount of unjustified kills will decrease after: "
if hours ~= 0 then
if hours == 1 then
message = message .. hours .. " hour, "
else
message = message .. hours .. " hours, "
end
end
if hours ~= 0 or minutes ~= 0 then
if minutes == 1 then
message = message .. minutes .. " minute and "
else
message = message .. minutes .. " minutes and "
end
end
if seconds == 1 then
message = message .. seconds .. " second."
else
message = message .. seconds .. " seconds."
end
player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, message)
return false
end
| gpl-2.0 |
mattyx14/otxserver | data/monster/raids/mawhawk.lua | 2 | 3542 | local mType = Game.createMonsterType("Mawhawk")
local monster = {}
monster.description = "Mawhawk"
monster.experience = 14000
monster.outfit = {
lookType = 595,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 45000
monster.maxHealth = 45000
monster.race = "blood"
monster.corpse = 20295
monster.speed = 270
monster.manaCost = 0
monster.changeTarget = {
interval = 5000,
chance = 8
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = true,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
{id = 20062, chance = 30000, maxCount = 2}, -- cluster of solace
{id = 20198, chance = 30000}, -- frazzle tongue
{id = 20264, chance = 30000, maxCount = 2, unique = true}, -- unrealized dream
{id = 3031, chance = 10000, maxCount = 100}, -- gold coin
{id = 3035, chance = 10000, maxCount = 25}, -- platinum coin
{id = 3280, chance = 10000}, -- fire sword
{id = 5880, chance = 10000}, -- iron ore
{id = 5895, chance = 10000}, -- fish fin
{id = 5911, chance = 10000}, -- red piece of cloth
{id = 5925, chance = 10000}, -- hardened bone
{id = 7404, chance = 10000}, -- assassin dagger
{id = 7407, chance = 10000}, -- haunted blade
{id = 7418, chance = 10000}, -- nightmare blade
{id = 16120, chance = 10000, maxCount = 3}, -- violet crystal shard
{id = 16121, chance = 10000, maxCount = 3}, -- green crystal shard
{id = 16122, chance = 10000, maxCount = 5}, -- green crystal splinter
{id = 16124, chance = 10000, maxCount = 5} -- blue crystal splinter
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, skill = 90, attack = 90},
{name ="combat", interval = 1800, chance = 10, type = COMBAT_EARTHDAMAGE, minDamage = -300, maxDamage = -685, length = 7, spread = 3, effect = CONST_ME_STONES, target = false},
{name ="combat", interval = 2000, chance = 9, type = COMBAT_EARTHDAMAGE, minDamage = -250, maxDamage = -590, radius = 6, effect = CONST_ME_BIGPLANTS, target = false}
}
monster.defenses = {
defense = 55,
armor = 55
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 100},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = -10},
{type = COMBAT_LIFEDRAIN, percent = 100},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = -10},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 0}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType.onThink = function(monster, interval)
end
mType.onAppear = function(monster, creature)
if monster:getType():isRewardBoss() then
monster:setReward(true)
end
end
mType.onDisappear = function(monster, creature)
end
mType.onMove = function(monster, creature, fromPosition, toPosition)
end
mType.onSay = function(monster, creature, type, message)
end
mType:register(monster)
| gpl-2.0 |
CarabusX/Zero-K | LuaUI/Widgets/chili/Controls/combobox.lua | 4 | 5024 | --// =============================================================================
--- ComboBox module
--- ComboBox fields.
-- Inherits from Control.
-- @see control.Control
-- @table ComboBox
-- @tparam {"item1", "item2", ...} items table of items in the ComboBox, (default {"items"})
-- @int[opt = 1] selected id of the selected item
-- @tparam {func1, func2, ...} OnSelect listener functions for selected item changes, (default {})
ComboBox = Button:Inherit{
classname = "combobox",
caption = 'combobox',
defaultWidth = 70,
defaultHeight = 20,
items = { "items" },
itemHeight = 20,
selected = 1,
OnOpen = {},
OnClose = {},
OnSelect = {},
OnSelectName = {},
selectionOffsetX = 0,
selectionOffsetY = 0,
maxDropDownHeight = 200,
minDropDownHeight = 50,
maxDropDownWidth = 500,
minDropDownWidth = 50,
topHeight = 7,
noFont = false,
preferComboUp = false
}
local ComboBoxWindow = Window:Inherit{classname = "combobox_window", resizable = false, draggable = false, }
local ComboBoxScrollPanel = ScrollPanel:Inherit{classname = "combobox_scrollpanel", horizontalScrollbar = false, }
local ComboBoxStackPanel = StackPanel:Inherit{classname = "combobox_stackpanel", autosize = true, resizeItems = false, borderThickness = 0, padding = {0, 0, 0, 0}, itemPadding = {0, 0, 0, 0}, itemMargin = {0, 0, 0, 0}, }
local ComboBoxItem = Button:Inherit{classname = "combobox_item"}
local this = ComboBox
local inherited = this.inherited
function ComboBox:New(obj)
obj = inherited.New(self, obj)
obj:Select(obj.selected or 1)
return obj
end
--- Selects an item by id
-- @int itemIdx id of the item to be selected
function ComboBox:Select(itemIdx)
if (type(itemIdx) == "number") then
local item = self.items[itemIdx]
if not item then
return
end
self.selected = itemIdx
if type(item) == "string" and not self.ignoreItemCaption then
self.caption = ""
self.caption = item
end
self:CallListeners(self.OnSelect, itemIdx, true)
self:Invalidate()
elseif (type(itemIdx) == "string") then
self:CallListeners(self.OnSelectName, itemIdx, true)
for i = 1, #self.items do
if self.items[i] == itemIdx then
self:Select(i)
end
end
end
end
function ComboBox:_CloseWindow()
self.labels = nil
if self._dropDownWindow then
self:CallListeners(self.OnClose)
self._dropDownWindow:Dispose()
self._dropDownWindow = nil
end
if (self.state.pressed) then
self.state.pressed = false
self:Invalidate()
return self
end
end
function ComboBox:FocusUpdate()
if not self.state.focused then
if self.labels then
for i = 1, #self.labels do
if self.labels[i].state.pressed then
return
end
end
end
self:_CloseWindow()
end
end
function ComboBox:MouseDown(x, y)
self.state.pressed = true
if not self._dropDownWindow then
local sx, sy = self:LocalToScreen(0, 0)
local selectByName = self.selectByName
local labels = {}
local width = math.max(self.width, self.minDropDownWidth)
local height = self.topHeight
for i = 1, #self.items do
local item = self.items[i]
if type(item) == "string" then
local newBtn = ComboBoxItem:New {
caption = item,
width = '100%',
height = self.itemHeight,
fontsize = self.itemFontSize,
objectOverrideFont = self.objectOverrideFont,
state = {focused = (i == self.selected), selected = (i == self.selected)},
OnMouseUp = {
function()
if selectByName then
self:Select(item)
else
self:Select(i)
end
self:_CloseWindow()
end
}
}
labels[#labels + 1] = newBtn
height = height + self.itemHeight
width = math.max(width, self.font:GetTextWidth(item))
else
labels[#labels + 1] = item
item.OnMouseUp = { function()
self:Select(i)
self:_CloseWindow()
end }
width = math.max(width, item.width + 5)
height = height + item.height -- FIXME: what if this height is relative?
end
end
self.labels = labels
height = math.max(self.minDropDownHeight, height)
height = math.min(self.maxDropDownHeight, height)
width = math.min(self.maxDropDownWidth, width)
local screen = self:FindParent("screen")
local y = sy + self.height
if self.preferComboUp or y + height > screen.height then
y = sy - height
end
self._dropDownWindow = ComboBoxWindow:New{
parent = screen,
width = width,
height = height,
minHeight = self.minDropDownHeight,
x = math.max(sx, math.min(sx + self.width - width, (sx + x - width/2))) + self.selectionOffsetX,
y = y + self.selectionOffsetY,
children = {
ComboBoxScrollPanel:New{
width = "100%",
height = "100%",
children = {
ComboBoxStackPanel:New{
width = '100%',
children = labels,
},
},
}
}
}
self:CallListeners(self.OnOpen)
else
self:_CloseWindow()
end
self:Invalidate()
return self
end
function ComboBox:MouseUp(...)
self:Invalidate()
return self
-- this exists to override Button:MouseUp so it doesn't modify .state.pressed
end
| gpl-2.0 |
abgoyal/nodemcu-firmware | lua_examples/adc_rgb.lua | 73 | 1163 | --
-- Light sensor on ADC(0), RGB LED connected to gpio12(6) Green, gpio13(7) Blue & gpio15(8) Red.
-- This works out of the box on the typical ESP8266 evaluation boards with Battery Holder
--
-- It uses the input from the sensor to drive a "rainbow" effect on the RGB LED
-- Includes a very "pseudoSin" function
--
function led(r,Sg,b)
pwm.setduty(8,r)
pwm.setduty(6,g)
pwm.setduty(7,b)
end
-- this is perhaps the lightest weight sin function in existance
-- Given an integer from 0..128, 0..512 appximating 256 + 256 * sin(idx*Pi/256)
-- This is first order square approximation of sin, it's accurate around 0 and any multiple of 128 (Pi/2),
-- 92% accurate at 64 (Pi/4).
function pseudoSin (idx)
idx = idx % 128
lookUp = 32 - idx % 64
val = 256 - (lookUp * lookUp) / 4
if (idx > 64) then
val = - val;
end
return 256+val
end
pwm.setup(6,500,512)
pwm.setup(7,500,512)
pwm.setup(8,500,512)
pwm.start(6)
pwm.start(7)
pwm.start(8)
tmr.alarm(1,20,1,function()
idx = 3 * adc.read(0) / 2
r = pseudoSin(idx)
g = pseudoSin(idx + 43)
b = pseudoSin(idx + 85)
led(r,g,b)
idx = (idx + 1) % 128
end)
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.