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
MOSAVI17/Security1
plugins/google.lua
722
1037
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 }
gpl-2.0
murdemon/domoticz_codesys
scripts/lua/dzVents/Device.lua
1
7302
local TimedCommand = require('TimedCommand') local function Device(domoticz, name, state, wasChanged) local changedAttributes = {} -- storage for changed attributes local self = { ['name'] = name, ['changed'] = wasChanged, ['_States'] = { on = { b = true, inv='Off'}, open = { b = true, inv='Closed'}, ['group on'] = { b = true }, panic = { b = true, inv='Off'}, normal = { b = true, inv='Alarm'}, alarm = { b = true, inv='Normal'}, chime = { b = true }, video = { b = true }, audio = { b = true }, photo = { b = true }, playing = { b = true, inv='Pause'}, motion = { b = true }, off = { b = false, inv='On'}, closed = { b = false, inv='Open'}, ['group off'] = { b = false }, ['panic end'] = { b = false }, ['no motion'] = { b = false, inv='Off'}, stop = { b = false, inv='Open'}, stopped = { b = false}, paused ={ b = false, inv='Play'} } } -- some states will be 'booleanized' local function stateToBool(state) state = string.lower(state) local info = self._States[state] local b if (info) then b = self._States[state]['b'] end if (b==nil) then b = false end return b end -- extract dimming levels for dimming devices local level if (state and string.find(state, 'Set Level')) then level = string.match(state, "%d+") -- extract dimming value state = 'On' -- consider the device to be on end if (level) then self['level'] = tonumber(level) end if (state~=nil) then -- not all devices have a state like sensors if (type(state)=='string') then -- just to be sure self['state'] = state self['bState'] = stateToBool(self['state']) else self['state'] = state end end function self.toggleSwitch() local current, inv if (self.state~=nil) then current = self._States[string.lower(self.state)] if (current~=nil) then inv = current.inv if (inv~=nil) then return TimedCommand(domoticz, self.name, inv) end end end return nil end function self.setState(newState) -- generic state update method return TimedCommand(domoticz, self.name, newState) end function self.switchOn() return TimedCommand(domoticz, self.name, 'On') end function self.switchOff() return TimedCommand(domoticz, self.name, 'Off') end function self.close() return TimedCommand(domoticz, self.name, 'Closed') end function self.open() return TimedCommand(domoticz, self.name, 'Open') end function self.stop() -- blinds return TimedCommand(domoticz, self.name, 'Stop') end function self.dimTo(percentage) return TimedCommand(domoticz, self.name, 'Set Level ' .. tostring(percentage)) end function self.switchSelector(level) return TimedCommand(domoticz, self.name, 'Set Level ' .. tostring(level)) end function self.update(...) -- generic update method for non-switching devices -- each part of the update data can be passed as a separate argument e.g. -- device.update(12,34,54) will result in a command like -- ['UpdateDevice'] = '<id>|12|34|54' local command = self.id for i,v in ipairs({...}) do command = command .. '|' .. tostring(v) end domoticz.sendCommand('UpdateDevice', command) end -- update specials -- see http://www.domoticz.com/wiki/Domoticz_API/JSON_URL%27s function self.updateTemperature(temperature) self.update(0, temperature) end function self.updateHumidity(humidity, status) --[[ status can be domoticz.HUM_NORMAL domoticz.HUM_COMFORTABLE domoticz.HUM_DRY domoticz.HUM_WET ]] self.update(humidity, status) end function self.updateBarometer(pressure, forecast) --[[ forecast: domoticz.BARO_STABLE domoticz.BARO_SUNNY domoticz.BARO_CLOUDY domoticz.BARO_UNSTABLE domoticz.BARO_THUNDERSTORM domoticz.BARO_UNKNOWN domoticz.BARO_CLOUDY_RAIN ]] self.update(0, tostring(pressure) .. ';' .. tostring(forecast)) end function self.updateTempHum(temperature, humidity, status) local value = tostring(temperature) .. ';' .. tostring(humidity) .. ';' .. tostring(status) self.update(0, value) end function self.updateTempHumBaro(temperature, humidity, status, pressure, forecast) local value = tostring(temperature) .. ';' .. tostring(humidity) .. ';' .. tostring(status) .. ';' .. tostring(pressure) .. ';' .. tostring(forecast) self.update(0, value) end function self.updateRain(rate, counter) self.update(0, tostring(rate) .. ';' .. tostring(counter)) end function self.updateWind(bearing, direction, speed, gust, temperature, chill) local value = tostring(bearing) .. ';' .. tostring(direction) .. ';' .. tostring(speed) .. ';' .. tostring(gust) .. ';' .. tostring(temperature) .. ';' .. tostring(chill) self.update(0, value) end function self.updateUV(uv) local value = tostring(uv) .. ';0' self.update(0, value) end function self.updateCounter(value) self.update(value) -- no 0?? end function self.updateElectricity(power, energy) self.update(0, tostring(power) .. ';' .. tostring(energy)) end function self.updateP1(usage1, usage2, return1, return2, cons, prod) --[[ USAGE1= energy usage meter tariff 1 USAGE2= energy usage meter tariff 2 RETURN1= energy return meter tariff 1 RETURN2= energy return meter tariff 2 CONS= actual usage power (Watt) PROD= actual return power (Watt) USAGE and RETURN are counters (they should only count up). For USAGE and RETURN supply the data in total Wh with no decimal point. (So if your meter displays f.i. USAGE1= 523,66 KWh you need to send 523660) ]] local value = tostring(usage1) .. ';' .. tostring(usage2) .. ';' .. tostring(return1) .. ';' .. tostring(return2) .. ';' .. tostring(cons) .. ';' .. tostring(prod) self.update(0, value) end function self.updateAirQuality(quality) self.update(quality) end function self.updatePressure(pressure) self.update(0, pressure) end function self.updatePercentage(percentage) self.update(0, percentage) end function self.updateGas(usage) --[[ USAGE= Gas usage in liter (1000 liter = 1 m³) So if your gas meter shows f.i. 145,332 m³ you should send 145332. The USAGE is the total usage in liters from start, not f.i. the daily usage. ]] self.update(0, usage) end function self.updateLux(lux) self.update(lux) end function self.updateVoltage(voltage) self.update(0, voltage) end function self.updateText(text) self.update(0, text) end function self.updateAlertSensor(level, text) --[[ level can be domoticz.ALERTLEVEL_GREY domoticz.ALERTLEVEL_GREEN domoticz.ALERTLEVEL_YELLOW domoticz.ALERTLEVEL_ORANGE domoticz.ALERTLEVEL_RED ]] self.update(level, text) end function self.updateDistance(distance) --[[ distance in cm or inches, can be in decimals. For example 12.6 ]] self.update(0, distance) end function self.attributeChanged(attribute) -- returns true if an attribute is marked as changed return (changedAttributes[attribute] == true) end function self.setAttributeChanged(attribute) -- mark an attribute as being changed changedAttributes[attribute] = true end function self.addAttribute(attribute, value) -- add attribute to this device self[attribute] = value end return self end return Device
gpl-3.0
WACcCKER/Anti_Wacccker
plugins/google.lua
722
1037
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 }
gpl-2.0
alikineh/ali_kineh
plugins/google.lua
722
1037
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 }
gpl-2.0
Fatalerror66/ffxi-a
scripts/globals/items/cluster_of_paprika.lua
3
1172
----------------------------------------- -- ID: 5740 -- Item: Cluster of Paprika -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -3 -- Defense -1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5740); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -3); target:addMod(MOD_DEF, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -3); target:delMod(MOD_DEF, -1); end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Wajaom_Woodlands/npcs/Harvesting_Point.lua
4
1130
----------------------------------- -- Area: Wajaom Woodlands -- NPC: Harvesting Point ----------------------------------- package.loaded["scripts/zones/Wajaom_Woodlands/TextIDs"] = nil; package.loaded["scripts/globals/harvesting"] = nil; ------------------------------------- require("scripts/globals/harvesting"); require("scripts/zones/Wajaom_Woodlands/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startHarvesting(player,player:getZone(),npc,trade,0x01FB); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020); 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
wounds1/zaza.bot
tg/test.lua
210
2571
started = 0 our_id = 0 function vardump(value, depth, key) local linePrefix = "" local spaces = "" if key ~= nil then linePrefix = "["..key.."] = " end if depth == nil then depth = 0 else depth = depth + 1 for i=1, depth do spaces = spaces .. " " end end if type(value) == 'table' then mTable = getmetatable(value) if mTable == nil then print(spaces ..linePrefix.."(table) ") else print(spaces .."(metatable) ") value = mTable end for tableKey, tableValue in pairs(value) do vardump(tableValue, depth, tableKey) end elseif type(value) == 'function' or type(value) == 'thread' or type(value) == 'userdata' or value == nil then print(spaces..tostring(value)) else print(spaces..linePrefix.."("..type(value)..") "..tostring(value)) end end print ("HI, this is lua script") function ok_cb(extra, success, result) end -- Notification code {{{ function get_title (P, Q) if (Q.type == 'user') then return P.first_name .. " " .. P.last_name elseif (Q.type == 'chat') then return Q.title elseif (Q.type == 'encr_chat') then return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name else return '' end end local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png" function do_notify (user, msg) local n = notify.Notification.new(user, msg, icon) n:show () end -- }}} function on_msg_receive (msg) if started == 0 then return end if msg.out then return end do_notify (get_title (msg.from, msg.to), msg.text) if (msg.text == 'ping') then if (msg.to.id == our_id) then send_msg (msg.from.print_name, 'pong', ok_cb, false) else send_msg (msg.to.print_name, 'pong', ok_cb, false) end return end if (msg.text == 'PING') then if (msg.to.id == our_id) then fwd_msg (msg.from.print_name, msg.id, ok_cb, false) else fwd_msg (msg.to.print_name, msg.id, ok_cb, false) end return end 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 function cron() -- do something postpone (cron, false, 1.0) end function on_binlog_replay_end () started = 1 postpone (cron, false, 1.0) end
gpl-2.0
pquentin/wesnoth
data/lua/wml/items.lua
23
2857
local helper = wesnoth.require "lua/helper.lua" local wml_actions = wesnoth.wml_actions local game_events = wesnoth.game_events local scenario_items = {} local function add_overlay(x, y, cfg) wesnoth.add_tile_overlay(x, y, cfg) local items = scenario_items[x * 10000 + y] if not items then items = {} scenario_items[x * 10000 + y] = items end table.insert(items, { x = x, y = y, image = cfg.image, halo = cfg.halo, team_name = cfg.team_name, visible_in_fog = cfg.visible_in_fog, redraw = cfg.redraw }) end local function remove_overlay(x, y, name) local items = scenario_items[x * 10000 + y] if not items then return end wesnoth.remove_tile_overlay(x, y, name) if name then for i = #items,1,-1 do local item = items[i] if item.image == name or item.halo == name then table.remove(items, i) end end end if not name or #items == 0 then scenario_items[x * 10000 + y] = nil end end local old_on_save = game_events.on_save function game_events.on_save() local custom_cfg = old_on_save() for i,v in pairs(scenario_items) do for j,w in ipairs(v) do table.insert(custom_cfg, { "item", w }) end end return custom_cfg end local old_on_load = game_events.on_load function game_events.on_load(cfg) local i = 1 while i <= #cfg do local v = cfg[i] if v[1] == "item" then local v2 = v[2] add_overlay(v2.x, v2.y, v2) table.remove(cfg, i) else i = i + 1 end end old_on_load(cfg) end function wml_actions.item(cfg) local locs = wesnoth.get_locations(cfg) cfg = helper.parsed(cfg) if not cfg.image and not cfg.halo then helper.wml_error "[item] missing required image= and halo= attributes." end for i, loc in ipairs(locs) do add_overlay(loc[1], loc[2], cfg) end local redraw = cfg.redraw if redraw == nil then redraw = true end if redraw then wml_actions.redraw {} end end function wml_actions.remove_item(cfg) local locs = wesnoth.get_locations(cfg) for i, loc in ipairs(locs) do remove_overlay(loc[1], loc[2], cfg.image) end end function wml_actions.store_items(cfg) local variable = cfg.variable or "items" variable = tostring(variable or helper.wml_error("invalid variable= in [store_items]")) wesnoth.set_variable(variable) local index = 0 for i, loc in ipairs(wesnoth.get_locations(cfg)) do --ugly workaround for the lack of the "continue" statement in lua repeat local items = scenario_items[loc[1] * 10000 + loc[2]] if not items then break end for j, item in ipairs(items) do wesnoth.set_variable(string.format("%s[%u]", variable, index), item) index = index + 1 end until true end end local methods = { remove = remove_overlay } function methods.place_image(x, y, name) add_overlay(x, y, { x = x, y = y, image = name }) end function methods.place_halo(x, y, name) add_overlay(x, y, { x = x, y = y, halo = name }) end return methods
gpl-2.0
kidaa/FFXIOrgins
scripts/zones/Lower_Jeuno/npcs/Faursel.lua
38
7011
----------------------------------- -- Area: Lower Jeuno -- NPC: Faursel -- Type: Aht Urhgan Quest NPC -- Involved in Quests: The Road to Aht Urhgan -- @pos 37.985 3.118 -45.208 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/teleports"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local questStatus = player:getQuestStatus(JEUNO,THE_ROAD_TO_AHT_URHGAN); local questStatusVar = player:getVar("THE_ROAD_TO_AHT_URHGAN"); if (questStatus == QUEST_ACCEPTED and questStatusVar == 1) then if (trade:hasItemQty(537,1) == true and trade:hasItemQty(538,1) == true and trade:hasItemQty(539,1) == true and trade:hasItemQty(540,1) == true and trade:hasItemQty(541,1) == true and trade:hasItemQty(542,1) == true and trade:getItemCount() == 6 and trade:getGil() == 0) then -- Beginner List (Subjob Items) player:startEvent(0x2756); elseif (trade:hasItemQty(1532,1) and trade:hasItemQty(1533,1) and trade:hasItemQty(1535,1) and trade:getItemCount() == 3 and trade:getGil() == 0) then -- Intermediate List player:startEvent(0x2756); elseif (trade:hasItemQty(1692,1) and trade:hasItemQty(1693,1) and trade:hasItemQty(1694,1) and trade:getItemCount() == 3 and trade:getGil() == 0) then -- Advanced List (Chips) player:startEvent(0x2756); elseif (trade:hasItemQty(1042,1) or trade:hasItemQty(1043,1) or trade:hasItemQty(1044,1) or trade:hasItemQty(1049,1) or trade:hasItemQty(1050,1) or trade:hasItemQty(1054,1) or trade:hasItemQty(10459,1) and trade:getItemCount() == 1 and trade:getGil() == 0) then -- Advanced List (Coffer Keys) player:startEvent(0x2756); elseif (trade:hasItemQty(1426,1) or trade:hasItemQty(1427,1) or trade:hasItemQty(1428,1) or trade:hasItemQty(1429,1) or trade:hasItemQty(1430,1) or trade:hasItemQty(1431,1) or trade:hasItemQty(1432,1) or trade:hasItemQty(1433,1) or trade:hasItemQty(1434,1) or trade:hasItemQty(1435,1) or trade:hasItemQty(1436,1) or trade:hasItemQty(1437,1) or trade:hasItemQty(1438,1) or trade:hasItemQty(1439,1) or trade:hasItemQty(1440,1) or trade:hasItemQty(2331,1) or trade:hasItemQty(2332,1) or trade:hasItemQty(2333,1) or trade:hasItemQty(2556,1) or trade:hasItemQty(2557,1) and trade:getItemCount() == 1 and trade:getGil() == 0) then -- Advanced List (Testimonys) player:startEvent(0x2756); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local passDay = player:getVar("THE_ROAD_TO_AHT_URHGAN_Day"); local passYear = player:getVar("THE_ROAD_TO_AHT_URHGAN_Year"); local currentDay = VanadielDayOfTheYear(); local passReady = ((passDay < currentDay) or (passDay > currentDay and passYear < VanadielYear())); local questStatus = player:getQuestStatus(JEUNO,THE_ROAD_TO_AHT_URHGAN); local questStatusVar = player:getVar("THE_ROAD_TO_AHT_URHGAN"); if (questStatus == QUEST_AVAILABLE and ENABLE_TOAU == 1) then player:startEvent(0x274E); -- Offer Quest, First Dialog. elseif (questStatus == QUEST_ACCEPTED and questStatusVar == 0) then player:startEvent(0x274F); -- Offically offer quest, Second Dialog. elseif (questStatus == QUEST_ACCEPTED and questStatusVar == 1) then player:startEvent(0x2750); -- Player did not make a decision during Second Dialog. Offering the list again. elseif (questStatus == QUEST_ACCEPTED and questStatusVar == 2 and passReady ~= true) then player:startEvent(0x2752); -- Bought Bording Pass, Player must wait One Day. elseif (questStatus == QUEST_ACCEPTED and questStatusVar == 3 and passReady ~= true) then player:startEvent(0x2758); -- Quested for Bording Pass, Player must wait One Day. elseif (questStatus == QUEST_ACCEPTED and questStatusVar == 2 and passReady == true) then player:startEvent(0x2753); -- Bought Bording Pass, ready to issue. elseif (questStatus == QUEST_ACCEPTED and questStatusVar == 3 and passReady == true) then player:startEvent(0x2756); -- Quested for Bording Pass, ready to issue. elseif (questStatus == QUEST_ACCEPTED and questStatusVar == 4) then player:startEvent(0x2754); -- Bought Bording Pass, returned from the Woodlands. elseif (questStatus == QUEST_COMPLETED) then player:startEvent(0x2757); -- Regular chat dialog after the quest. else player:startEvent(0x2751); -- Regular chat dialog. end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == 0x274F or csid == 0x2750) then if (option == 10) then -- Beginner List player:updateEvent(537,538,539,540,541,542,0,0); elseif (option == 12) then -- Intermediate List player:updateEvent(1532,1533,1535,0,0,0,0,0); elseif (option == 13) then -- Advanced List player:updateEvent(1692,1693,1694,0,0,0,0,0); elseif (option == 14) then -- Gil Option player:updateEvent(1,1,1,1,1,1,player:getGil(),1); elseif (option == 2 or option == 1073741824) then -- Let me think about it... / Cancel end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x274E and option == 1) then -- Offer Quest, First Dialog. player:addQuest(JEUNO,THE_ROAD_TO_AHT_URHGAN); elseif (csid == 0x274F or csid == 0x2750) then if (csid == 0x274F and option == 1 or csid == 0x274F and option == 2) then -- Offically offer quest, Second Dialog. player:setVar("THE_ROAD_TO_AHT_URHGAN",1); elseif (option == 3) then player:delGil(500000); player:setVar("THE_ROAD_TO_AHT_URHGAN",2); player:setVar("THE_ROAD_TO_AHT_URHGAN_Day",VanadielDayOfTheYear()); player:setVar("THE_ROAD_TO_AHT_URHGAN_Year",VanadielYear()); end elseif (csid == 0x2753) then player:addKeyItem(MAP_OF_WAJAOM_WOODLANDS); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_WAJAOM_WOODLANDS); player:addKeyItem(BOARDING_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,BOARDING_PERMIT); player:setVar("THE_ROAD_TO_AHT_URHGAN",4); toWajaomLaypoint(player); elseif (csid == 0x2754) then player:completeQuest(JEUNO,THE_ROAD_TO_AHT_URHGAN); player:setVar("THE_ROAD_TO_AHT_URHGAN",0); player:setVar("THE_ROAD_TO_AHT_URHGAN_Day",0); player:setVar("THE_ROAD_TO_AHT_URHGAN_Year",0); player:addFame(JEUNO, JEUNO_FAME*30); elseif (csid == 0x2756) then player:addKeyItem(BOARDING_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,BOARDING_PERMIT); player:completeQuest(JEUNO,THE_ROAD_TO_AHT_URHGAN); player:setVar("THE_ROAD_TO_AHT_URHGAN",0); player:setVar("THE_ROAD_TO_AHT_URHGAN_Day",0); player:setVar("THE_ROAD_TO_AHT_URHGAN_Year",0); player:addFame(JEUNO, JEUNO_FAME*30); player:tradeComplete(); end end;
gpl-3.0
murdemon/domoticz_codesys
scripts/lua/dzVents/tests/testScriptDeviceMain.lua
1
1059
local _ = require 'lodash' package.path = package.path .. ";../?.lua" package.path = package.path .. ";../../?.lua" -- two folders up describe('script_time_main', function() setup(function() _G.TESTMODE = true _G.timeofday = { Daytime = 'dt', Nighttime = 'nt', SunriseInMinutes = 'sunrisemin', SunsetInMinutes = 'sunsetmin' } _G.globalvariables = { Security = 'sec' } _G.devicechanged = { ['onscript1'] = 'On', } _G.otherdevices = { ['onscript1'] = 'On', ['device1'] = 'On' } _G.otherdevices_lastupdate = { ['onscript1'] = '2016-03-20 12:23:00', } _G.otherdevices_idx = { ['onscript1'] = 1, } _G.otherdevices_svalues = { ['onscript1'] = '1;2;3', } _G.uservariables = {} _G['uservariables_lastupdate'] = {} end) teardown(function() end) it("should do it's thing", function() _G.commandArray = {} local main = require('script_device_main') assert.is_same({ {["onscript1"]="Off"}, {["onscript1"]="Set Level 10"}, {["UpdateDevice"]="1|123"}}, main) end) end)
gpl-3.0
emadni/emadoso
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
capr/fbclient-alien
lua/fbclient/service_class.lua
2
18634
--[=[ Service Manager API, objectual interface based on service.lua connect([hostname],[username],[password],[timeout_sec],[libname|fbapi],[svc_class]) -> svo connect_ex([hostname],[spb_options_t],[libname|fbapi],[svc_class) -> svo service_class -> the LOOP class that svo objects inherit. svo.sv -> the status_vector object with which all calls are made. svo.fbapi -> the binding object onto which all calls are made. svo.timeout -> the timeout value against which all queries are made. you can change it between queries. svo:close() svo:lines() -> line_iterator -> line_num,line svo:chunks() -> chunk_iterator -> chunk_num,chunk svo:service_manager_version() -> n; currently 2 svo:busy() -> boolean svo:server_version() -> s svo:server_implementation_string() -> s svo:server_capabilities() -> caps_t (pair() it out to see) svo:server_install_path() -> s svo:server_lock_path() -> s svo:server_msg_path() -> s svo:server_log() -> svo; use lines() or chunks() to get the output svo:attachment_num() -> n svo:db_num() -> n svo:db_names() -> name_t svo:db_stats(dbname,[options_t]) -> svo; use lines() or chunks() to get the output svo:db_backup(dbname,backup_file|backup_file_t,[options_t]) -> svo svo:db_restore(backup_file|backup_file_list,db_file,[options_t]) -> svo svo:db_repair(dbname,[options_t]) svo:db_sweep(dbname) svo:db_mend(dbname) svo:db_nbackup(dbname,backup_file,[nbackup_level=0],[options_t]) --firebird 2.5+ svo:db_nrestore(backup_file|backup_file_list,db_file,[options_t]) --firebird 2.5+ svo:db_set_page_buffers(dbname,page_buffer_num) svo:db_set_sweep_interval(dbname,sweep_interval) svo:db_set_forced_writes(dbname,true|false) svo:db_set_space_reservation(dbname,true|false) svo:db_set_read_only(dbname,true|false) svo:db_set_dialect(dbname,dialect) svo:db_shutdown(dbname,timeout_sec,[force_mode],[shutdown_mode]) svo:db_activate(dbname,[online_mode]) svo:db_use_shadow(dbname) --user management API (user_db_file option is fb 2.5+) svo:user_db_file() -> s svo:user_list([user_db_file]) -> t[username] -> user_t svo:user_list(username,[user_db_file]) -> user_t svo:user_add(username,password,first_name,middle_name,last_name,[user_db_file]) svo:user_update(username,password,first_name,middle_name,last_name,[user_db_file]) svo:user_delete(username,[user_db_file]) --trace API: firebird 2.5+ svo:trace_start(trace_config_string,[trace_name]) -> svo; use lines() or chunks() to get the output svo:trace_list() -> trace_list_t svo:trace_suspend(trace_id) svo:trace_resume(trace_id) svo:trace_stop(trace_id) --enable/disable the RDB$ADMIN role for the appointed OS user for a service request to access security2.fdb. --firebird 2.5+ svo:rdbadmin_set_mapping() svo:rdbadmin_drop_maping() USAGE/NOTES: - the functions db_backup() and db_restore() with verbose option on, as well as db_stats(), server_log(), trace_start(), do not return any output directly. instead you must use the lines() or chunks() iterators to get their output either line by line or chunk by chunk. ]=] module(...,require 'fbclient.module') local binding = require 'fbclient.binding' local svapi = require 'fbclient.status_vector' local api = require 'fbclient.service_wrapper' local oo = require 'loop.base' service_class = oo.class() function connect(hostname, user, pass, timeout, fbapi, svc_class) local spb_opts = { isc_spb_user_name = user, isc_spb_password = pass, } return connect_ex(hostname, spb_opts, timeout, fbapi, svc_class) end function connect_ex(hostname, spb_opts, timeout, fbapi, svc_class) svc_class = svc_class or service_class fbapi = xtype(fbapi) == 'alien library' and fbapi or binding.new(fbapi or 'fbclient') local service_name = (hostname and hostname..':' or '')..'service_mgr' local sv = svapi.new() local svo = svc_class { fbapi = fbapi, sv = sv, timeout = timeout, } svo.handler = api.attach(fbapi, sv, service_name, spb_opts) return svo end function service_class:close() return api.detach(self.fbapi,self.sv,self.handler) end local function line_iterator(state,var) local info info,state.buf,state.buf_size = api.query(state.self.fbapi,state.self.sv,state.self.handler,{isc_info_svc_line=true},{isc_info_svc_timeout=state.self.timeout},state.buf,state.buf_size) if info.isc_info_svc_line == '' then return nil else return var+1,info.isc_info_svc_line end end function service_class:lines() return line_iterator,{self=self},0 end local function chunk_iterator(state,var) local info info,state.buf,state.buf_size = api.query(state.self.fbapi,state.self.sv,state.self.handler,{isc_info_svc_to_eof=true},{isc_info_svc_timeout=state.self.timeout},state.buf,state.buf_size) if info.isc_info_svc_to_eof == '' then return nil else return var+1,info.isc_info_svc_to_eof end end function service_class:chunks() return chunk_iterator,{self=self},0 end --about the service manager function service_class:service_manager_version() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_version=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_version end function service_class:busy() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_running=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_running end --about the server function service_class:server_version() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_server_version=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_server_version end function service_class:server_implementation_string() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_implementation=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_implementation end function service_class:server_capabilities() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_capabilities=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_capabilities end function service_class:server_install_path() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_get_env=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_get_env end function service_class:server_lock_path() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_get_env_lock=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_get_env_lock end function service_class:server_msg_path() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_get_env_msg=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_get_env_msg end function service_class:server_log() api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_get_fb_log') return self end --about databases function service_class:attachment_num() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_svr_db_info=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_svr_db_info.isc_spb_num_att[1] end function service_class:db_num() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_svr_db_info=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_svr_db_info.isc_spb_num_db[1] end function service_class:db_names() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_svr_db_info=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_svr_db_info.isc_spb_dbname --this is an array end function service_class:db_stats(db_name,opts) opts = opts or {} api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_db_stats', { isc_spb_dbname = db_name, isc_spb_options = { isc_spb_sts_hdr_pages = opts.header_page_only, --this option is exclusive, unlike others isc_spb_sts_data_pages = opts.data_pages, isc_spb_sts_idx_pages = opts.index_pages, isc_spb_sts_record_versions = opts.record_versions, isc_spb_sts_sys_relations = opts.include_system_tables, }, }) return self end --operations on a database function service_class:db_backup(db_name,backup_file,opts) opts = opts or {} api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_backup', { isc_spb_dbname = db_name, isc_spb_bkp_file = backup_file, isc_spb_verbose = opts.verbose, isc_spb_options = { isc_spb_bkp_ignore_checksums = opts.ignore_checksums, isc_spb_bkp_ignore_limbo = opts.ignore_limbo, isc_spb_bkp_metadata_only = opts.metadata_only, isc_spb_bkp_no_garbage_collect = opts.no_garbage_collect, isc_spb_bkp_old_descriptions = opts.old_descriptions, --don't use this option isc_spb_bkp_non_transportable = opts.non_transportable, --don't use this option isc_spb_bkp_convert = opts.include_external_tables, }, }) return self end function service_class:db_restore(backup_file,db_file,opts) opts = opts or {} api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_restore', { isc_spb_bkp_file = backup_file, isc_spb_dbname = db_file, isc_spb_verbose = opts.verbose, isc_spb_res_buffers = opts.page_buffers, isc_spb_res_page_size = opts.page_size, isc_spb_res_access_mode = opts.read_only and 'isc_spb_prp_am_readonly' or opts.read_only == false and 'isc_spb_prp_am_readwrite' or nil, isc_spb_options = { isc_spb_res_deactivate_idx = opts.dont_build_indexes, isc_spb_res_no_shadow = opts.dont_recreate_shadow_files, isc_spb_res_no_validity = opts.dont_validate, isc_spb_res_one_at_a_time = opts.commit_each_table, isc_spb_res_replace = opts.force, isc_spb_res_create = not opts.force or nil, isc_spb_res_use_all_space = opts.no_space_reservation, }, }) return self end function service_class:db_nbackup(db_name,backup_file,nbackup_level,opts) --firebird 2.5+ nbackup_level = nbackup_level or 0 opts = opts or {} api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_nbak',{ isc_spb_dbname = db_name, isc_spb_nbk_file = backup_file, isc_spb_nbk_level = nbackup_level, isc_spb_options = { isc_spb_nbk_no_triggers = opts.no_triggers, }, }) end function service_class:db_nrestore(backup_file_list,db_file,opts) --firebird 2.5+ if type(backup_file_list) == 'string' then backup_file_list = {backup_file_list} end opts = opts or {} api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_nrest', { isc_spb_nbk_file = backup_file_list, isc_spb_dbname = db_file, isc_spb_options = { isc_spb_nbk_no_triggers = opts.no_triggers, }, }) end function service_class:db_repair(db_name,opts) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_repair', { isc_spb_dbname = db_name, isc_spb_options = { isc_spb_rpr_validate_db = true, isc_spb_rpr_check_db = opts.dont_fix, isc_spb_rpr_ignore_checksum = opts.ignore_checksums, isc_spb_rpr_kill_shadows = opts.kill_shadows, isc_spb_rpr_full = opts.full, }, }) end function service_class:db_sweep(db_name) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_repair', { isc_spb_dbname = db_name, isc_spb_options = {isc_spb_rpr_sweep_db = true}, }) end function service_class:db_mend(db_name,opts) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_repair', { isc_spb_dbname = db_name, isc_spb_options = {isc_spb_rpr_mend_db = true}, }) end function service_class:db_set_page_buffers(db_name,page_buffers) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_page_buffers = page_buffers, }) end function service_class:db_set_sweep_interval(db_name,sweep_interval) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_sweep_interval = sweep_interval, }) end function service_class:db_set_forced_writes(db_name,enable_forced_writes) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_write_mode = enable_forced_writes and 'isc_spb_prp_wm_sync' or 'isc_spb_prp_wm_async', }) end function service_class:db_set_space_reservation(db_name,enable_reservation) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_reserve_space = enable_reservation and 'isc_spb_prp_res' or 'isc_spb_prp_res_use_full', }) end function service_class:db_set_read_only(db_name,enable_read_only) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_access_mode = enable_read_only and 'isc_spb_prp_am_readonly' or 'isc_spb_prp_am_readwrite', }) end function service_class:db_set_dialect(db_name,dialect) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_set_sql_dialect = dialect, }) end local shutdown_modes = { normal = 'isc_spb_prp_sm_normal', multi = 'isc_spb_prp_sm_multi', single = 'isc_spb_prp_sm_single', full = 'isc_spb_prp_sm_full', } --force_mode = full|transactions|connections; shutdown_mode = normal|multi|single|full function service_class:db_shutdown(db_name,timeout,force_mode,shutdown_mode) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_shutdown_db = (force_mode or 'full') == 'full' and timeout or nil, --force isc_spb_prp_deny_new_attachments = force_mode == 'transactions' and timeout or nil, --let transactions finish isc_spb_prp_deny_new_transactions = force_mode == 'connections' and timeout or nil, --let attachments finish isc_spb_prp_shutdown_mode = asserts(shutdown_modes[shutdown_mode or 'multi'], 'invalid shutdown mode %s', shutdown_mode), }) end function service_class:db_activate(db_name,online_mode) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_prp_online_mode = asserts(shutdown_modes[online_mode or 'normal'], 'invalid online mode %s', online_mode), isc_spb_options = { isc_spb_prp_db_online = true, }, }) end function service_class:db_use_shadow(db_name) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_properties', { isc_spb_dbname = db_name, isc_spb_options = {isc_spb_prp_activate = true}, }) end --operations on the security database function service_class:user_db_file() local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_user_dbpath=true},{isc_info_svc_timeout=self.timeout}) return info.isc_info_svc_user_dbpath end function service_class:user_list(username,user_db_file) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_display_user',{ isc_spb_sec_username = username, isc_spb_dbname = user_db_file, }) local info = api.query(self.fbapi,self.sv,self.handler,{isc_info_svc_get_users=true},{isc_info_svc_timeout=self.timeout}) if username then local a = info.isc_info_svc_get_users assert(#a == 1,'user not found') return { first_name=a.isc_spb_sec_firstname[1], middle_name=a.isc_spb_sec_middlename[1], last_name=a.isc_spb_sec_lastname[1] } else local t = {} for i,username in ipairs(info.isc_info_svc_get_users.isc_spb_sec_username) do t[username] = { first_name=info.isc_info_svc_get_users.isc_spb_sec_firstname[i], middle_name=info.isc_info_svc_get_users.isc_spb_sec_middlename[i], last_name=info.isc_info_svc_get_users.isc_spb_sec_lastname[i], } end return t end end function service_class:user_add(username,password,first_name,middle_name,last_name,user_db_file) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_add_user',{ isc_spb_sec_username = username, isc_spb_sec_password = password, isc_spb_sec_firstname = first_name, isc_spb_sec_middlename = middle_name, isc_spb_sec_lastname = last_name, isc_spb_dbname = user_db_file, }) end function service_class:user_update(username,password,first_name,middle_name,last_name,user_db_file) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_modify_user',{ isc_spb_sec_username = username, isc_spb_sec_password = password, isc_spb_sec_firstname = first_name, isc_spb_sec_middlename = middle_name, isc_spb_sec_lastname = last_name, isc_spb_dbname = user_db_file, }) end function service_class:user_delete(username,user_db_file) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_delete_user',{ isc_spb_sec_username = username, isc_spb_dbname = user_db_file, }) end --tracing API (firebird 2.5+) local function check_trace_action_result(s) assert(not s:find('not found') and not s:find('No permission'),s) end function service_class:trace_list() api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_trace_list') local function decode_timestamp(y,m,d,h,m,s) return {year=y,month=m,day=d,hour=h,min=m,sec=s} end local function decode_flags(s) local t = {} s:gsub('([^,]*)', function(c) t[trim(c)]=true; end) return t end local t,s = {} local function tryadd(patt,field,decoder) local from,to,c1,c2,c3,c4,c5,c6 = s:find(patt) if from then t[field] = decoder(c1,c2,c3,c4,c5,c6) end end for i,s in self:lines() do tryadd('^Session ID: (%d+)','id',tonumber) tryadd('^ name: (%.+)','name',tostring) tryadd('^ user: (%.+)','user',tostring) tryadd('^ date: (%d%d%d%d)-(%d%d)-(%d%d) (%d%d):(%d%d):(%d%d)','date',decode_timestamp) tryadd('^ flags: (%.+)','flags',decode_flags) end return t end function service_class:trace_start(trace_config_string,trace_name) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_trace_start',{ isc_spb_trc_name = trace_name, isc_spb_trc_cfg = trace_config_string, }) return self end function service_class:trace_suspend(trace_id) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_trace_suspend',{isc_spb_trc_id=trace_id}) for i,line in self:lines() do return check_trace_action_result(line) end end function service_class:trace_resume(trace_id) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_trace_resume',{isc_spb_trc_id=trace_id}) for i,line in self:lines() do return check_trace_action_result(line) end end function service_class:trace_stop(trace_id) api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_trace_stop',{isc_spb_trc_id=trace_id}) for i,line in self:lines() do return check_trace_action_result(line) end end --RDB$ADMIN mapping (firebird 2.5+) function service_class:rdbadmin_set_mapping() api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_set_mapping') end function service_class:rdbadmin_drop_mapping() api.start(self.fbapi,self.sv,self.handler,'isc_action_svc_drop_mapping') end
mit
gunzino/forgottenserver
data/talkactions/scripts/buyhouse.lua
20
1149
function onSay(player, words, param) local housePrice = configManager.getNumber(configKeys.HOUSE_PRICE) if housePrice == -1 then return true end if player:getPremiumDays() <= 0 then player:sendCancelMessage("You need a premium account.") return false end local position = player:getPosition() position:getNextPosition(player:getDirection()) local house = House(getTileHouseInfo(position)) if house == nil then player:sendCancelMessage("You have to be looking at the door of the house you would like to buy.") return false end if house:getOwnerGuid() > 0 then player:sendCancelMessage("This house already has an owner.") return false end if player:getHouse() then player:sendCancelMessage("You are already the owner of a house.") return false end local price = house:getTileCount() * housePrice if not player:removeMoney(price) then player:sendCancelMessage("You do not have enough money.") return false end house:setOwnerGuid(player:getGuid()) player:sendTextMessage(MESSAGE_INFO_DESCR, "You have successfully bought this house, be sure to have the money for the rent in the bank.") return false end
gpl-2.0
Segs/Segs
Data/scripts/City_01_02/TimeCop.lua
3
1824
--TimeCop controls auto-refreshing of map spawners (spawndef-based) local TimeCop = {}; TimeCop.spawned = false; TimeCop.name = "Time Cop"; TimeCop.model = "MaleNpc_230"; TimeCop.location = {}; TimeCop.location.coordinates = vec3.new(-790, 32, 1450.5); TimeCop.location.orientation = vec3.new(0, 3.14, 0); TimeCop.variation = 1; TimeCop.entityId = nil; TimeCop.minLevel = 0; TimeCop.hideTime = 0; TimeCop.isStore = false; TimeCop.NumEncounters = 50; --number of encounters to respawn TimeCop.RefreshRate = 60; --number of seconds before respawns TimeCop.onTickCallBack = function(startTime, diff, current) --print("startTime: " .. tostring(startTime) .. " diff: " .. tostring(diff) .. " current: " .. tostring(current)); local stopTime = TimeCop.RefreshRate; if(diff == stopTime) then MapInstance.StopTimer(contactsForZone.TimeCop.entityId); DespawnMapEncounters() RandomSpawn(TimeCop.NumEncounters) MapInstance.StartTimer(contactsForZone.TimeCop.entityId); end end --Default with no arg turns Time Cop off. Otherwise, pass "true" to activate function TimeCopMode(Refresh, EncounterCount, Rate) EncounterCount = EncounterCount or TimeCop.NumEncounters Rate = Rate or TimeCop.RefreshRate TimeCop.NumEncounters = EncounterCount TimeCop.RefreshRate = Rate if Refresh == nil or Refresh == false then MapInstance.StopTimer(contactsForZone.TimeCop.entityId); MapClientSession.SendInfoMessage(13, "Map encounters auto-refresh has ceased.") elseif Refresh == true then MapInstance.StartTimer(contactsForZone.TimeCop.entityId); MapClientSession.SendInfoMessage(13, "Map encounters will auto-refresh.") end end -- Must be at end if(contactsForZone ~= nil) then contactsForZone.TimeCop = TimeCop; end
bsd-3-clause
Puccio7/bot-telegram
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
apache-2.0
emoses/hammerspoon
extensions/expose/init.lua
5
26724
--- === hs.expose === --- --- **WARNING**: This module depends on the EXPERIMENTAL hs.window.filter. It can undergo breaking API changes or *go away entirely* **at any point and without notice**. --- (Should you encounter any issues, please feel free to report them on https://github.com/Hammerspoon/hammerspoon/issues --- or #hammerspoon on irc.freenode.net) --- --- Keyboard-driven expose replacement/enhancement --- --- Usage: --- -- set up your windowfilter --- expose = hs.expose.new() -- default windowfilter: only visible windows, all Spaces --- expose2 = hs.expose.new(hs.window.filter.new():trackSpaces(true):setDefaultFilter()) -- include minimized/hidden windows, current Space only --- expose_browsers = hs.expose.new{'Safari','Google Chrome'} -- specialized expose for your dozens of browser windows :) --- --- -- then bind to a hotkey --- hs.hotkey.bind('ctrl-cmd','e','expose',function()expose:toggleShow()end) --- --- -- alternatively, call .expose directly --- hs.hotkey.bind('ctrl-alt','e','expose',expose.expose) --- hs.hotkey.bind('ctrl-alt-shift','e','expose app',expose.exposeApplicationWindows) --TODO /// hs.drawing:setClickCallback(fn) -> drawingObject --TODO showExtraKeys local expose={} --module local drawing,image=require'hs.drawing',require'hs.image' local window,screen=require'hs.window',require'hs.screen' local windowfilter=require'hs.window.filter' local application,spaces=require'hs.application',require'hs.spaces' local eventtap=require'hs.eventtap' local execute,fnutils=hs.execute,require'hs.fnutils' local log=require'hs.logger'.new('expose') expose.setLogLevel=log.setLogLevel local newmodal=require'hs.hotkey'.modal.new local tinsert,tremove,min,max,ceil,abs,fmod,floor=table.insert,table.remove,math.min,math.max,math.ceil,math.abs,math.fmod,math.floor local next,type,ipairs,pairs,setmetatable,sformat,supper,ssub,tostring=next,type,ipairs,pairs,setmetatable,string.format,string.upper,string.sub,tostring local rect = {} -- a centered rect class (more handy for our use case) rect.new = function(r) local o = setmetatable({},{__index=rect}) o.x=r.x+r.w/2 o.y=r.y+r.h/2 o.w=r.w o.h=r.h return o end function rect:scale(factor) self.w=self.w*factor self.h=self.h*factor end function rect:move(dx,dy) self.x=self.x+dx self.y=self.y+dy end function rect:tohs() return {x=self.x-self.w/2,y=self.y-self.h/2,w=self.w,h=self.h} end function rect:intersect(r2) local r1,x,y,w,h=self if r1.x<r2.x then x=r2.x-r2.w/2 w=r1.x+r1.w/2-x else x=r1.x-r1.w/2 w=r2.x+r2.w/2-x end if r1.y<r2.y then y=r2.y-r2.h/2 h=r1.y+r1.h/2-y else y=r1.y-r1.h/2 h=r2.y+r2.h/2-y end return rect.new({x=x,y=y,w=w,h=h}) end function rect:fit(frame) if self.w>frame.w then self:scale(frame.w/self.w) end if self.h>frame.h then self:scale(frame.h/self.h) end self.x=max(self.x,frame.x+self.w/2) self.x=min(self.x,frame.x+frame.w-self.w/2) self.y=max(self.y,frame.y+self.h/2) self.y=min(self.y,frame.y+frame.h-self.h/2) end function rect:toString() return sformat('%d,%d %dx%d',self.x,self.y,self.w,self.h) end local function isAreaEmpty(rect,windows,screenFrame) if rect.x-rect.w/2<screenFrame.x or rect.x+rect.w/2>screenFrame.w+screenFrame.x or rect.y-rect.h/2<screenFrame.y or rect.y+rect.h/2>screenFrame.h+screenFrame.y then return end for i,win in ipairs(windows) do local i = win.frame:intersect(rect) if i.w>0 and i.h>0 then return end end return true end local function fitWindows(windows,maxIterations,animate,alt_algo) local screenFrame = windows.frame local avgRatio = min(1,screenFrame.w*screenFrame.h/windows.area*2) log.vf('shrink %d windows to %.0f%%',#windows,avgRatio*100) for i,win in ipairs(windows) do win.frame:scale(avgRatio) win.frame:fit(screenFrame) end local didwork = true local iterations = 0 local screenArea=screenFrame.w*screenFrame.h local screenCenter=rect.new(screenFrame) while didwork and iterations<maxIterations do didwork=false iterations=iterations+1 local thisAnimate=animate and floor(math.sqrt(iterations)) local totalOverlaps = 0 local totalRatio=0 for i,win in ipairs(windows) do local winRatio = win.frame.w*win.frame.h/win.area totalRatio=totalRatio+winRatio -- log.vf('processing %s - %s',win.appname,win.frame:toString()) local overlapAreaTotal = 0 local overlaps={} for j,win2 in ipairs(windows) do if j~=i then --log.vf('vs %s %s',win2.appname,win2.frame:toString()) local intersection = win.frame:intersect(win2.frame) local area = intersection.w*intersection.h --log.vf('intersection %s [%d]',intersection:toString(),area) if intersection.w>1 and intersection.h>1 then --log.vf('vs %s intersection %s [%d]',win2.appname,intersection:toString(),area) overlapAreaTotal=overlapAreaTotal+area overlaps[#overlaps+1] = intersection if area*0.9>win.frame.w*win.frame.h then overlaps[#overlaps].x=(win.frame.x+win2.frame.x)/2 overlaps[#overlaps].y=(win.frame.y+win2.frame.y)/2 end end end end totalOverlaps=totalOverlaps+#overlaps -- find the overlap regions center if #overlaps>0 then didwork=true local ax,ay=0,0 for _,ov in ipairs(overlaps) do local weight = ov.w*ov.h/overlapAreaTotal ax=ax+ weight*(ov.x) ay=ay+ weight*(ov.y) end ax=(win.frame.x-ax)*overlapAreaTotal/screenArea*3 ay=(win.frame.y-ay)*overlapAreaTotal/screenArea*3 win.frame:move(ax,ay) if winRatio/avgRatio>0.8 then win.frame:scale(alt_algo and 0.95 or 0.98) end win.frame:fit(screenFrame) elseif alt_algo then -- scale back up win.frame:scale(1.05) win.frame:fit(screenFrame) end if totalOverlaps>0 and avgRatio<0.9 and not alt_algo then local DISPLACE=5 for dx = -DISPLACE,DISPLACE,DISPLACE*2 do if win.frame.x>screenCenter.x then dx=-dx end local r = {x=win.frame.x+win.frame.w/(dx<0 and -2 or 2)+dx,y=win.frame.y,w=abs(dx)*2-1,h=win.frame.h} if isAreaEmpty(r,windows,screenFrame) then win.frame:move(dx,0) if winRatio/avgRatio<1.33 and winRatio<1 then win.frame:scale(1.01)end didwork=true break end end for dy = -DISPLACE,DISPLACE,DISPLACE*2 do if win.frame.y>screenCenter.y then dy=-dy end local r = {y=win.frame.y+win.frame.h/(dy<0 and -2 or 2)+dy,x=win.frame.x,h=abs(dy)*2-1,w=win.frame.w} if isAreaEmpty(r,windows,screenFrame) then win.frame:move(0,dy) if winRatio/avgRatio<1.33 and winRatio<1 then win.frame:scale(1.01)end didwork=true break end end end if thisAnimate and thisAnimate>animate then win.thumb:setFrame(win.frame:tohs()) end end avgRatio=totalRatio/#windows local totalArea=0 for i,win in ipairs(windows) do totalArea=totalArea+win.frame.w*win.frame.h end local halting=iterations==maxIterations if not didwork or halting then log.vf('%s (%d iterations): coverage %.2f%% (%d overlaps)',halting and 'halted' or 'optimal',iterations,totalArea/(screenFrame.w*screenFrame.h)*100,totalOverlaps) end animate=animate and thisAnimate end end local ui = { textColor={1,1,1}, fontName='Lucida Grande', textSize=40, hintLetterWidth=35, backgroundColor={0.3,0.3,0.3,0.95}, closeModeBackgroundColor={0.7,0.1,0.1,0.95}, minimizeModeBackgroundColor={0.1,0.3,0.6,0.95}, minimizedStripBackgroundColor={0.15,0.15,0.15,0.95}, minimizedStripWidth=200, fadeColor={0,0,0,0.8}, fadeStrokeColor={0,0,0}, highlightColor={0.8,0.5,0,0.1}, highlightStrokeColor={0.8,0.5,0,0.8}, strokeWidth=10, showExtraKeys=true, closeModeModifier = 'shift', minimizeModeModifier = 'alt', maxHintLetters = 2, } --- === hs.expose.ui === --- --- Allows customization of the expose user interface --- --- This table contains variables that you can change to customize the look of the UI. The default values are shown in the right hand side of the assignements below. --- --- To represent color values, you can use: --- * a table {red=redN, green=greenN, blue=blueN, alpha=alphaN} --- * a table {redN,greenN,blueN[,alphaN]} - if omitted alphaN defaults to 1.0 --- where redN, greenN etc. are the desired value for the color component between 0.0 and 1.0 --- --- The following variables must be color values: --- * `hs.expose.ui.backgroundColor = {0.3,0.3,0.3,0.95}` --- * `hs.expose.ui.closeModeBackgroundColor = {0.7,0.1,0.1,0.95}` --- * `hs.expose.ui.minimizeModeBackgroundColor = {0.1,0.3,0.6,0.95}` --- * `hs.expose.ui.minimizedStripBackgroundColor = {0.15,0.15,0.15,0.95}` -- this is the strip alongside your dock that contains thumbnails for non-visible windows --- * `hs.expose.ui.highlightColor = {0.8,0.5,0,0.1}` -- highlight candidate thumbnails when pressing a hint key --- * `hs.expose.ui.highlightStrokeColor = {0.8,0.5,0,0.8}` --- * `hs.expose.ui.fadeColor = {0,0,0,0.8}` -- fade excluded thumbnails when pressing a hint key --- * `hs.expose.ui.fadeStrokeColor = {0,0,0}` --- * `hs.expose.ui.textColor = {1,1,1}` --- --- The following variables must be numbers (in screen points): --- * `hs.expose.ui.textSize = 40` --- * `hs.expose.ui.hintLetterWidth = 35` -- max width of a single letter; set accordingly if you change font or text size --- * `hs.expose.ui.strokeWidth = 10` --- --- The following variables must be strings: --- * `hs.expose.ui.fontName = 'Lucida Grande'` --- --- The following variables must be numbers: --- * `hs.expose.ui.maxHintLetters = 2` -- if necessary, hints longer than this will be disambiguated with digits --- --- The following variables must be strings, one of 'cmd', 'shift', 'ctrl' or 'alt': --- * `hs.expose.ui.closeModeModifier = 'shift'` --- * `hs.expose.ui.minimizeModeModifier = 'alt'` --- --- The following variables must be booleans: --- * `hs.expose.ui.showExtraKeys = true` -- show non-hint keybindings at the top of the screen expose.ui=setmetatable({},{__newindex=function(t,k,v) ui[k]=v end,__index=ui}) local function getHints(screens) local function tlen(t) if not t then return 0 end local l=0 for _ in pairs(t) do l=l+1 end return l end local function hasSubHints(t) for k,v in pairs(t) do if type(k)=='string' and #k==1 then return true end end end local hints={apps={}} local reservedHint=1 for _,screen in pairs(screens) do for _,w in ipairs(screen) do local appname=w.appname or '' while #appname<ui.maxHintLetters do appname=appname..tostring(reservedHint) reservedHint=reservedHint+1 end hints[#hints+1]=w hints.apps[appname]=(hints.apps[appname] or 0)+1 w.hint='' end end local function normalize(t,n) --change in place while #t>0 and tlen(t.apps)>0 do if n>ui.maxHintLetters or (tlen(t.apps)==1 and n>1 and not hasSubHints(t)) then -- last app remaining for this hint; give it digits local app=next(t.apps) t.apps={} if #t>1 then --fix so that accumulation is possible local total=#t for i,w in ipairs(t) do t[i]=nil local c=tostring(total<10 and i-(t.m1 and 1 or 0) or floor(i/10)) t[c]=t[c] or {} tinsert(t[c],w) if #t[c]>1 then t[c].apps={app=#t[c]} t[c].m1=c~='0' end w.hint=w.hint..c end end else -- find the app with least #windows and add a hint to it local minfound,minapp=9999 for appname,nwindows in pairs(t.apps) do if nwindows<minfound then minfound=nwindows minapp=appname end end t.apps[minapp]=nil local c=supper(ssub(minapp,n,n)) --TODO what if not long enough t[c]=t[c] or {apps={}} t[c].apps[minapp]=minfound local i=1 while i<=#t do if t[i].appname==minapp then local w=tremove(t,i) tinsert(t[c],w) w.hint=w.hint..c else i=i+1 end end end end for c,subt in pairs(t) do if type(c)=='string' and #c==1 then normalize(subt,n+1) end end end normalize(hints,1) return hints end local function getColor(t) if t.red then return t else return {red=t[1] or 0,green=t[2] or 0,blue=t[3] or 0,alpha=t[4] or 1} end end local function updateHighlights(hints,subtree,show) for c,t in pairs(hints) do if t==subtree then updateHighlights(t,nil,true) elseif type(c)=='string' and #c==1 then if t[1] then t[1].highlight:setFillColor(getColor(show and ui.highlightColor or ui.fadeColor)):setStrokeColor(getColor(show and ui.highlightStrokeColor or ui.fadeStrokeColor)) else updateHighlights(t,subtree,show) end end end end local screens,modals={},{} local modes,activeInstance,tap={} local function exitAll() log.d('exiting') while modals[#modals] do log.vf('exit modal for hint #%d',#modals) tremove(modals).modal:exit() end --cleanup for _,s in pairs(screens) do for _,w in ipairs(s) do if w.thumb then w.thumb:delete() end if w.icon then w.icon:delete() w.highlight:delete() w.hinttext:delete() w.hintrect:delete() end -- if w.rect then w.rect:delete() end -- if w.ratio then w.ratio:delete() end end s.bg:delete() end tap:stop() activeInstance=nil end local function setMode(k,mode) if modes[k]==mode then return end modes[k]=mode for s,screen in pairs(screens) do screen.bg:setFillColor(getColor(modes[k] and (k=='close' and ui.closeModeBackgroundColor or ui.minimizeModeBackgroundColor) or (s=='inv' and ui.minimizedStripBackgroundColor or ui.backgroundColor))) end end local enter,setThumb local function exit() log.vf('exit modal for hint #%d',#modals) tremove(modals).modal:exit() if #modals==0 then return exitAll() end return enter() end enter=function(hints) if not hints then updateHighlights(modals[#modals].hints,nil,true) modals[#modals].modal:enter() elseif hints[1] then --got a hint local h,w=hints[1],hints[1].window local app,appname=w:application(),h.appname if modes.close then log.f('Closing window (%s)',appname) w:close() h.hintrect:delete() h.hinttext:delete() h.highlight:delete() h.thumb:delete() h.icon:delete() hints[1]=nil -- close app if app then if #app:allWindows()==0 then log.f('Quitting application %s',appname) app:kill() end end return enter() elseif modes.min then local newscreen log.f('Toggling window minimized/hidden (%s)',appname) if w:isMinimized() then w:unminimize() newscreen=w:screen():id() elseif app:isHidden() then app:unhide() newscreen=w:screen():id() else w:minimize() newscreen='inv' end h.frame:fit(screens[newscreen].frame) setThumb(h) return enter() else log.f('Focusing window (%s)',appname) if w:isMinimized() then w:unminimize() end w:focus() return exitAll() end else if modals[#modals] then log.vf('exit modal %d',#modals) modals[#modals].modal:exit() end local modal=newmodal() modals[#modals+1]={modal=modal,hints=hints} modal:bind({},'escape',exitAll) modal:bind({},'delete',exit) for c,t in pairs(hints) do if type(c)=='string' and #c==1 then modal:bind({},c,function()updateHighlights(hints,t) enter(t) end) modal:bind({ui.closeModeModifier},c,function()updateHighlights(hints,t) enter(t) end) modal:bind({ui.minimizeModeModifier},c,function()updateHighlights(hints,t) enter(t) end) end end log.vf('enter modal for hint #%d',#modals) modal:enter() end end local function spaceChanged() if not activeInstance then return end local tempinstance=activeInstance -- if tempinstance.wf.currentSpaceWindows then -- wf tracks spaces exitAll() -- if type(tempinstance)=='table' then tempinstance:show() end return tempinstance() -- windowfilter.switchedToSpace(space,function()tempinstance:expose()end) -- end end local spacesWatcher = spaces.watcher.new(spaceChanged) spacesWatcher:start() setThumb=function(w) w.thumb:setFrame(w.frame:tohs()):orderAbove() w.highlight:setFrame(w.frame:tohs()):orderAbove() local hwidth=#w.hint*ui.hintLetterWidth local iconSize=ui.textSize*1.1 local br={x=w.frame.x-hwidth/2-iconSize/2,y=w.frame.y-iconSize/2,w=hwidth+iconSize,h=iconSize} local tr={x=w.frame.x-hwidth/2+iconSize/2,y=w.frame.y-iconSize/2,w=hwidth,h=iconSize} local ir={x=w.frame.x-hwidth/2-iconSize/2,y=w.frame.y-iconSize/2,w=iconSize,h=iconSize} w.hintrect:setFrame(br):orderAbove() w.hinttext:setFrame(tr):orderAbove() w.icon:setFrame(w.appbundle and ir or {x=0,y=0,w=0,h=0}):orderAbove() end local UNAVAILABLE=image.imageFromName'NSStopProgressTemplate' local function showExpose(wins,animate,iterations,alt_algo) -- animate is waaay to slow: don't bother -- alt_algo sometimes performs better in terms of coverage, but (in the last half-broken implementation) always reaches maxIterations -- alt_algo TL;DR: much slower, don't bother log.d('activated') screens={} local hsscreens = screen.allScreens() local mainscreen = hsscreens[1] for _,s in ipairs(hsscreens) do local id=s:id() local frame=s:frame() screens[id]={frame=frame,area=0,bg=drawing.rectangle(frame):setFill(true):setFillColor(getColor(ui.backgroundColor)):show()} end do -- hidden windows strip local invSize=ui.minimizedStripWidth local msid=mainscreen:id() local f=screens[msid].frame local invf={x=f.x,y=f.y,w=f.w,h=f.h} local dock = execute'defaults read com.apple.dock "orientation"':sub(1,-2) if dock=='bottom' then f.h=f.h-invSize invf.y=f.y+f.h invf.h=invSize elseif dock=='left' then f.w=f.w-invSize f.x=f.x+invSize invf.w=invSize elseif dock=='right' then f.w=f.w-invSize invf.x=f.x+f.w invf.w=invSize end screens.inv={area=0,frame=invf,bg=drawing.rectangle(invf):setFill(true):setFillColor(getColor(ui.minimizedStripBackgroundColor)):show()} screens[msid].bg:setFrame(f) end for i=#wins,1,-1 do local w = wins[i] local wid = w.id and w:id() local app = w:application() local appname,appbundle = app:title(),app:bundleID() local wsc = w.screen and w:screen() local scid = wsc and wsc:id() if not scid or not wid or not w:isVisible() then scid='inv' end local frame=w:frame() screens[scid].area=screens[scid].area+frame.w*frame.h screens[scid][#screens[scid]+1] = {appname=appname,appbundle=appbundle,window=w, frame=rect.new(frame),originalFrame=frame,area=frame.w*frame.h,id=wid} end local hints=getHints(screens) for _,s in pairs(screens) do if animate then for _,w in ipairs(s) do w.thumb = drawing.image(w.originalFrame,window.snapshotForID(w.id)):show() --FIXME gh#413 end end fitWindows(s,iterations or 200,animate and 0 or nil,alt_algo) for _,w in ipairs(s) do if animate then w.thumb:setFrame(w.frame:tohs()) else local thumb=w.id and window.snapshotForID(w.id) w.thumb = drawing.image(w.frame:tohs(),thumb or UNAVAILABLE) end -- w.ratio=drawing.text(w.frame:tohs(),sformat('%d%%',w.frame.w*w.frame.h*100/w.area)):setTextColor{red=1,green=0,blue=0,alpha=1}:show() local f=w.frame:tohs() w.highlight=drawing.rectangle(f):setFill(true):setFillColor(getColor(ui.highlightColor)):setStrokeWidth(ui.strokeWidth):setStrokeColor(getColor(ui.highlightStrokeColor)) w.hintrect=drawing.rectangle(f):setFill(true):setFillColor(getColor(ui.backgroundColor)):setStroke(false):setRoundedRectRadii(ui.textSize/4,ui.textSize/4) w.hinttext=drawing.text(f,w.hint):setTextColor(getColor(ui.textColor)):setTextSize(ui.textSize):setTextFont(ui.fontName) local icon=w.appbundle and image.imageFromAppBundle(w.appbundle) w.icon = drawing.image(f,icon or UNAVAILABLE) setThumb(w) w.thumb:show() w.highlight:show() w.hintrect:show() w.hinttext:show() w.icon:show() end end enter(hints) tap=eventtap.new({eventtap.event.types.flagsChanged},function(e) local function hasOnly(t,mod) local n=next(t) if n~=mod then return end if not next(t,n) then return true end end setMode('close',hasOnly(e:getFlags(),ui.closeModeModifier)) setMode('min',hasOnly(e:getFlags(),ui.minimizeModeModifier)) end) tap:start() end --- hs.expose:toggleShow(applicationWindows) --- Function --- Toggles the expose - see `hs.expose:show()` and `hs.expose:hide()` --- --- Parameters: --- * applicationWindows --- --- Returns: --- * None function expose:toggleShow(currentApp) if activeInstance then return self:hide() else return self:show(currentApp) end end --- hs.expose:hide() --- Function --- Hides the expose, if visible, and exits the modal mode. --- Call this function if you need to make sure the modal is exited without waiting for the user to press `esc`. --- --- Parameters: --- * None --- --- Returns: --- * None function expose:hide() if activeInstance then return exitAll() end end --- hs.expose:show(applicationWindows) --- Method --- Shows an expose-like screen with modal keyboard hints for switching to, closing or minimizing/unminimizing windows. --- --- Parameters: --- * applicationWindows - (optional) if true, only show windows of the active application (within the --- scope of the instance windowfilter); otherwise show all windows allowed by the instance windowfilter --- --- Returns: --- * None --- --- Notes: --- * Completing a hint will exit the expose and focus the selected window. --- * Pressing esc will exit the expose and with no action taken. --- * If shift is being held when a hint is completed (the background will be red), the selected --- window will be closed. If it's the last window of an application, the application will be closed. --- * If alt is being held when a hint is completed (the background will be blue), the selected --- window will be minimized (if visible) or unminimized/unhidden (if minimized or hidden). local function getApplicationWindows() local a=application.frontmostApplication() if not a then log.w('Cannot get active application') return end return a:allWindows() end function expose:show(currentApp,...) if activeInstance then return end local wins=self.wf:getWindows() if currentApp then local allwins,appwins=wins,getApplicationWindows() if not appwins then return end wins={} for _,w in ipairs(appwins) do if fnutils.contains(allwins,w) then wins[#wins+1]=w end --FIXME probably requires window userdata 'recycling' (or at least __eq metamethod) end end activeInstance=function()return self:show(currentApp)end return showExpose(wins,...) end --- hs.expose.expose(windows) --- Function --- Shows an expose-like screen with modal keyboard hints for switching to, closing or minimizing/unminimizing windows. --- If an expose is already visible, calling this function will toggle it off. --- --- Parameters: --- * windows - a list of windows to expose; if omitted or nil, `hs.window.allWindows()` will be used --- --- Returns: --- * None --- --- Notes: --- * Due to OS X limitations, this function cannot show hidden applications or windows across --- Mission Control Spaces; if you need these, you can create an instance with `hs.expose.new` --- (set the windowfilter for your needs) and then use `:show()` --- * Completing a hint will exit the expose and focus the selected window. --- * Pressing esc will exit the expose and with no action taken. --- * If shift is being held when a hint is completed (the background will be red), the selected --- window will be closed. If it's the last window of an application, the application will be closed. --- * If alt is being held when a hint is completed (the background will be blue), the selected --- window will be minimized (if visible) or unminimized/unhidden (if minimized or hidden). function expose.expose(wins,...) if activeInstance then return exitAll() end local origWins=wins if not wins then wins=window.orderedWindows() end if type(wins)~='table' then error('windows must be a table',2) end activeInstance=function()return expose.expose(origWins)end return showExpose(wins,...) end --- hs.expose.exposeApplicationWindows() --- Function --- Shows an expose for the windows of the active application. --- If an expose is already visible, calling this function will toggle it off. --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * This is just a convenience wrapper for `hs.expose.expose(hs.window.focusedWindow():application():allWindows())` function expose.exposeApplicationWindows(...) if activeInstance then return exitAll() end activeInstance=function()return expose.exposeApplicationWindows()end local wins=getApplicationWindows() return wins and showExpose(wins,...) end --- hs.expose.new(windowfilter) -> hs.expose --- Constructor --- Creates a new hs.expose instance. It uses a windowfilter to determine which windows to show --- --- Parameters: --- * windowfilter - (optional) it can be: --- * `nil` or omitted (as in `myexpose=hs.expose.new()`): the default windowfilter will be used --- * an `hs.window.filter` object --- * otherwise all parameters are passed to `hs.window.filter.new` to create a new instance --- --- Returns: --- * the new instance --- --- Notes: --- * The default windowfilter (or an unmodified copy) will allow the expose instance to be populated with windows from all --- Mission Control Spaces (unlike the OSX expose); to limit to windows in the current Space only, use `:trackSpaces(true)` --- * The default windowfilter (or an unmodified copy) will not track hidden windows; to let the expose instance also manage hidden windows, --- use `:setDefaultFilter()` and/or other appropriate application-specific visiblity rules function expose.new(wf,...) local o = setmetatable({},{__index=expose}) if wf==nil then log.i('New expose instance, using default windowfilter') o.wf=windowfilter.default elseif type(wf)=='table' and type(wf.isWindowAllowed)=='function' then log.i('New expose instance, using windowfilter instance') o.wf=wf else log.i('New expose instance, creating windowfilter') o.wf=windowfilter.new(wf,...) end o.wf:keepActive() return o end return expose
mit
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/talents/uber/uber.lua
1
3332
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newTalentType{ hide = true, type="uber/strength", name = "strength", description = "Ultimate talents you may only know one." } newTalentType{ hide = true, type="uber/dexterity", name = "dexterity", description = "Ultimate talents you may only know one." } newTalentType{ hide = true, type="uber/constitution", name = "constitution", description = "Ultimate talents you may only know one." } newTalentType{ hide = true, type="uber/magic", name = "magic", description = "Ultimate talents you may only know one." } newTalentType{ hide = true, type="uber/willpower", name = "willpower", description = "Ultimate talents you may only know one." } newTalentType{ hide = true, type="uber/cunning", name = "cunning", description = "Ultimate talents you may only know one." } newTalentType{ hide = true, type="uber/other", name = "other", description = "Ultimate talents you may only know one." } knowRessource = function(self, r, v) local cnt = 0 for tid, l in pairs(self.talents) do local t = self:getTalentFromId(tid) if rawget(t, r) or rawget(t, "sustain_"..r) then cnt = cnt + l end end return cnt >= v end uberTalent = function(t) t.type = {"uber/strength", 1} t.uber = true t.require = t.require or {} t.require.level = 30 t.require.stat = t.require.stat or {} t.require.stat.str = 50 newTalent(t) end load("/data/talents/uber/str.lua") uberTalent = function(t) t.type = {"uber/dexterity", 1} t.uber = true t.require = t.require or {} t.require.stat = t.require.stat or {} t.require.level = 30 t.require.stat.dex = 50 newTalent(t) end load("/data/talents/uber/dex.lua") uberTalent = function(t) t.type = {"uber/constitution", 1} t.uber = true t.require = t.require or {} t.require.stat = t.require.stat or {} t.require.level = 30 t.require.stat.con = 50 newTalent(t) end load("/data/talents/uber/const.lua") uberTalent = function(t) t.type = {"uber/magic", 1} t.uber = true t.require = t.require or {} t.require.stat = t.require.stat or {} t.require.level = 30 t.require.stat.mag = 50 newTalent(t) end load("/data/talents/uber/mag.lua") uberTalent = function(t) t.type = {"uber/willpower", 1} t.uber = true t.require = t.require or {} t.require.level = 30 t.require.stat = t.require.stat or {} t.require.stat.wil = 50 newTalent(t) end load("/data/talents/uber/wil.lua") uberTalent = function(t) t.type = {"uber/cunning", 1} t.uber = true t.require = t.require or {} t.require.level = 30 t.require.stat = t.require.stat or {} t.require.stat.cun = 50 newTalent(t) end load("/data/talents/uber/cun.lua")
gpl-3.0
Blackdutchie/Zero-K
LuaRules/Utilities/glVolumes.lua
4
7733
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Exported Functions: -- gl.Utilities.DrawMyBox(minX,minY,minZ, maxX,maxY,maxZ) -- gl.Utilities.DrawMyCylinder(x,y,z, height,radius,divs) -- gl.Utilities.DrawMyHollowCylinder(x,y,z, height,radius,innerRadius,divs) -- gl.Utilities.DrawGroundRectangle(x1,z1,x2,z2) -- gl.Utilities.DrawGroundCircle(x,z,radius) -- gl.Utilities.DrawGroundHollowCircle(x,z,radius,innerRadius) -- gl.Utilities.DrawVolume(vol_dlist) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gl) then return end gl.Utilities = gl.Utilities or {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local min = math.min local max = math.max local sin = math.sin local cos = math.cos local floor = math.floor local TWO_PI = math.pi * 2 local glVertex = gl.Vertex GL.KEEP = 0x1E00 GL.INCR_WRAP = 0x8507 GL.DECR_WRAP = 0x8508 GL.INCR = 0x1E02 GL.DECR = 0x1E03 GL.INVERT = 0x150A local stencilBit1 = 0x01 local stencilBit2 = 0x10 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gl.Utilities.DrawMyBox(minX,minY,minZ, maxX,maxY,maxZ) gl.BeginEnd(GL.QUADS, function() --// top glVertex(minX, maxY, minZ) glVertex(minX, maxY, maxZ) glVertex(maxX, maxY, maxZ) glVertex(maxX, maxY, minZ) --// bottom glVertex(minX, minY, minZ) glVertex(maxX, minY, minZ) glVertex(maxX, minY, maxZ) glVertex(minX, minY, maxZ) end) gl.BeginEnd(GL.QUAD_STRIP, function() --// sides glVertex(minX, maxY, minZ) glVertex(minX, minY, minZ) glVertex(minX, maxY, maxZ) glVertex(minX, minY, maxZ) glVertex(maxX, maxY, maxZ) glVertex(maxX, minY, maxZ) glVertex(maxX, maxY, minZ) glVertex(maxX, minY, minZ) glVertex(minX, maxY, minZ) glVertex(minX, minY, minZ) end) end local function CreateSinCosTable(divs) local sinTable = {} local cosTable = {} local divAngle = TWO_PI / divs local alpha = 0 local i = 1 repeat sinTable[i] = sin(alpha) cosTable[i] = cos(alpha) alpha = alpha + divAngle i = i + 1 until (alpha >= TWO_PI) sinTable[i] = 0.0 -- sin(TWO_PI) cosTable[i] = 1.0 -- cos(TWO_PI) return sinTable, cosTable end function gl.Utilities.DrawMyCylinder(x,y,z, height,radius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) local bottomY = y - (height / 2) local topY = y + (height / 2) gl.BeginEnd(GL.TRIANGLE_STRIP, function() --// top for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], topY, z + radius*cosTable[i]) glVertex(x, topY, z) end --// degenerate glVertex(x, topY , z) glVertex(x, bottomY, z) glVertex(x, bottomY, z) --// bottom for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], bottomY, z + radius*cosTable[i]) glVertex(x, bottomY, z) end --// degenerate glVertex(x, bottomY, z) glVertex(x, bottomY, z+radius) glVertex(x, bottomY, z+radius) --// sides for i = 1, #sinTable do local rx = x + radius * sinTable[i] local rz = z + radius * cosTable[i] glVertex(rx, topY , rz) glVertex(rx, bottomY, rz) end end) end function gl.Utilities.DrawMyHollowCylinder(x,y,z, height,radius,inRadius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) local bottomY = y - (height / 2) local topY = y + (height / 2) gl.BeginEnd(GL.TRIANGLE_STRIP, function() --// top for i = 1, #sinTable do local sa = sinTable[i] local ca = cosTable[i] glVertex(x + inRadius*sa, topY, z + inRadius*ca) glVertex(x + radius*sa, topY, z + radius*ca) end --// sides for i = 1, #sinTable do local rx = x + radius * sinTable[i] local rz = z + radius * cosTable[i] glVertex(rx, topY , rz) glVertex(rx, bottomY, rz) end --// bottom for i = 1, #sinTable do local sa = sinTable[i] local ca = cosTable[i] glVertex(x + radius*sa, bottomY, z + radius*ca) glVertex(x + inRadius*sa, bottomY, z + inRadius*ca) end if (inRadius > 0) then --// inner sides for i = 1, #sinTable do local rx = x + inRadius * sinTable[i] local rz = z + inRadius * cosTable[i] glVertex(rx, bottomY, rz) glVertex(rx, topY , rz) end end end) end local heightMargin = 2000 local minheight, maxheight = Spring.GetGroundExtremes() --the returned values do not change even if we terraform the map local averageGroundHeight = (minheight + maxheight) / 2 local shapeHeight = heightMargin + (maxheight - minheight) + heightMargin local box = gl.CreateList(gl.Utilities.DrawMyBox,0,-0.5,0,1,0.5,1) function gl.Utilities.DrawGroundRectangle(x1,z1,x2,z2) if (type(x1) == "table") then local rect = x1 x1,z1,x2,z2 = rect[1],rect[2],rect[3],rect[4] end gl.PushMatrix() gl.Translate(x1, averageGroundHeight, z1) gl.Scale(x2-x1, shapeHeight, z2-z1) gl.Utilities.DrawVolume(box) gl.PopMatrix() end local cylinder = gl.CreateList(gl.Utilities.DrawMyCylinder,0,0,0,1,1,35) function gl.Utilities.DrawGroundCircle(x,z,radius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawVolume(cylinder) gl.PopMatrix() end local hollowCylinders = { [ 0 ] = cylinder, } local function GetHollowCylinder(radius, innerRadius) if (innerRadius >= 1) then innerRadius = min(innerRadius / radius, 1.0) end innerRadius = floor(innerRadius * 100 + 0.5) / 100 if (not hollowCylinders[innerRadius]) then hollowCylinders[innerRadius] = gl.CreateList(gl.Utilities.DrawMyHollowCylinder,0,0,0,1,1,innerRadius,35) end return hollowCylinders[innerRadius] end --// when innerRadius is < 1, its value is treated as relative to radius --// when innerRadius is >=1, its value is treated as absolute value in elmos function gl.Utilities.DrawGroundHollowCircle(x,z,radius,innerRadius) local hollowCylinder = GetHollowCylinder(radius, innerRadius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawVolume(hollowCylinder) gl.PopMatrix() end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gl.Utilities.DrawVolume(vol_dlist) gl.DepthMask(false) if (gl.DepthClamp) then gl.DepthClamp(true) end gl.StencilTest(true) gl.Culling(false) gl.DepthTest(true) gl.ColorMask(false, false, false, false) gl.StencilOp(GL.KEEP, GL.INCR, GL.KEEP) --gl.StencilOp(GL.KEEP, GL.INVERT, GL.KEEP) gl.StencilMask(0x11) gl.StencilFunc(GL.ALWAYS, 0, 0) gl.CallList(vol_dlist) gl.Culling(GL.FRONT) gl.DepthTest(false) gl.ColorMask(true, true, true, true) gl.StencilOp(GL.ZERO, GL.ZERO, GL.ZERO) gl.StencilMask(0x11) gl.StencilFunc(GL.NOTEQUAL, 0, 0+1) gl.CallList(vol_dlist) if (gl.DepthClamp) then gl.DepthClamp(false) end gl.StencilTest(false) -- gl.DepthTest(true) gl.Culling(false) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
electricpandafishstudios/Spoon
game/engines/te4-1.4.1/engine/Autolevel.lua
1
1728
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" --- Handles autoleveling schemes -- Used mainly for NPCS, although it could also be used for player allies -- or players themselves for lazy players/modules -- @classmod engine.Autolevel module(..., package.seeall, class.make) _M.schemes = {} --- Register Scheme for use with actors -- @param[type=table] t your scheme definition -- @usage registerScheme({ name = "warrior", levelup = function(self) self:learnStats{ self.STAT_STR, self.STAT_STR, self.STAT_DEX } end}) function _M:registerScheme(t) assert(t.name, "no autolevel name") assert(t.levelup, "no autolevel levelup function") _M.schemes[t.name] = t end --- Triggers the autolevel function defined with registerScheme for the specified actor -- @param[type=Actor] actor function _M:autoLevel(actor) if not actor.autolevel then return end assert(_M.schemes[actor.autolevel], "no autoleveling scheme "..actor.autolevel) _M.schemes[actor.autolevel].levelup(actor) end
gpl-3.0
musenshen/SandBoxLua
src/cocos/ui/GuiConstants.lua
38
2802
ccui = ccui or {} ccui.BrightStyle = { none = -1, normal = 0, highlight = 1, } ccui.TextureResType = { localType = 0, plistType = 1, } ccui.TouchEventType = { began = 0, moved = 1, ended = 2, canceled = 3, } ccui.SizeType = { absolute = 0, percent = 1, } ccui.PositionType = { absolute = 0, percent = 1, } ccui.CheckBoxEventType = { selected = 0, unselected = 1, } ccui.TextFiledEventType = { attach_with_ime = 0, detach_with_ime = 1, insert_text = 2, delete_backward = 3, } ccui.LayoutBackGroundColorType = { none = 0, solid = 1, gradient = 2, } ccui.LayoutType = { ABSOLUTE = 0, VERTICAL = 1, HORIZONTAL = 2, RELATIVE = 3, } ccui.LayoutParameterType = { none = 0, linear = 1, relative = 2, } ccui.LinearGravity = { none = 0, left = 1, top = 2, right = 3, bottom = 4, centerVertical = 5, centerHorizontal = 6, } ccui.RelativeAlign = { alignNone = 0, alignParentTopLeft = 1, alignParentTopCenterHorizontal = 2, alignParentTopRight = 3, alignParentLeftCenterVertical = 4, centerInParent = 5, alignParentRightCenterVertical = 6, alignParentLeftBottom = 7, alignParentBottomCenterHorizontal = 8, alignParentRightBottom = 9, locationAboveLeftAlign = 10, locationAboveCenter = 11, locationAboveRightAlign = 12, locationLeftOfTopAlign = 13, locationLeftOfCenter = 14, locationLeftOfBottomAlign = 15, locationRightOfTopAlign = 16, locationRightOfCenter = 17, locationRightOfBottomAlign = 18, locationBelowLeftAlign = 19, locationBelowCenter = 20, locationBelowRightAlign = 21, } ccui.SliderEventType = {percentChanged = 0} ccui.LoadingBarDirection = { LEFT = 0, RIGHT = 1} ccui.ScrollViewDir = { none = 0, vertical = 1, horizontal = 2, both = 3, } ccui.ScrollViewMoveDir = { none = 0, up = 1, down = 2, left = 3, right = 4, } ccui.ScrollviewEventType = { scrollToTop = 0, scrollToBottom = 1, scrollToLeft = 2, scrollToRight = 3, scrolling = 4, bounceTop = 5, bounceBottom = 6, bounceLeft = 7, bounceRight = 8, } ccui.ListViewDirection = { none = 0, vertical = 1, horizontal = 2, } ccui.ListViewMoveDirection = { none = 0, up = 1, down = 2, left = 3, right = 4, } ccui.ListViewEventType = { ONSELECTEDITEM_START = 0, ONSELECTEDITEM_END = 1, } ccui.PageViewEventType = { turning = 0, } ccui.PVTouchDir = { touchLeft = 0, touchRight = 1, } ccui.ListViewGravity = { left = 0, right = 1, centerHorizontal = 2, top = 3, bottom = 4 , centerVertical = 5, } ccui.TextType = { SYSTEM = 0, TTF = 1, }
mit
Blackdutchie/Zero-K
LuaRules/Gadgets/weapon_noexplode_stopper.lua
4
2149
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Noexplode Stopper", desc = "Implements noexplodes that do not penetrate shields.", author = "GoogleFrog", date = "4 Feb 2012", license = "None", layer = 50, enabled = true } end local passedProjectile = {} function gadget:ProjectileDestroyed(proID) if passedProjectile[proID] then passedProjectile[proID] = false end end function gadget:ShieldPreDamaged(proID, proOwnerID, shieldEmitterWeaponNum, shieldCarrierUnitID, bounceProjectile) --[[ -- Code that causes projectile bounce if Spring.ValidUnitID(shieldCarrierUnitID) then local px, py, pz = Spring.GetProjectilePosition(proID) local vx, vy, vz = Spring.GetProjectileVelocity(proID) local sx, sy, sz = Spring.GetUnitPosition(shieldCarrierUnitID) local rx, ry, rz = px-sx, py-sy, pz-sz local f = 2 * (rx*vx + ry*vy + rz*vz) / (rx^2 + ry^2 + rz^2) local nx, ny, nz = vx - f*rx, vy - f*ry, vz - f*rz Spring.SetProjectileVelocity(proID, nx, ny, nz) return true end return false --]] local wname = Spring.GetProjectileName(proID) if passedProjectile[proID] then return true --elseif select(2, Spring.GetProjectilePosition(proID)) < 0 then -- passedProjectile[proID] = true -- return true elseif wname and shieldCarrierUnitID and shieldEmitterWeaponNum then local wd = WeaponDefNames[wname] if wd and wd.noExplode then local on, charge = Spring.GetUnitShieldState(shieldCarrierUnitID) --FIXME figure out a way to get correct shield if charge and wd.damages[0] < charge then --Spring.MarkerAddPoint(x,y,z,"") Spring.SetProjectilePosition(proID,-100000,-100000,-100000) Spring.SetProjectileCollision(proID) else passedProjectile[proID] = true end end end return false end
gpl-2.0
nimaghorbani/nimatelegram
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
liamneit/Cornucopia
Cornucopia/Libs/Sushi-3.0/Classes/CallHandler.lua
1
1398
--[[ Copyright 2008-2015 João Cardoso Sushi is distributed under the terms of the GNU General Public License (or the Lesser GPL). This file is part of Sushi. Sushi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Sushi 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 Sushi. If not, see <http://www.gnu.org/licenses/>. --]] local Handler = MakeSushi(3, nil, 'CallHandler', UIParent) if not Handler then return end --[[ Builder ]]-- function Handler:OnAcquire () self.calls = {} self:ClearAllPoints() self:Show() end function Handler:OnRelease () self:SetParent(UIParent) self:ClearAllPoints() self:SetPoint('TOP', UIParent, 'BOTTOM') -- outside of screen self:Hide() end --[[ API ]]-- function Handler:SetCall (event, method) self.calls[event] = method end function Handler:GetCall (event) return self.calls and self.calls[event] end function Handler:FireCall (event, ...) local call = self:GetCall(event) if call then call(self, ...) end end
gpl-3.0
xAleXXX007x/Witcher-RolePlay
nutscript/gamemode/core/libs/cl_hud.lua
5
1058
nut.hud = {} local owner, w, h, ceil, ft, clmp ceil = math.ceil clmp = math.Clamp local aprg, aprg2 = 0, 0 function nut.hud.drawDeath() owner = LocalPlayer() ft = FrameTime() w, h = ScrW(), ScrH() if (owner:getChar()) then if (owner:Alive()) then if (aprg != 0) then aprg2 = clmp(aprg2 - ft*1.3, 0, 1) if (aprg2 == 0) then aprg = clmp(aprg - ft*.7, 0, 1) end end else if (aprg2 != 1) then aprg = clmp(aprg + ft*.5, 0, 1) if (aprg == 1) then aprg2 = clmp(aprg2 + ft*.4, 0, 1) end end end end if (IsValid(nut.char.gui) and nut.gui.char:IsVisible() or !owner:getChar()) then return end surface.SetDrawColor(0, 0, 0, ceil((aprg^.5) * 255)) surface.DrawRect(-1, -1, w+2, h+2) local tx, ty = nut.util.drawText(L"youreDead", w/2, h/2, ColorAlpha(color_white, aprg2 * 255), 1, 1, "nutDynFontMedium", aprg2 * 255) end hook.Add("GetCrosshairAlpha", "nutCrosshair", function(alpha) return alpha * (1 - aprg) end) function nut.hud.drawAll(postHook) if (postHook) then nut.hud.drawDeath() end end
mit
teslamint/luci
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
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/zones/town-gates-of-morning/traps.lua
1
3592
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/traps/store.lua") newEntity{ base = "BASE_STORE", define_as = "HEAVY_ARMOR_STORE", name="Impenetrable Plates", display='2', color=colors.UMBER, resolvers.store("HEAVY_ARMOR", "sunwall", "store/shop_door.png", "store/shop_sign_impenetrable_plates.png"), } newEntity{ base = "BASE_STORE", define_as = "LIGHT_ARMOR_STORE", name="Quality Leather", display='2', color=colors.UMBER, resolvers.store("LIGHT_ARMOR", "sunwall", "store/shop_door.png", "store/shop_sign_quality_leather.png"), } newEntity{ base = "BASE_STORE", define_as = "CLOTH_ARMOR_STORE", name="Arcane Cloth", display='2', color=colors.UMBER, resolvers.store("CLOTH_ARMOR", "sunwall", "store/shop_door.png", "store/shop_sign_arcane_cloth.png"), } newEntity{ base = "BASE_STORE", define_as = "SWORD_WEAPON_STORE", name="Swordmaster", display='3', color=colors.UMBER, resolvers.store("SWORD_WEAPON", "sunwall", "store/shop_door.png", "store/shop_sign_swordsmith.png"), } newEntity{ base = "BASE_STORE", define_as = "KNIFE_WEAPON_STORE", name="Night Affairs", display='3', color=colors.UMBER, resolvers.store("KNIFE_WEAPON", "sunwall", "store/shop_door.png", "store/shop_sign_night_affairs.png"), } newEntity{ base = "BASE_STORE", define_as = "AXE_WEAPON_STORE", name="Orc Cutters", display='3', color=colors.UMBER, resolvers.store("AXE_WEAPON", "sunwall", "store/shop_door.png", "store/shop_sign_orc_cutters.png"), } newEntity{ base = "BASE_STORE", define_as = "MAUL_WEAPON_STORE", name="Mauling for Brutes", display='3', color=colors.UMBER, resolvers.store("MAUL_WEAPON", "sunwall", "store/shop_door.png", "store/shop_sign_mauling_brutes.png"), } newEntity{ base = "BASE_STORE", define_as = "ARCHER_WEAPON_STORE", name="Bows and Slings", display='3', color=colors.UMBER, resolvers.store("ARCHER_WEAPON", "sunwall", "store/shop_door.png", "store/shop_sign_bows_slings.png"), } newEntity{ base = "BASE_STORE", define_as = "STAFF_WEAPON_STORE", name="Sook's Arcane Goodness", display='3', color=colors.UMBER, resolvers.store("STAFF_WEAPON", "sunwall", "store/shop_door.png", "store/shop_sign_sooks_goodness.png"), } newEntity{ base = "BASE_STORE", define_as = "HERBALIST", name="Sarah's Herbal Infusions", display='4', color=colors.LIGHT_GREEN, resolvers.store("POTION", "sunwall", "store/shop_door.png", "store/shop_sign_saras_herbal_infusions.png"), } newEntity{ base = "BASE_STORE", define_as = "RUNES", name="Sook's Runes and other Harmless Contraptions", display='5', color=colors.LIGHT_RED, resolvers.store("SCROLL", "sunwall", "store/shop_door.png", "store/shop_sign_sooks_runes.png"), } newEntity{ base = "BASE_STORE", define_as = "ZEMEKKYS", name="Zemekkys Home", display='+', color=colors.UMBER, image = "store/shop_door_barred.png", resolvers.chatfeature("zemekkys", "sunwall"), }
gpl-3.0
sleepingwit/premake-core
mobdebug.lua
14
68852
-- -- MobDebug -- Lua remote debugger -- Copyright 2011-15 Paul Kulchenko -- Based on RemDebug 1.0 Copyright Kepler Project 2005 -- -- use loaded modules or load explicitly on those systems that require that local require = require local io = io or require "io" local table = table or require "table" local string = string or require "string" local coroutine = coroutine or require "coroutine" local debug = require "debug" -- protect require "os" as it may fail on embedded systems without os module local os = os or (function(module) local ok, res = pcall(require, module) return ok and res or nil end)("os") local mobdebug = { _NAME = "mobdebug", _VERSION = "0.702", _COPYRIGHT = "Paul Kulchenko", _DESCRIPTION = "Mobile Remote Debugger for the Lua programming language", port = os and os.getenv and tonumber((os.getenv("MOBDEBUG_PORT"))) or 8172, checkcount = 200, yieldtimeout = 0.02, -- yield timeout (s) connecttimeout = 2, -- connect timeout (s) } local HOOKMASK = "lcr" local error = error local getfenv = getfenv local setfenv = setfenv local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2 local pairs = pairs local setmetatable = setmetatable local tonumber = tonumber local unpack = table.unpack or unpack local rawget = rawget local gsub, sub, find = string.gsub, string.sub, string.find -- if strict.lua is used, then need to avoid referencing some global -- variables, as they can be undefined; -- use rawget to avoid complaints from strict.lua at run-time. -- it's safe to do the initialization here as all these variables -- should get defined values (if any) before the debugging starts. -- there is also global 'wx' variable, which is checked as part of -- the debug loop as 'wx' can be loaded at any time during debugging. local genv = _G or _ENV local jit = rawget(genv, "jit") local MOAICoroutine = rawget(genv, "MOAICoroutine") -- ngx_lua debugging requires a special handling as its coroutine.* -- methods use a different mechanism that doesn't allow resume calls -- from debug hook handlers. -- Instead, the "original" coroutine.* methods are used. -- `rawget` needs to be used to protect against `strict` checks, but -- ngx_lua hides those in a metatable, so need to use that. local metagindex = getmetatable(genv) and getmetatable(genv).__index local ngx = type(metagindex) == "table" and metagindex.rawget and metagindex:rawget("ngx") or nil local corocreate = ngx and coroutine._create or coroutine.create local cororesume = ngx and coroutine._resume or coroutine.resume local coroyield = ngx and coroutine._yield or coroutine.yield local corostatus = ngx and coroutine._status or coroutine.status local corowrap = coroutine.wrap if not setfenv then -- Lua 5.2+ -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html -- this assumes f is a function local function findenv(f) local level = 1 repeat local name, value = debug.getupvalue(f, level) if name == '_ENV' then return level, value end level = level + 1 until name == nil return nil end getfenv = function (f) return(select(2, findenv(f)) or _G) end setfenv = function (f, t) local level = findenv(f) if level then debug.setupvalue(f, level, t) end return f end end -- check for OS and convert file names to lower case on windows -- (its file system is case insensitive, but case preserving), as setting a -- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua. -- OSX and Windows behave the same way (case insensitive, but case preserving). -- OSX can be configured to be case-sensitive, so check for that. This doesn't -- handle the case of different partitions having different case-sensitivity. local win = os and os.getenv and (os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows')) and true or false local mac = not win and (os and os.getenv and os.getenv('DYLD_LIBRARY_PATH') or not io.open("/proc")) and true or false local iscasepreserving = win or (mac and io.open('/library') ~= nil) -- turn jit off based on Mike Pall's comment in this discussion: -- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2 -- "You need to turn it off at the start if you plan to receive -- reliable hook calls at any later point in time." if jit and jit.off then jit.off() end local socket = require "socket" local coro_debugger local coro_debugee local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 } local breakpoints = {} local watches = {} local lastsource local lastfile local watchescnt = 0 local abort -- default value is nil; this is used in start/loop distinction local seen_hook = false local checkcount = 0 local step_into = false local step_over = false local step_level = 0 local stack_level = 0 local server local buf local outputs = {} local iobase = {print = print} local basedir = "" local deferror = "execution aborted at default debugee" local debugee = function () local a = 1 for _ = 1, 10 do a = a + 1 end error(deferror) end local function q(s) return string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end local serpent = (function() ---- include Serpent module for serialization local n, v = "serpent", "0.30" -- (C) 2012-17 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 getmetatable = debug and debug.getmetatable or getmetatable local pairs = function(t) return next, t end -- avoid using __pairs in Lua 5.2+ 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(type(G[g]) == 'table' and 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 maxlen, metatostring = tonumber(opts.maxlength), opts.metatostring local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local numformat = opts.numformat or "%.17g" 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 numformat:format(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 ' --[['..select(2, pcall(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 -- protect from those cases where __tostring may fail if type(mt) == 'table' then local to, tr = pcall(function() return mt.__tostring(t) end) local so, sr = pcall(function() return mt.__serialize(t) end) if (opts.metatostring ~= false and to or so) then -- knows how to serialize itself seen[t] = insref or spath t = so and sr or tr ttype = type(t) end -- new value falls through to be serialized end if ttype == "table" then if level >= maxl then return tag..'{}'..comment('maxlvl', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty if maxlen and maxlen < 0 then return tag..'{}'..comment('maxlen', level) end 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.keyignore and opts.keyignore[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) if maxlen then maxlen = maxlen - #out[#out] if maxlen < 0 then break end end 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,level) 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 if opts.nocode then return tag.."function() --[[..skipped..]] end"..comment(t, level) end local ok, res = pcall(string.dump, t) local func = ok and "((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 } end)() ---- end of Serpent module mobdebug.line = serpent.line mobdebug.dump = serpent.dump mobdebug.linemap = nil mobdebug.loadstring = loadstring local function removebasedir(path, basedir) if iscasepreserving then -- check if the lowercased path matches the basedir -- if so, return substring of the original path (to not lowercase it) return path:lower():find('^'..q(basedir:lower())) and path:sub(#basedir+1) or path else return string.gsub(path, '^'..q(basedir), '') end end local function stack(start) local function vars(f) local func = debug.getinfo(f, "f").func local i = 1 local locals = {} -- get locals while true do local name, value = debug.getlocal(f, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, select(2,pcall(tostring,value))} end i = i + 1 end -- get varargs (these use negative indices) i = 1 while true do local name, value = debug.getlocal(f, -i) -- `not name` should be enough, but LuaJIT 2.0.0 incorrectly reports `(*temporary)` names here if not name or name ~= "(*vararg)" then break end locals[name:gsub("%)$"," "..i..")")] = {value, select(2,pcall(tostring,value))} i = i + 1 end -- get upvalues i = 1 local ups = {} while func do -- check for func as it may be nil for tail calls local name, value = debug.getupvalue(func, i) if not name then break end ups[name] = {value, select(2,pcall(tostring,value))} i = i + 1 end return locals, ups end local stack = {} local linemap = mobdebug.linemap for i = (start or 0), 100 do local source = debug.getinfo(i, "Snl") if not source then break end local src = source.source if src:find("@") == 1 then src = src:sub(2):gsub("\\", "/") if src:find("%./") == 1 then src = src:sub(3) end end table.insert(stack, { -- remove basedir from source {source.name, removebasedir(src, basedir), linemap and linemap(source.linedefined, source.source) or source.linedefined, linemap and linemap(source.currentline, source.source) or source.currentline, source.what, source.namewhat, source.short_src}, vars(i+1)}) if source.what == 'main' then break end end return stack end local function set_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif iscasepreserving then file = string.lower(file) end if not breakpoints[line] then breakpoints[line] = {} end breakpoints[line][file] = true end local function remove_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif file == '*' and line == 0 then breakpoints = {} elseif iscasepreserving then file = string.lower(file) end if breakpoints[line] then breakpoints[line][file] = nil end end local function has_breakpoint(file, line) return breakpoints[line] and breakpoints[line][iscasepreserving and string.lower(file) or file] end local function restore_vars(vars) if type(vars) ~= 'table' then return end -- locals need to be processed in the reverse order, starting from -- the inner block out, to make sure that the localized variables -- are correctly updated with only the closest variable with -- the same name being changed -- first loop find how many local variables there is, while -- the second loop processes them from i to 1 local i = 1 while true do local name = debug.getlocal(3, i) if not name then break end i = i + 1 end i = i - 1 local written_vars = {} while i > 0 do local name = debug.getlocal(3, i) if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setlocal(3, i, rawget(vars, name)) end written_vars[name] = true end i = i - 1 end i = 1 local func = debug.getinfo(3, "f").func while true do local name = debug.getupvalue(func, i) if not name then break end if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setupvalue(func, i, rawget(vars, name)) end written_vars[name] = true end i = i + 1 end end local function capture_vars(level, thread) level = (level or 0)+2 -- add two levels for this and debug calls local func = (thread and debug.getinfo(thread, level, "f") or debug.getinfo(level, "f") or {}).func if not func then return {} end local vars = {['...'] = {}} local i = 1 while true do local name, value = debug.getupvalue(func, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end i = 1 while true do local name, value if thread then name, value = debug.getlocal(thread, level, i) else name, value = debug.getlocal(level, i) end if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end -- get varargs (these use negative indices) i = 1 while true do local name, value if thread then name, value = debug.getlocal(thread, level, -i) else name, value = debug.getlocal(level, -i) end -- `not name` should be enough, but LuaJIT 2.0.0 incorrectly reports `(*temporary)` names here if not name or name ~= "(*vararg)" then break end vars['...'][i] = value i = i + 1 end -- returned 'vars' table plays a dual role: (1) it captures local values -- and upvalues to be restored later (in case they are modified in "eval"), -- and (2) it provides an environment for evaluated chunks. -- getfenv(func) is needed to provide proper environment for functions, -- including access to globals, but this causes vars[name] to fail in -- restore_vars on local variables or upvalues with `nil` values when -- 'strict' is in effect. To avoid this `rawget` is used in restore_vars. setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) return vars end local function stack_depth(start_depth) for i = start_depth, 0, -1 do if debug.getinfo(i, "l") then return i+1 end end return start_depth end local function is_safe(stack_level) -- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function if stack_level == 3 then return true end for i = 3, stack_level do -- return if it is not safe to abort local info = debug.getinfo(i, "S") if not info then return true end if info.what == "C" then return false end end return true end local function in_debugger() local this = debug.getinfo(1, "S").source -- only need to check few frames as mobdebug frames should be close for i = 3, 7 do local info = debug.getinfo(i, "S") if not info then return false end if info.source == this then return true end end return false end local function is_pending(peer) -- if there is something already in the buffer, skip check if not buf and checkcount >= mobdebug.checkcount then peer:settimeout(0) -- non-blocking buf = peer:receive(1) peer:settimeout() -- back to blocking checkcount = 0 end return buf end local function readnext(peer, num) peer:settimeout(0) -- non-blocking local res, err, partial = peer:receive(num) peer:settimeout() -- back to blocking return res or partial or '', err end local function handle_breakpoint(peer) -- check if the buffer has the beginning of SETB/DELB command; -- this is to avoid reading the entire line for commands that -- don't need to be handled here. if not buf or not (buf:sub(1,1) == 'S' or buf:sub(1,1) == 'D') then return end -- check second character to avoid reading STEP or other S* and D* commands if #buf == 1 then buf = buf .. readnext(peer, 1) end if buf:sub(2,2) ~= 'E' then return end -- need to read few more characters buf = buf .. readnext(peer, 5-#buf) if buf ~= 'SETB ' and buf ~= 'DELB ' then return end local res, _, partial = peer:receive() -- get the rest of the line; blocking if not res then if partial then buf = buf .. partial end return end local _, _, cmd, file, line = (buf..res):find("^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if cmd == 'SETB' then set_breakpoint(file, tonumber(line)) elseif cmd == 'DELB' then remove_breakpoint(file, tonumber(line)) else -- this looks like a breakpoint command, but something went wrong; -- return here to let the "normal" processing to handle, -- although this is likely to not go well. return end buf = nil end local function normalize_path(file) local n repeat file, n = file:gsub("/+%.?/+","/") -- remove all `//` and `/./` references until n == 0 -- collapse all up-dir references: this will clobber UNC prefix (\\?\) -- and disk on Windows when there are too many up-dir references: `D:\foo\..\..\bar`; -- handle the case of multiple up-dir references: `foo/bar/baz/../../../more`; -- only remove one at a time as otherwise `../../` could be removed; repeat file, n = file:gsub("[^/]+/%.%./", "", 1) until n == 0 -- there may still be a leading up-dir reference left (as `/../` or `../`); remove it return (file:gsub("^(/?)%.%./", "%1")) end local function debug_hook(event, line) -- (1) LuaJIT needs special treatment. Because debug_hook is set for -- *all* coroutines, and not just the one being debugged as in regular Lua -- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html), -- need to avoid debugging mobdebug's own code as LuaJIT doesn't -- always correctly generate call/return hook events (there are more -- calls than returns, which breaks stack depth calculation and -- 'step' and 'step over' commands stop working; possibly because -- 'tail return' events are not generated by LuaJIT). -- the next line checks if the debugger is run under LuaJIT and if -- one of debugger methods is present in the stack, it simply returns. if jit then -- when luajit is compiled with LUAJIT_ENABLE_LUA52COMPAT, -- coroutine.running() returns non-nil for the main thread. local coro, main = coroutine.running() if not coro or main then coro = 'main' end local disabled = coroutines[coro] == false or coroutines[coro] == nil and coro ~= (coro_debugee or 'main') if coro_debugee and disabled or not coro_debugee and (disabled or in_debugger()) then return end end -- (2) check if abort has been requested and it's safe to abort if abort and is_safe(stack_level) then error(abort) end -- (3) also check if this debug hook has not been visited for any reason. -- this check is needed to avoid stepping in too early -- (for example, when coroutine.resume() is executed inside start()). if not seen_hook and in_debugger() then return end if event == "call" then stack_level = stack_level + 1 elseif event == "return" or event == "tail return" then stack_level = stack_level - 1 elseif event == "line" then if mobdebug.linemap then local ok, mappedline = pcall(mobdebug.linemap, line, debug.getinfo(2, "S").source) if ok then line = mappedline end if not line then return end end -- may need to fall through because of the following: -- (1) step_into -- (2) step_over and stack_level <= step_level (need stack_level) -- (3) breakpoint; check for line first as it's known; then for file -- (4) socket call (only do every Xth check) -- (5) at least one watch is registered if not ( step_into or step_over or breakpoints[line] or watchescnt > 0 or is_pending(server) ) then checkcount = checkcount + 1; return end checkcount = mobdebug.checkcount -- force check on the next command -- this is needed to check if the stack got shorter or longer. -- unfortunately counting call/return calls is not reliable. -- the discrepancy may happen when "pcall(load, '')" call is made -- or when "error()" is called in a function. -- in either case there are more "call" than "return" events reported. -- this validation is done for every "line" event, but should be "cheap" -- as it checks for the stack to get shorter (or longer by one call). -- start from one level higher just in case we need to grow the stack. -- this may happen after coroutine.resume call to a function that doesn't -- have any other instructions to execute. it triggers three returns: -- "return, tail return, return", which needs to be accounted for. stack_level = stack_depth(stack_level+1) local caller = debug.getinfo(2, "S") -- grab the filename and fix it if needed local file = lastfile if (lastsource ~= caller.source) then file, lastsource = caller.source, caller.source -- technically, users can supply names that may not use '@', -- for example when they call loadstring('...', 'filename.lua'). -- Unfortunately, there is no reliable/quick way to figure out -- what is the filename and what is the source code. -- If the name doesn't start with `@`, assume it's a file name if it's all on one line. if find(file, "^@") or not find(file, "[\r\n]") then file = gsub(gsub(file, "^@", ""), "\\", "/") -- normalize paths that may include up-dir or same-dir references -- if the path starts from the up-dir or reference, -- prepend `basedir` to generate absolute path to keep breakpoints working. -- ignore qualified relative path (`D:../`) and UNC paths (`\\?\`) if find(file, "^%.%./") then file = basedir..file end if find(file, "/%.%.?/") then file = normalize_path(file) end -- need this conversion to be applied to relative and absolute -- file names as you may write "require 'Foo'" to -- load "foo.lua" (on a case insensitive file system) and breakpoints -- set on foo.lua will not work if not converted to the same case. if iscasepreserving then file = string.lower(file) end if find(file, "^%./") then file = sub(file, 3) else file = gsub(file, "^"..q(basedir), "") end -- some file systems allow newlines in file names; remove these. file = gsub(file, "\n", ' ') else file = mobdebug.line(file) end -- set to true if we got here; this only needs to be done once per -- session, so do it here to at least avoid setting it for every line. seen_hook = true lastfile = file end if is_pending(server) then handle_breakpoint(server) end local vars, status, res if (watchescnt > 0) then vars = capture_vars(1) for index, value in pairs(watches) do setfenv(value, vars) local ok, fired = pcall(value) if ok and fired then status, res = cororesume(coro_debugger, events.WATCH, vars, file, line, index) break -- any one watch is enough; don't check multiple times end end end -- need to get into the "regular" debug handler, but only if there was -- no watch that was fired. If there was a watch, handle its result. local getin = (status == nil) and (step_into -- when coroutine.running() return `nil` (main thread in Lua 5.1), -- step_over will equal 'main', so need to check for that explicitly. or (step_over and step_over == (coroutine.running() or 'main') and stack_level <= step_level) or has_breakpoint(file, line) or is_pending(server)) if getin then vars = vars or capture_vars(1) step_into = false step_over = false status, res = cororesume(coro_debugger, events.BREAK, vars, file, line) end -- handle 'stack' command that provides stack() information to the debugger while status and res == 'stack' do -- resume with the stack trace and variables if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values status, res = cororesume(coro_debugger, events.STACK, stack(3), file, line) end -- need to recheck once more as resume after 'stack' command may -- return something else (for example, 'exit'), which needs to be handled if status and res and res ~= 'stack' then if not abort and res == "exit" then mobdebug.onexit(1, true); return end if not abort and res == "done" then mobdebug.done(); return end abort = res -- only abort if safe; if not, there is another (earlier) check inside -- debug_hook, which will abort execution at the first safe opportunity if is_safe(stack_level) then error(abort) end elseif not status and res then error(res, 2) -- report any other (internal) errors back to the application end if vars then restore_vars(vars) end -- last command requested Step Over/Out; store the current thread if step_over == true then step_over = coroutine.running() or 'main' end end end local function stringify_results(params, status, ...) if not status then return status, ... end -- on error report as it params = params or {} if params.nocode == nil then params.nocode = true end if params.comment == nil then params.comment = 1 end local t = {...} for i,v in pairs(t) do -- stringify each of the returned values local ok, res = pcall(mobdebug.line, v, params) t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026") end -- stringify table with all returned values -- this is done to allow each returned value to be used (serialized or not) -- intependently and to preserve "original" comments return pcall(mobdebug.dump, t, {sparse = false}) end local function isrunning() return coro_debugger and (corostatus(coro_debugger) == 'suspended' or corostatus(coro_debugger) == 'running') end -- this is a function that removes all hooks and closes the socket to -- report back to the controller that the debugging is done. -- the script that called `done` can still continue. local function done() if not (isrunning() and server) then return end if not jit then for co, debugged in pairs(coroutines) do if debugged then debug.sethook(co) end end end debug.sethook() server:close() coro_debugger = nil -- to make sure isrunning() returns `false` seen_hook = nil -- to make sure that the next start() call works abort = nil -- to make sure that callback calls use proper "abort" value end local function debugger_loop(sev, svars, sfile, sline) local command local app, osname local eval_env = svars or {} local function emptyWatch () return false end local loaded = {} for k in pairs(package.loaded) do loaded[k] = true end while true do local line, err local wx = rawget(genv, "wx") -- use rawread to make strict.lua happy if (wx or mobdebug.yield) and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end while true do line, err = server:receive() if not line and err == "timeout" then -- yield for wx GUI applications if possible to avoid "busyness" app = app or (wx and wx.wxGetApp and wx.wxGetApp()) if app then local win = app:GetTopWindow() local inloop = app:IsMainLoopRunning() osname = osname or wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName() if win and not inloop then -- process messages in a regular way -- and exit as soon as the event loop is idle if osname == 'Unix' then wx.wxTimer(app):Start(10, true) end local exitLoop = function() win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_IDLE) win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_TIMER) app:ExitMainLoop() end win:Connect(wx.wxEVT_IDLE, exitLoop) win:Connect(wx.wxEVT_TIMER, exitLoop) app:MainLoop() end elseif mobdebug.yield then mobdebug.yield() end elseif not line and err == "closed" then error("Debugger connection closed", 0) else -- if there is something in the pending buffer, prepend it to the line if buf then line = buf .. line; buf = nil end break end end if server.settimeout then server:settimeout() end -- back to blocking command = string.sub(line, string.find(line, "^[A-Z]+")) if command == "SETB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then set_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "DELB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then remove_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXEC" then -- extract any optional parameters local params = string.match(line, "--%s*(%b{})%s*$") local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") if chunk then local func, res = mobdebug.loadstring(chunk) local status if func then local pfunc = params and loadstring("return "..params) -- use internal function params = pfunc and pfunc() params = (type(params) == "table" and params or {}) local stack = tonumber(params.stack) -- if the requested stack frame is not the current one, then use a new capture -- with a specific stack frame: `capture_vars(0, coro_debugee)` local env = stack and coro_debugee and capture_vars(stack-1, coro_debugee) or eval_env setfenv(func, env) status, res = stringify_results(params, pcall(func, unpack(env['...'] or {}))) end if status then if mobdebug.onscratch then mobdebug.onscratch(res) end server:send("200 OK " .. tostring(#res) .. "\n") server:send(res) else -- fix error if not set (for example, when loadstring is not present) if not res then res = "Unknown error" end server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "LOAD" then local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$") size = tonumber(size) if abort == nil then -- no LOAD/RELOAD allowed inside start() if size > 0 then server:receive(size) end if sfile and sline then server:send("201 Started " .. sfile .. " " .. tostring(sline) .. "\n") else server:send("200 OK 0\n") end else -- reset environment to allow required modules to load again -- remove those packages that weren't loaded when debugger started for k in pairs(package.loaded) do if not loaded[k] then package.loaded[k] = nil end end if size == 0 and name == '-' then -- RELOAD the current script being debugged server:send("200 OK 0\n") coroyield("load") else -- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading local chunk = size == 0 and "" or server:receive(size) if chunk then -- LOAD a new script for debugging local func, res = mobdebug.loadstring(chunk, "@"..name) if func then server:send("200 OK 0\n") debugee = func coroyield("load") else server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end end end elseif command == "SETW" then local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$") if exp then local func, res = mobdebug.loadstring("return(" .. exp .. ")") if func then watchescnt = watchescnt + 1 local newidx = #watches + 1 watches[newidx] = func server:send("200 OK " .. tostring(newidx) .. "\n") else server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "DELW" then local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$") index = tonumber(index) if index > 0 and index <= #watches then watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0) watches[index] = emptyWatch server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "RUN" then server:send("200 OK\n") local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "STEP" then server:send("200 OK\n") step_into = true local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "OVER" or command == "OUT" then server:send("200 OK\n") step_over = true -- OVER and OUT are very similar except for -- the stack level value at which to stop if command == "OUT" then step_level = stack_level - 1 else step_level = stack_level end local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "BASEDIR" then local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$") if dir then basedir = iscasepreserving and string.lower(dir) or dir -- reset cached source as it may change with basedir lastsource = nil server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "SUSPEND" then -- do nothing; it already fulfilled its role elseif command == "DONE" then coroyield("done") return -- done with all the debugging elseif command == "STACK" then -- first check if we can execute the stack command -- as it requires yielding back to debug_hook it cannot be executed -- if we have not seen the hook yet as happens after start(). -- in this case we simply return an empty result local vars, ev = {} if seen_hook then ev, vars = coroyield("stack") end if ev and ev ~= events.STACK then server:send("401 Error in Execution " .. tostring(#vars) .. "\n") server:send(vars) else local params = string.match(line, "--%s*(%b{})%s*$") local pfunc = params and loadstring("return "..params) -- use internal function params = pfunc and pfunc() params = (type(params) == "table" and params or {}) if params.nocode == nil then params.nocode = true end if params.sparse == nil then params.sparse = false end -- take into account additional levels for the stack frames and data management if tonumber(params.maxlevel) then params.maxlevel = tonumber(params.maxlevel)+4 end local ok, res = pcall(mobdebug.dump, vars, params) if ok then server:send("200 OK " .. tostring(res) .. "\n") else server:send("401 Error in Execution " .. tostring(#res) .. "\n") server:send(res) end end elseif command == "OUTPUT" then local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode and stream == "stdout" then -- assign "print" in the global environment local default = mode == 'd' genv.print = default and iobase.print or corowrap(function() -- wrapping into coroutine.wrap protects this function from -- being stepped through in the debugger. -- don't use vararg (...) as it adds a reference for its values, -- which may affect how they are garbage collected while true do local tbl = {coroutine.yield()} if mode == 'c' then iobase.print(unpack(tbl)) end for n = 1, #tbl do tbl[n] = select(2, pcall(mobdebug.line, tbl[n], {nocode = true, comment = false})) end local file = table.concat(tbl, "\t").."\n" server:send("204 Output " .. stream .. " " .. tostring(#file) .. "\n" .. file) end end) if not default then genv.print() end -- "fake" print to start printing loop server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXIT" then server:send("200 OK\n") coroyield("exit") else server:send("400 Bad Request\n") end end end local function output(stream, data) if server then return server:send("204 Output "..stream.." "..tostring(#data).."\n"..data) end end local function connect(controller_host, controller_port) local sock, err = socket.tcp() if not sock then return nil, err end if sock.settimeout then sock:settimeout(mobdebug.connecttimeout) end local res, err = sock:connect(controller_host, tostring(controller_port)) if sock.settimeout then sock:settimeout() end if not res then return nil, err end return sock end local lasthost, lastport -- Starts a debug session by connecting to a controller local function start(controller_host, controller_port) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local err server, err = mobdebug.connect(controller_host, controller_port) if server then -- correct stack depth which already has some calls on it -- so it doesn't go into negative when those calls return -- as this breaks subsequence checks in stack_depth(). -- start from 16th frame, which is sufficiently large for this check. stack_level = stack_depth(16) -- provide our own traceback function to report errors remotely -- but only under Lua 5.1/LuaJIT as it's not called under Lua 5.2+ -- (http://lua-users.org/lists/lua-l/2016-05/msg00297.html) local function f() return function()end end if f() ~= f() then -- Lua 5.1 or LuaJIT local dtraceback = debug.traceback debug.traceback = function (...) if select('#', ...) >= 1 then local thr, err, lvl = ... if type(thr) ~= 'thread' then err, lvl = thr, err end local trace = dtraceback(err, (lvl or 1)+1) if genv.print == iobase.print then -- no remote redirect return trace else genv.print(trace) -- report the error remotely return -- don't report locally to avoid double reporting end end -- direct call to debug.traceback: return the original. -- debug.traceback(nil, level) doesn't work in Lua 5.1 -- (http://lua-users.org/lists/lua-l/2011-06/msg00574.html), so -- simply remove first frame from the stack trace local tb = dtraceback("", 2) -- skip debugger frames -- if the string is returned, then remove the first new line as it's not needed return type(tb) == "string" and tb:gsub("^\n","") or tb end end coro_debugger = corocreate(debugger_loop) debug.sethook(debug_hook, HOOKMASK) seen_hook = nil -- reset in case the last start() call was refused step_into = true -- start with step command return true else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) end end local function controller(controller_host, controller_port, scratchpad) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local exitonerror = not scratchpad local err server, err = mobdebug.connect(controller_host, controller_port) if server then local function report(trace, err) local msg = err .. "\n" .. trace server:send("401 Error in Execution " .. tostring(#msg) .. "\n") server:send(msg) return err end seen_hook = true -- allow to accept all commands coro_debugger = corocreate(debugger_loop) while true do step_into = true -- start with step command abort = false -- reset abort flag from the previous loop if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away coro_debugee = corocreate(debugee) debug.sethook(coro_debugee, debug_hook, HOOKMASK) local status, err = cororesume(coro_debugee, unpack(arg or {})) -- was there an error or is the script done? -- 'abort' state is allowed here; ignore it if abort then if tostring(abort) == 'exit' then break end else if status then -- no errors if corostatus(coro_debugee) == "suspended" then -- the script called `coroutine.yield` in the "main" thread error("attempt to yield from the main thread", 3) end break -- normal execution is done elseif err and not string.find(tostring(err), deferror) then -- report the error back -- err is not necessarily a string, so convert to string to report report(debug.traceback(coro_debugee), tostring(err)) if exitonerror then break end -- check if the debugging is done (coro_debugger is nil) if not coro_debugger then break end -- resume once more to clear the response the debugger wants to send -- need to use capture_vars(0) to capture only two (default) level, -- as even though there is controller() call, because of the tail call, -- the caller may not exist for it; -- This is not entirely safe as the user may see the local -- variable from console, but they will be reset anyway. -- This functionality is used when scratchpad is paused to -- gain access to remote console to modify global variables. local status, err = cororesume(coro_debugger, events.RESTART, capture_vars(0)) if not status or status and err == "exit" then break end end end end else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) return false end return true end local function scratchpad(controller_host, controller_port) return controller(controller_host, controller_port, true) end local function loop(controller_host, controller_port) return controller(controller_host, controller_port, false) end local function on() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end if co then coroutines[co] = true debug.sethook(co, debug_hook, HOOKMASK) else if jit then coroutines.main = true end debug.sethook(debug_hook, HOOKMASK) end end local function off() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end -- don't remove coroutine hook under LuaJIT as there is only one (global) hook if co then coroutines[co] = false if not jit then debug.sethook(co) end else if jit then coroutines.main = false end if not jit then debug.sethook() end end -- check if there is any thread that is still being debugged under LuaJIT; -- if not, turn the debugging off if jit then local remove = true for _, debugged in pairs(coroutines) do if debugged then remove = false; break end end if remove then debug.sethook() end end end -- Handles server debugging commands local function handle(params, client, options) -- when `options.verbose` is not provided, use normal `print`; verbose output can be -- disabled (`options.verbose == false`) or redirected (`options.verbose == function()...end`) local verbose = not options or options.verbose ~= nil and options.verbose local print = verbose and (type(verbose) == "function" and verbose or print) or function() end local file, line, watch_idx local _, _, command = string.find(params, "^([a-z]+)") if command == "run" or command == "step" or command == "out" or command == "over" or command == "exit" then client:send(string.upper(command) .. "\n") client:receive() -- this should consume the first '200 OK' response while true do local done = true local breakpoint = client:receive() if not breakpoint then print("Program finished") return nil, nil, false end local _, _, status = string.find(breakpoint, "^(%d+)") if status == "200" then -- don't need to do anything elseif status == "202" then _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file .. " line " .. line) end elseif status == "203" then _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$") if file and line and watch_idx then print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])") end elseif status == "204" then local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$") if stream and size then local size = tonumber(size) local msg = size > 0 and client:receive(size) or "" print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") if size then local msg = client:receive(tonumber(size)) print("Error in remote application: " .. msg) return nil, nil, msg end else print("Unknown error") return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'" end if done then break end end elseif command == "done" then client:send(string.upper(command) .. "\n") -- no response is expected elseif command == "setb" or command == "asetb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("SETB " .. file .. " " .. line .. "\n") if command == "asetb" or client:receive() == "200 OK" then set_breakpoint(file, line) else print("Error: breakpoint not inserted") end else print("Invalid command") end elseif command == "setw" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp then client:send("SETW " .. exp .. "\n") local answer = client:receive() local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$") if watch_idx then watches[watch_idx] = exp print("Inserted watch exp no. " .. watch_idx) else local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$") if size then local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","") print("Error: watch expression not set: " .. err) else print("Error: watch expression not set") end end else print("Invalid command") end elseif command == "delb" or command == "adelb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("DELB " .. file .. " " .. line .. "\n") if command == "adelb" or client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: breakpoint not removed") end else print("Invalid command") end elseif command == "delallb" then local file, line = "*", 0 client:send("DELB " .. file .. " " .. tostring(line) .. "\n") if client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: all breakpoints not removed") end elseif command == "delw" then local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$") if index then client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression not removed") end else print("Invalid command") end elseif command == "delallw" then for index, exp in pairs(watches) do client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed") end end elseif command == "eval" or command == "exec" or command == "load" or command == "loadstring" or command == "reload" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp or (command == "reload") then if command == "eval" or command == "exec" then exp = (exp:gsub("%-%-%[(=*)%[.-%]%1%]", "") -- remove comments :gsub("%-%-.-\n", " ") -- remove line comments :gsub("\n", " ")) -- convert new lines if command == "eval" then exp = "return " .. exp end client:send("EXEC " .. exp .. "\n") elseif command == "reload" then client:send("LOAD 0 -\n") elseif command == "loadstring" then local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s(.+)") if not file then _, _, file, lines = string.find(exp, "^(%S+)%s(.+)") end client:send("LOAD " .. tostring(#lines) .. " " .. file .. "\n") client:send(lines) else local file = io.open(exp, "r") if not file and pcall(require, "winapi") then -- if file is not open and winapi is there, try with a short path; -- this may be needed for unicode paths on windows winapi.set_encoding(winapi.CP_UTF8) local shortp = winapi.short_path(exp) file = shortp and io.open(shortp, "r") end if not file then return nil, nil, "Cannot open file " .. exp end -- read the file and remove the shebang line as it causes a compilation error local lines = file:read("*all"):gsub("^#!.-\n", "\n") file:close() local file = string.gsub(exp, "\\", "/") -- convert slash file = removebasedir(file, basedir) client:send("LOAD " .. tostring(#lines) .. " " .. file .. "\n") if #lines > 0 then client:send(lines) end end while true do local params, err = client:receive() if not params then return nil, nil, "Debugger connection " .. (err or "error") end local done = true local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$") if status == "200" then len = tonumber(len) if len > 0 then local status, res local str = client:receive(len) -- handle serialized table with results local func, err = loadstring(str) if func then status, res = pcall(func) if not status then err = res elseif type(res) ~= "table" then err = "received "..type(res).." instead of expected 'table'" end end if err then print("Error in processing results: " .. err) return nil, nil, "Error in processing results: " .. err end print(unpack(res)) return res[1], res end elseif status == "201" then _, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$") elseif status == "202" or params == "200 OK" then -- do nothing; this only happens when RE/LOAD command gets the response -- that was for the original command that was aborted elseif status == "204" then local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$") if stream and size then local size = tonumber(size) local msg = size > 0 and client:receive(size) or "" print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then len = tonumber(len) local res = client:receive(len) print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'" end if done then break end end else print("Invalid command") end elseif command == "listb" then for l, v in pairs(breakpoints) do for f in pairs(v) do print(f .. ": " .. l) end end elseif command == "listw" then for i, v in pairs(watches) do print("Watch exp. " .. i .. ": " .. v) end elseif command == "suspend" then client:send("SUSPEND\n") elseif command == "stack" then local opts = string.match(params, "^[a-z]+%s+(.+)$") client:send("STACK" .. (opts and " "..opts or "") .."\n") local resp = client:receive() local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$") if status == "200" then local func, err = loadstring(res) if func == nil then print("Error in stack information: " .. err) return nil, nil, err end local ok, stack = pcall(func) if not ok then print("Error in stack information: " .. stack) return nil, nil, stack end for _,frame in ipairs(stack) do print(mobdebug.line(frame[1], {comment = false})) end return stack elseif status == "401" then local _, _, len = string.find(resp, "%s+(%d+)%s*$") len = tonumber(len) local res = len > 0 and client:receive(len) or "Invalid stack information." print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after STACK" end elseif command == "output" then local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode then client:send("OUTPUT "..stream.." "..mode.."\n") local resp, err = client:receive() if not resp then print("Unknown error: "..err) return nil, nil, "Debugger connection error: "..err end local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("Stream "..stream.." redirected") outputs[stream] = type(options) == 'table' and options.handler or nil -- the client knows when she is doing, so install the handler elseif type(options) == 'table' and options.handler then outputs[stream] = options.handler else print("Unknown error") return nil, nil, "Debugger error: can't redirect "..stream end else print("Invalid command") end elseif command == "basedir" then local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$") if dir then dir = string.gsub(dir, "\\", "/") -- convert slash if not string.find(dir, "/$") then dir = dir .. "/" end local remdir = dir:match("\t(.+)") if remdir then dir = dir:gsub("/?\t.+", "/") end basedir = dir client:send("BASEDIR "..(remdir or dir).."\n") local resp, err = client:receive() if not resp then print("Unknown error: "..err) return nil, nil, "Debugger connection error: "..err end local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("New base directory is " .. basedir) else print("Unknown error") return nil, nil, "Debugger error: unexpected response after BASEDIR" end else print(basedir) end elseif command == "help" then print("setb <file> <line> -- sets a breakpoint") print("delb <file> <line> -- removes a breakpoint") print("delallb -- removes all breakpoints") print("setw <exp> -- adds a new watch expression") print("delw <index> -- removes the watch expression at index") print("delallw -- removes all watch expressions") print("run -- runs until next breakpoint") print("step -- runs until next line, stepping into function calls") print("over -- runs until next line, stepping over function calls") print("out -- runs until line after returning from current function") print("listb -- lists breakpoints") print("listw -- lists watch expressions") print("eval <exp> -- evaluates expression on the current context and returns its value") print("exec <stmt> -- executes statement on the current context") print("load <file> -- loads a local file for debugging") print("reload -- restarts the current debugging session") print("stack -- reports stack trace") print("output stdout <d|c|r> -- capture and redirect io stream (default|copy|redirect)") print("basedir [<path>] -- sets the base path of the remote application, or shows the current one") print("done -- stops the debugger and continues application execution") print("exit -- exits debugger and the application") else local _, _, spaces = string.find(params, "^(%s*)$") if spaces then return nil, nil, "Empty command" else print("Invalid command") return nil, nil, "Invalid command" end end return file, line end -- Starts debugging server local function listen(host, port) host = host or "*" port = port or mobdebug.port local socket = require "socket" print("Lua Remote Debugger") print("Run the program you wish to debug") local server = socket.bind(host, port) local client = server:accept() client:send("STEP\n") client:receive() local breakpoint = client:receive() local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file ) print("Type 'help' for commands") else local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$") if size then print("Error in remote application: ") print(client:receive(size)) end end while true do io.write("> ") local file, line, err = handle(io.read("*line"), client) if not file and err == false then break end -- completed debugging end client:close() end local cocreate local function coro() if cocreate then return end -- only set once cocreate = cocreate or coroutine.create coroutine.create = function(f, ...) return cocreate(function(...) mobdebug.on() return f(...) end, ...) end end local moconew local function moai() if moconew then return end -- only set once moconew = moconew or (MOAICoroutine and MOAICoroutine.new) if not moconew then return end MOAICoroutine.new = function(...) local thread = moconew(...) -- need to support both thread.run and getmetatable(thread).run, which -- was used in earlier MOAI versions local mt = thread.run and thread or getmetatable(thread) local patched = mt.run mt.run = function(self, f, ...) return patched(self, function(...) mobdebug.on() return f(...) end, ...) end return thread end end -- make public functions available mobdebug.setbreakpoint = set_breakpoint mobdebug.removebreakpoint = remove_breakpoint mobdebug.listen = listen mobdebug.loop = loop mobdebug.scratchpad = scratchpad mobdebug.handle = handle mobdebug.connect = connect mobdebug.start = start mobdebug.on = on mobdebug.off = off mobdebug.moai = moai mobdebug.coro = coro mobdebug.done = done mobdebug.pause = function() step_into = true end mobdebug.yield = nil -- callback mobdebug.output = output mobdebug.onexit = os and os.exit or done mobdebug.onscratch = nil -- callback mobdebug.basedir = function(b) if b then basedir = b end return basedir end return mobdebug
bsd-3-clause
tdubourg/geobombing
mobileapp/corona/utils.lua
1
3441
local json = require "json" local socket = require "socket" -- table.indexOf( array, object ) returns the index -- of object in array. Returns 'nil' if not in array. table.indexOf = function( t, object ) local result if "table" == type( t ) then for i=1,#t do if object == t[i] then result = i break end end end return result end -- return a new array containing the concatenation of all of its -- parameters. Scaler parameters are included in place, and array -- parameters have their values shallow-copied to the final array. -- Note that userdata and function values are treated as scalar. function array_concat(...) local t = {} for n = 1,select("#",...) do local arg = select(n,...) if type(arg)=="table" then for _,v in ipairs(arg) do t[#t+1] = v end else t[#t+1] = arg end end return t end -- local last_print = 0 -- _G.print = function ( ... ) -- if (now() - last_print < 3000) then -- return -- end -- last_print = now() -- io.write( "Utiliser la fonction print tue des chatons, je vais utiliser dbg(const, {arg1, arg2, arg3} a la place.\n") -- io.write( "Ce message ne s'affiche qu'une fois par 3 secondes.\n") -- end function array_insert(receivingArray, insertedArray) for _,v in ipairs(insertedArray) do receivingArray[#receivingArray+1] = v end return receivingArray end function silent_fail_require(module_name) local function requiref(module_name) require(module_name) end local res = pcall(requiref,module_name) return res end function dbg( mode, things ) if (mode) then dbg_write(now(), "\t") for _,v in pairs(things) do if (type(v) == "table") then v = json.encode(v) else v = tostring(v) end dbg_write(v, "\t") end dbg_write("\n") end end local dbg_file = nil function dbg_write( ... ) if(LOG_TO_FILE) then if (dbg_file == nil) then local path = system.pathForFile(LOG_TO_FILE, system.DocumentsDirectory ) io.write( "path\t", tostring(path), "\n") dbg_file = io.open( path, "w" ) io.write( "dbg_file==nil\t", tostring(dbg_file==nil), "\n") end dbg_file:write( ... ) else io.write( ... ) end end local colors = { [1] = {255,0,0}, [2] = {0,255,0}, [3] = {0,0,255}, [4] = {255,0,195}, [5] = {162,0,255}, [6] = {0,221,255}, [7] = {234,255,0}, [8] = {255,149,0}, [9] = {255,255,255}, [10] = {0,0,0}, } function idToColor(pid) -- old method based on random + seeding ----------------------------------------------- -- math.randomseed(pid) -- local r = math.random() -- local g = math.random() -- local b = math.random() -- math.randomseed(os.time()) -- local total = r+g+b -- r = r*255/total -- g = g*255/total -- b = b*255/total ----------------------------------------------- return colors[pid%(#colors)] end -- Returns the timestamp in milliseconds -- That is to say the number of milliseconds since the 01/01/1970 function now() return socket.gettime()*1000 end function fileExists(fileName, base) assert(fileName, "fileName is missing") local base = base or system.ResourceDirectory local filePath = system.pathForFile( fileName, base ) local exists = false if (filePath) then -- file may exist. won't know until you open it local fileHandle = io.open( filePath, "r" ) if (fileHandle) then -- nil if no file found exists = true io.close(fileHandle) end end return(exists) end
lgpl-3.0
backupify/qless
lib/qless/lua/qless.lua
1
70768
-- Current SHA: 20dc687832ad472f0a00899d26c285b893ff466c -- This is a generated file local Qless = { ns = 'ql:' } local QlessQueue = { ns = Qless.ns .. 'q:' } QlessQueue.__index = QlessQueue local QlessWorker = { ns = Qless.ns .. 'w:' } QlessWorker.__index = QlessWorker local QlessJob = { ns = Qless.ns .. 'j:' } QlessJob.__index = QlessJob local QlessThrottle = { ns = Qless.ns .. 'th:' } QlessThrottle.__index = QlessThrottle local QlessRecurringJob = {} QlessRecurringJob.__index = QlessRecurringJob Qless.config = {} function table.extend(self, other) for i, v in ipairs(other) do table.insert(self, v) end end function Qless.publish(channel, message) redis.call('publish', Qless.ns .. channel, message) end function Qless.job(jid) assert(jid, 'Job(): no jid provided') local job = {} setmetatable(job, QlessJob) job.jid = jid return job end function Qless.recurring(jid) assert(jid, 'Recurring(): no jid provided') local job = {} setmetatable(job, QlessRecurringJob) job.jid = jid return job end function Qless.throttle(tid) assert(tid, 'Throttle(): no tid provided') local throttle = QlessThrottle.data({id = tid}) setmetatable(throttle, QlessThrottle) throttle.locks = { length = function() return (redis.call('zcard', QlessThrottle.ns .. tid .. '-locks') or 0) end, members = function() return redis.call('zrange', QlessThrottle.ns .. tid .. '-locks', 0, -1) end, add = function(...) if #arg > 0 then redis.call('zadd', QlessThrottle.ns .. tid .. '-locks', unpack(arg)) end end, remove = function(...) if #arg > 0 then return redis.call('zrem', QlessThrottle.ns .. tid .. '-locks', unpack(arg)) end end, pop = function(min, max) return redis.call('zremrangebyrank', QlessThrottle.ns .. tid .. '-locks', min, max) end, peek = function(min, max) return redis.call('zrange', QlessThrottle.ns .. tid .. '-locks', min, max) end } throttle.pending = { length = function() return (redis.call('zcard', QlessThrottle.ns .. tid .. '-pending') or 0) end, members = function() return redis.call('zrange', QlessThrottle.ns .. tid .. '-pending', 0, -1) end, add = function(now, jid) redis.call('zadd', QlessThrottle.ns .. tid .. '-pending', now, jid) end, remove = function(...) if #arg > 0 then return redis.call('zrem', QlessThrottle.ns .. tid .. '-pending', unpack(arg)) end end, pop = function(min, max) return redis.call('zremrangebyrank', QlessThrottle.ns .. tid .. '-pending', min, max) end, peek = function(min, max) return redis.call('zrange', QlessThrottle.ns .. tid .. '-pending', min, max) end } return throttle end function Qless.failed(group, start, limit) start = assert(tonumber(start or 0), 'Failed(): Arg "start" is not a number: ' .. (start or 'nil')) limit = assert(tonumber(limit or 25), 'Failed(): Arg "limit" is not a number: ' .. (limit or 'nil')) if group then return { total = redis.call('llen', 'ql:f:' .. group), jobs = redis.call('lrange', 'ql:f:' .. group, start, start + limit - 1) } else local response = {} local groups = redis.call('smembers', 'ql:failures') for index, group in ipairs(groups) do response[group] = redis.call('llen', 'ql:f:' .. group) end return response end end function Qless.jobs(now, state, ...) assert(state, 'Jobs(): Arg "state" missing') if state == 'complete' then local offset = assert(tonumber(arg[1] or 0), 'Jobs(): Arg "offset" not a number: ' .. tostring(arg[1])) local count = assert(tonumber(arg[2] or 25), 'Jobs(): Arg "count" not a number: ' .. tostring(arg[2])) return redis.call('zrevrange', 'ql:completed', offset, offset + count - 1) else local name = assert(arg[1], 'Jobs(): Arg "queue" missing') local offset = assert(tonumber(arg[2] or 0), 'Jobs(): Arg "offset" not a number: ' .. tostring(arg[2])) local count = assert(tonumber(arg[3] or 25), 'Jobs(): Arg "count" not a number: ' .. tostring(arg[3])) local queue = Qless.queue(name) if state == 'running' then return queue.locks.peek(now, offset, count) elseif state == 'stalled' then return queue.locks.expired(now, offset, count) elseif state == 'throttled' then return queue.throttled.peek(now, offset, count) elseif state == 'scheduled' then queue:check_scheduled(now, queue.scheduled.length()) return queue.scheduled.peek(now, offset, count) elseif state == 'depends' then return queue.depends.peek(now, offset, count) elseif state == 'recurring' then return queue.recurring.peek(math.huge, offset, count) else error('Jobs(): Unknown type "' .. state .. '"') end end end function Qless.track(now, command, jid) if command ~= nil then assert(jid, 'Track(): Arg "jid" missing') assert(Qless.job(jid):exists(), 'Track(): Job does not exist') if string.lower(command) == 'track' then Qless.publish('track', jid) return redis.call('zadd', 'ql:tracked', now, jid) elseif string.lower(command) == 'untrack' then Qless.publish('untrack', jid) return redis.call('zrem', 'ql:tracked', jid) else error('Track(): Unknown action "' .. command .. '"') end else local response = { jobs = {}, expired = {} } local jids = redis.call('zrange', 'ql:tracked', 0, -1) for index, jid in ipairs(jids) do local data = Qless.job(jid):data() if data then table.insert(response.jobs, data) else table.insert(response.expired, jid) end end return response end end function Qless.tag(now, command, ...) assert(command, 'Tag(): Arg "command" must be "add", "remove", "get" or "top"') if command == 'add' then local jid = assert(arg[1], 'Tag(): Arg "jid" missing') local tags = redis.call('hget', QlessJob.ns .. jid, 'tags') if tags then tags = cjson.decode(tags) local _tags = {} for i,v in ipairs(tags) do _tags[v] = true end for i=2,#arg do local tag = arg[i] if _tags[tag] == nil then _tags[tag] = true table.insert(tags, tag) end Qless.job(jid):insert_tag(now, tag) end redis.call('hset', QlessJob.ns .. jid, 'tags', cjson.encode(tags)) return tags else error('Tag(): Job ' .. jid .. ' does not exist') end elseif command == 'remove' then local jid = assert(arg[1], 'Tag(): Arg "jid" missing') local tags = redis.call('hget', QlessJob.ns .. jid, 'tags') if tags then tags = cjson.decode(tags) local _tags = {} for i,v in ipairs(tags) do _tags[v] = true end for i=2,#arg do local tag = arg[i] _tags[tag] = nil Qless.job(jid):remove_tag(tag) end local results = {} for i,tag in ipairs(tags) do if _tags[tag] then table.insert(results, tag) end end redis.call('hset', QlessJob.ns .. jid, 'tags', cjson.encode(results)) return results else error('Tag(): Job ' .. jid .. ' does not exist') end elseif command == 'get' then local tag = assert(arg[1], 'Tag(): Arg "tag" missing') local offset = assert(tonumber(arg[2] or 0), 'Tag(): Arg "offset" not a number: ' .. tostring(arg[2])) local count = assert(tonumber(arg[3] or 25), 'Tag(): Arg "count" not a number: ' .. tostring(arg[3])) return { total = redis.call('zcard', 'ql:t:' .. tag), jobs = redis.call('zrange', 'ql:t:' .. tag, offset, offset + count - 1) } elseif command == 'top' then local offset = assert(tonumber(arg[1] or 0) , 'Tag(): Arg "offset" not a number: ' .. tostring(arg[1])) local count = assert(tonumber(arg[2] or 25), 'Tag(): Arg "count" not a number: ' .. tostring(arg[2])) return redis.call('zrevrangebyscore', 'ql:tags', '+inf', 2, 'limit', offset, count) else error('Tag(): First argument must be "add", "remove" or "get"') end end function Qless.cancel(now, ...) local dependents = {} for _, jid in ipairs(arg) do dependents[jid] = redis.call( 'smembers', QlessJob.ns .. jid .. '-dependents') or {} end for i, jid in ipairs(arg) do for j, dep in ipairs(dependents[jid]) do if dependents[dep] == nil then error('Cancel(): ' .. jid .. ' is a dependency of ' .. dep .. ' but is not mentioned to be canceled') end end end for _, jid in ipairs(arg) do local state, queue, failure, worker = unpack(redis.call( 'hmget', QlessJob.ns .. jid, 'state', 'queue', 'failure', 'worker')) if state ~= 'complete' then local encoded = cjson.encode({ jid = jid, worker = worker, event = 'canceled', queue = queue }) Qless.publish('log', encoded) if worker and (worker ~= '') then redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid) Qless.publish('w:' .. worker, encoded) end if queue then local queue = Qless.queue(queue) queue:remove_job(jid) end local job = Qless.job(jid) job:throttles_release(now) for i, j in ipairs(redis.call( 'smembers', QlessJob.ns .. jid .. '-dependencies')) do redis.call('srem', QlessJob.ns .. j .. '-dependents', jid) end if state == 'failed' then failure = cjson.decode(failure) redis.call('lrem', 'ql:f:' .. failure.group, 0, jid) if redis.call('llen', 'ql:f:' .. failure.group) == 0 then redis.call('srem', 'ql:failures', failure.group) end local bin = failure.when - (failure.when % 86400) local failed = redis.call( 'hget', 'ql:s:stats:' .. bin .. ':' .. queue, 'failed') redis.call('hset', 'ql:s:stats:' .. bin .. ':' .. queue, 'failed', failed - 1) end job:delete() if redis.call('zscore', 'ql:tracked', jid) ~= false then Qless.publish('canceled', jid) end end end return arg end Qless.config.defaults = { ['application'] = 'qless', ['heartbeat'] = 60, ['grace-period'] = 10, ['stats-history'] = 30, ['histogram-history'] = 7, ['jobs-history-count'] = 50000, ['jobs-history'] = 604800 } Qless.config.get = function(key, default) if key then return redis.call('hget', 'ql:config', key) or Qless.config.defaults[key] or default else local reply = redis.call('hgetall', 'ql:config') for i = 1, #reply, 2 do Qless.config.defaults[reply[i]] = reply[i + 1] end return Qless.config.defaults end end Qless.config.set = function(option, value) assert(option, 'config.set(): Arg "option" missing') assert(value , 'config.set(): Arg "value" missing') Qless.publish('log', cjson.encode({ event = 'config_set', option = option, value = value })) redis.call('hset', 'ql:config', option, value) end Qless.config.unset = function(option) assert(option, 'config.unset(): Arg "option" missing') Qless.publish('log', cjson.encode({ event = 'config_unset', option = option })) redis.call('hdel', 'ql:config', option) end function QlessJob:data(...) local job = redis.call( 'hmget', QlessJob.ns .. self.jid, 'jid', 'klass', 'state', 'queue', 'worker', 'priority', 'expires', 'retries', 'remaining', 'data', 'tags', 'failure', 'throttles', 'spawned_from_jid') if not job[1] then return nil end local data = { jid = job[1], klass = job[2], state = job[3], queue = job[4], worker = job[5] or '', tracked = redis.call( 'zscore', 'ql:tracked', self.jid) ~= false, priority = tonumber(job[6]), expires = tonumber(job[7]) or 0, retries = tonumber(job[8]), remaining = math.floor(tonumber(job[9])), data = job[10], tags = cjson.decode(job[11]), history = self:history(), failure = cjson.decode(job[12] or '{}'), throttles = cjson.decode(job[13] or '[]'), spawned_from_jid = job[14], dependents = redis.call( 'smembers', QlessJob.ns .. self.jid .. '-dependents'), dependencies = redis.call( 'smembers', QlessJob.ns .. self.jid .. '-dependencies') } if #arg > 0 then local response = {} for index, key in ipairs(arg) do table.insert(response, data[key]) end return response else return data end end function QlessJob:complete(now, worker, queue, raw_data, ...) assert(worker, 'Complete(): Arg "worker" missing') assert(queue , 'Complete(): Arg "queue" missing') local data = assert(cjson.decode(raw_data), 'Complete(): Arg "data" missing or not JSON: ' .. tostring(raw_data)) local options = {} for i = 1, #arg, 2 do options[arg[i]] = arg[i + 1] end local nextq = options['next'] local delay = assert(tonumber(options['delay'] or 0)) local depends = assert(cjson.decode(options['depends'] or '[]'), 'Complete(): Arg "depends" not JSON: ' .. tostring(options['depends'])) if options['delay'] and nextq == nil then error('Complete(): "delay" cannot be used without a "next".') end if options['depends'] and nextq == nil then error('Complete(): "depends" cannot be used without a "next".') end local bin = now - (now % 86400) local lastworker, state, priority, retries, current_queue = unpack( redis.call('hmget', QlessJob.ns .. self.jid, 'worker', 'state', 'priority', 'retries', 'queue')) if lastworker == false then error('Complete(): Job does not exist') elseif (state ~= 'running') then error('Complete(): Job is not currently running: ' .. state) elseif lastworker ~= worker then error('Complete(): Job has been handed out to another worker: ' .. tostring(lastworker)) elseif queue ~= current_queue then error('Complete(): Job running in another queue: ' .. tostring(current_queue)) end self:history(now, 'done') if raw_data then redis.call('hset', QlessJob.ns .. self.jid, 'data', raw_data) end local queue_obj = Qless.queue(queue) queue_obj:remove_job(self.jid) self:throttles_release(now) local time = tonumber( redis.call('hget', QlessJob.ns .. self.jid, 'time') or now) local waiting = now - time queue_obj:stat(now, 'run', waiting) redis.call('hset', QlessJob.ns .. self.jid, 'time', string.format("%.20f", now)) redis.call('zrem', 'ql:w:' .. worker .. ':jobs', self.jid) if redis.call('zscore', 'ql:tracked', self.jid) ~= false then Qless.publish('completed', self.jid) end if nextq then queue_obj = Qless.queue(nextq) Qless.publish('log', cjson.encode({ jid = self.jid, event = 'advanced', queue = queue, to = nextq })) self:history(now, 'put', {q = nextq}) if redis.call('zscore', 'ql:queues', nextq) == false then redis.call('zadd', 'ql:queues', now, nextq) end redis.call('hmset', QlessJob.ns .. self.jid, 'state', 'waiting', 'worker', '', 'failure', '{}', 'queue', nextq, 'expires', 0, 'remaining', tonumber(retries)) if (delay > 0) and (#depends == 0) then queue_obj.scheduled.add(now + delay, self.jid) return 'scheduled' else local count = 0 for i, j in ipairs(depends) do local state = redis.call('hget', QlessJob.ns .. j, 'state') if (state and state ~= 'complete') then count = count + 1 redis.call( 'sadd', QlessJob.ns .. j .. '-dependents',self.jid) redis.call( 'sadd', QlessJob.ns .. self.jid .. '-dependencies', j) end end if count > 0 then queue_obj.depends.add(now, self.jid) redis.call('hset', QlessJob.ns .. self.jid, 'state', 'depends') if delay > 0 then queue_obj.depends.add(now, self.jid) redis.call('hset', QlessJob.ns .. self.jid, 'scheduled', now + delay) end return 'depends' else queue_obj.work.add(now, priority, self.jid) return 'waiting' end end else Qless.publish('log', cjson.encode({ jid = self.jid, event = 'completed', queue = queue })) redis.call('hmset', QlessJob.ns .. self.jid, 'state', 'complete', 'worker', '', 'failure', '{}', 'queue', '', 'expires', 0, 'remaining', tonumber(retries)) local count = Qless.config.get('jobs-history-count') local time = Qless.config.get('jobs-history') count = tonumber(count or 50000) time = tonumber(time or 7 * 24 * 60 * 60) redis.call('zadd', 'ql:completed', now, self.jid) local jids = redis.call('zrangebyscore', 'ql:completed', 0, now - time) for index, jid in ipairs(jids) do Qless.job(jid):delete() end redis.call('zremrangebyscore', 'ql:completed', 0, now - time) jids = redis.call('zrange', 'ql:completed', 0, (-1-count)) for index, jid in ipairs(jids) do Qless.job(jid):delete() end redis.call('zremrangebyrank', 'ql:completed', 0, (-1-count)) for i, j in ipairs(redis.call( 'smembers', QlessJob.ns .. self.jid .. '-dependents')) do redis.call('srem', QlessJob.ns .. j .. '-dependencies', self.jid) if redis.call( 'scard', QlessJob.ns .. j .. '-dependencies') == 0 then local q, p, scheduled = unpack( redis.call('hmget', QlessJob.ns .. j, 'queue', 'priority', 'scheduled')) if q then local queue = Qless.queue(q) queue.depends.remove(j) if scheduled then queue.scheduled.add(scheduled, j) redis.call('hset', QlessJob.ns .. j, 'state', 'scheduled') redis.call('hdel', QlessJob.ns .. j, 'scheduled') else queue.work.add(now, p, j) redis.call('hset', QlessJob.ns .. j, 'state', 'waiting') end end end end redis.call('del', QlessJob.ns .. self.jid .. '-dependents') return 'complete' end end function QlessJob:fail(now, worker, group, message, data) local worker = assert(worker , 'Fail(): Arg "worker" missing') local group = assert(group , 'Fail(): Arg "group" missing') local message = assert(message , 'Fail(): Arg "message" missing') local bin = now - (now % 86400) if data then data = cjson.decode(data) end local queue, state, oldworker = unpack(redis.call( 'hmget', QlessJob.ns .. self.jid, 'queue', 'state', 'worker')) if not state then error('Fail(): Job does not exist') elseif state ~= 'running' then error('Fail(): Job not currently running: ' .. state) elseif worker ~= oldworker then error('Fail(): Job running with another worker: ' .. oldworker) end Qless.publish('log', cjson.encode({ jid = self.jid, event = 'failed', worker = worker, group = group, message = message })) if redis.call('zscore', 'ql:tracked', self.jid) ~= false then Qless.publish('failed', self.jid) end redis.call('zrem', 'ql:w:' .. worker .. ':jobs', self.jid) self:history(now, 'failed', {worker = worker, group = group}) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. queue, 'failures', 1) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. queue, 'failed' , 1) local queue_obj = Qless.queue(queue) queue_obj:remove_job(self.jid) if data then redis.call('hset', QlessJob.ns .. self.jid, 'data', cjson.encode(data)) end redis.call('hmset', QlessJob.ns .. self.jid, 'state', 'failed', 'worker', '', 'expires', '', 'failure', cjson.encode({ ['group'] = group, ['message'] = message, ['when'] = math.floor(now), ['worker'] = worker })) self:throttles_release(now) redis.call('sadd', 'ql:failures', group) redis.call('lpush', 'ql:f:' .. group, self.jid) return self.jid end function QlessJob:retry(now, queue, worker, delay, group, message) assert(queue , 'Retry(): Arg "queue" missing') assert(worker, 'Retry(): Arg "worker" missing') delay = assert(tonumber(delay or 0), 'Retry(): Arg "delay" not a number: ' .. tostring(delay)) local oldqueue, state, retries, oldworker, priority, failure = unpack( redis.call('hmget', QlessJob.ns .. self.jid, 'queue', 'state', 'retries', 'worker', 'priority', 'failure')) if oldworker == false then error('Retry(): Job does not exist') elseif state ~= 'running' then error('Retry(): Job is not currently running: ' .. state) elseif oldworker ~= worker then error('Retry(): Job has been given to another worker: ' .. oldworker) end local remaining = tonumber(redis.call( 'hincrby', QlessJob.ns .. self.jid, 'remaining', -1)) redis.call('hdel', QlessJob.ns .. self.jid, 'grace') Qless.queue(oldqueue).locks.remove(self.jid) self:throttles_release(now) redis.call('zrem', 'ql:w:' .. worker .. ':jobs', self.jid) if remaining < 0 then local group = group or 'failed-retries-' .. queue self:history(now, 'failed', {['group'] = group}) redis.call('hmset', QlessJob.ns .. self.jid, 'state', 'failed', 'worker', '', 'expires', '') if group ~= nil and message ~= nil then redis.call('hset', QlessJob.ns .. self.jid, 'failure', cjson.encode({ ['group'] = group, ['message'] = message, ['when'] = math.floor(now), ['worker'] = worker }) ) else redis.call('hset', QlessJob.ns .. self.jid, 'failure', cjson.encode({ ['group'] = group, ['message'] = 'Job exhausted retries in queue "' .. oldqueue .. '"', ['when'] = now, ['worker'] = unpack(self:data('worker')) })) end redis.call('sadd', 'ql:failures', group) redis.call('lpush', 'ql:f:' .. group, self.jid) local bin = now - (now % 86400) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. queue, 'failures', 1) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. queue, 'failed' , 1) else local queue_obj = Qless.queue(queue) if delay > 0 then queue_obj.scheduled.add(now + delay, self.jid) redis.call('hset', QlessJob.ns .. self.jid, 'state', 'scheduled') else queue_obj.work.add(now, priority, self.jid) redis.call('hset', QlessJob.ns .. self.jid, 'state', 'waiting') end if group ~= nil and message ~= nil then redis.call('hset', QlessJob.ns .. self.jid, 'failure', cjson.encode({ ['group'] = group, ['message'] = message, ['when'] = math.floor(now), ['worker'] = worker }) ) end end return math.floor(remaining) end function QlessJob:depends(now, command, ...) assert(command, 'Depends(): Arg "command" missing') local state = redis.call('hget', QlessJob.ns .. self.jid, 'state') if state ~= 'depends' then error('Depends(): Job ' .. self.jid .. ' not in the depends state: ' .. tostring(state)) end if command == 'on' then for i, j in ipairs(arg) do local state = redis.call('hget', QlessJob.ns .. j, 'state') if (state and state ~= 'complete') then redis.call( 'sadd', QlessJob.ns .. j .. '-dependents' , self.jid) redis.call( 'sadd', QlessJob.ns .. self.jid .. '-dependencies', j) end end return true elseif command == 'off' then if arg[1] == 'all' then for i, j in ipairs(redis.call( 'smembers', QlessJob.ns .. self.jid .. '-dependencies')) do redis.call('srem', QlessJob.ns .. j .. '-dependents', self.jid) end redis.call('del', QlessJob.ns .. self.jid .. '-dependencies') local q, p = unpack(redis.call( 'hmget', QlessJob.ns .. self.jid, 'queue', 'priority')) if q then local queue_obj = Qless.queue(q) queue_obj.depends.remove(self.jid) queue_obj.work.add(now, p, self.jid) redis.call('hset', QlessJob.ns .. self.jid, 'state', 'waiting') end else for i, j in ipairs(arg) do redis.call('srem', QlessJob.ns .. j .. '-dependents', self.jid) redis.call( 'srem', QlessJob.ns .. self.jid .. '-dependencies', j) if redis.call('scard', QlessJob.ns .. self.jid .. '-dependencies') == 0 then local q, p = unpack(redis.call( 'hmget', QlessJob.ns .. self.jid, 'queue', 'priority')) if q then local queue_obj = Qless.queue(q) queue_obj.depends.remove(self.jid) queue_obj.work.add(now, p, self.jid) redis.call('hset', QlessJob.ns .. self.jid, 'state', 'waiting') end end end end return true else error('Depends(): Argument "command" must be "on" or "off"') end end function QlessJob:heartbeat(now, worker, data) assert(worker, 'Heatbeat(): Arg "worker" missing') local queue = redis.call('hget', QlessJob.ns .. self.jid, 'queue') or '' local expires = now + tonumber( Qless.config.get(queue .. '-heartbeat') or Qless.config.get('heartbeat', 60)) if data then data = cjson.decode(data) end local job_worker, state = unpack( redis.call('hmget', QlessJob.ns .. self.jid, 'worker', 'state')) if job_worker == false then error('Heartbeat(): Job does not exist') elseif state ~= 'running' then error('Heartbeat(): Job not currently running: ' .. state) elseif job_worker ~= worker or #job_worker == 0 then error('Heartbeat(): Job given out to another worker: ' .. job_worker) else if data then redis.call('hmset', QlessJob.ns .. self.jid, 'expires', expires, 'worker', worker, 'data', cjson.encode(data)) else redis.call('hmset', QlessJob.ns .. self.jid, 'expires', expires, 'worker', worker) end redis.call('zadd', 'ql:w:' .. worker .. ':jobs', expires, self.jid) local queue = Qless.queue( redis.call('hget', QlessJob.ns .. self.jid, 'queue')) queue.locks.add(expires, self.jid) return expires end end function QlessJob:priority(priority) priority = assert(tonumber(priority), 'Priority(): Arg "priority" missing or not a number: ' .. tostring(priority)) local queue = redis.call('hget', QlessJob.ns .. self.jid, 'queue') if queue == nil then error('Priority(): Job ' .. self.jid .. ' does not exist') elseif queue == '' then redis.call('hset', QlessJob.ns .. self.jid, 'priority', priority) return priority else local queue_obj = Qless.queue(queue) if queue_obj.work.score(self.jid) then queue_obj.work.add(0, priority, self.jid) end redis.call('hset', QlessJob.ns .. self.jid, 'priority', priority) return priority end end function QlessJob:update(data) local tmp = {} for k, v in pairs(data) do table.insert(tmp, k) table.insert(tmp, v) end redis.call('hmset', QlessJob.ns .. self.jid, unpack(tmp)) end function QlessJob:timeout(now) local queue_name, state, worker = unpack(redis.call('hmget', QlessJob.ns .. self.jid, 'queue', 'state', 'worker')) if queue_name == nil then error('Timeout(): Job does not exist') elseif state ~= 'running' then error('Timeout(): Job ' .. self.jid .. ' not running') else self:history(now, 'timed-out') local queue = Qless.queue(queue_name) queue.locks.remove(self.jid) queue.work.add(now, math.huge, self.jid) redis.call('hmset', QlessJob.ns .. self.jid, 'state', 'stalled', 'expires', 0) local encoded = cjson.encode({ jid = self.jid, event = 'lock_lost', worker = worker }) Qless.publish('w:' .. worker, encoded) Qless.publish('log', encoded) return queue_name end end function QlessJob:exists() return redis.call('exists', QlessJob.ns .. self.jid) == 1 end function QlessJob:history(now, what, item) local history = redis.call('hget', QlessJob.ns .. self.jid, 'history') if history then history = cjson.decode(history) for i, value in ipairs(history) do redis.call('rpush', QlessJob.ns .. self.jid .. '-history', cjson.encode({math.floor(value.put), 'put', {q = value.q}})) if value.popped then redis.call('rpush', QlessJob.ns .. self.jid .. '-history', cjson.encode({math.floor(value.popped), 'popped', {worker = value.worker}})) end if value.failed then redis.call('rpush', QlessJob.ns .. self.jid .. '-history', cjson.encode( {math.floor(value.failed), 'failed', nil})) end if value.done then redis.call('rpush', QlessJob.ns .. self.jid .. '-history', cjson.encode( {math.floor(value.done), 'done', nil})) end end redis.call('hdel', QlessJob.ns .. self.jid, 'history') end if what == nil then local response = {} for i, value in ipairs(redis.call('lrange', QlessJob.ns .. self.jid .. '-history', 0, -1)) do value = cjson.decode(value) local dict = value[3] or {} dict['when'] = value[1] dict['what'] = value[2] table.insert(response, dict) end return response else local count = tonumber(Qless.config.get('max-job-history', 100)) if count > 0 then local obj = redis.call('lpop', QlessJob.ns .. self.jid .. '-history') redis.call('ltrim', QlessJob.ns .. self.jid .. '-history', -count + 2, -1) if obj ~= nil then redis.call('lpush', QlessJob.ns .. self.jid .. '-history', obj) end end return redis.call('rpush', QlessJob.ns .. self.jid .. '-history', cjson.encode({math.floor(now), what, item})) end end function QlessJob:throttles_release(now) local throttles = redis.call('hget', QlessJob.ns .. self.jid, 'throttles') throttles = cjson.decode(throttles or '[]') for _, tid in ipairs(throttles) do Qless.throttle(tid):release(now, self.jid) end end function QlessJob:throttles_available() for _, tid in ipairs(self:throttles()) do if not Qless.throttle(tid):available() then return false end end return true end function QlessJob:throttles_acquire(now) if not self:throttles_available() then return false end for _, tid in ipairs(self:throttles()) do Qless.throttle(tid):acquire(self.jid) end return true end function QlessJob:throttle(now) for _, tid in ipairs(self:throttles()) do local throttle = Qless.throttle(tid) if not throttle:available() then throttle:pend(now, self.jid) return end end end function QlessJob:throttles() if not self._throttles then self._throttles = cjson.decode(redis.call('hget', QlessJob.ns .. self.jid, 'throttles') or '[]') end return self._throttles end function QlessJob:delete() local tags = redis.call('hget', QlessJob.ns .. self.jid, 'tags') or '[]' tags = cjson.decode(tags) for i, tag in ipairs(tags) do self:remove_tag(tag) end redis.call('del', QlessJob.ns .. self.jid) redis.call('del', QlessJob.ns .. self.jid .. '-history') redis.call('del', QlessJob.ns .. self.jid .. '-dependencies') end function QlessJob:insert_tag(now, tag) redis.call('zadd', 'ql:t:' .. tag, now, self.jid) redis.call('zincrby', 'ql:tags', 1, tag) end function QlessJob:remove_tag(tag) local namespaced_tag = 'ql:t:' .. tag redis.call('zrem', namespaced_tag, self.jid) local remaining = redis.call('zcard', namespaced_tag) if tonumber(remaining) == 0 then redis.call('zrem', 'ql:tags', tag) else redis.call('zincrby', 'ql:tags', -1, tag) end end function Qless.queue(name) assert(name, 'Queue(): no queue name provided') local queue = {} setmetatable(queue, QlessQueue) queue.name = name queue.work = { peek = function(count) if count == 0 then return {} end local jids = {} for index, jid in ipairs(redis.call( 'zrevrange', queue:prefix('work'), 0, count - 1)) do table.insert(jids, jid) end return jids end, remove = function(...) if #arg > 0 then return redis.call('zrem', queue:prefix('work'), unpack(arg)) end end, add = function(now, priority, jid) return redis.call('zadd', queue:prefix('work'), priority - (now / 10000000000), jid) end, score = function(jid) return redis.call('zscore', queue:prefix('work'), jid) end, length = function() return redis.call('zcard', queue:prefix('work')) end } queue.locks = { expired = function(now, offset, count) return redis.call('zrangebyscore', queue:prefix('locks'), -math.huge, now, 'LIMIT', offset, count) end, peek = function(now, offset, count) return redis.call('zrangebyscore', queue:prefix('locks'), now, math.huge, 'LIMIT', offset, count) end, add = function(expires, jid) redis.call('zadd', queue:prefix('locks'), expires, jid) end, remove = function(...) if #arg > 0 then return redis.call('zrem', queue:prefix('locks'), unpack(arg)) end end, running = function(now) return redis.call('zcount', queue:prefix('locks'), now, math.huge) end, length = function(now) if now then return redis.call('zcount', queue:prefix('locks'), 0, now) else return redis.call('zcard', queue:prefix('locks')) end end } queue.depends = { peek = function(now, offset, count) return redis.call('zrange', queue:prefix('depends'), offset, offset + count - 1) end, add = function(now, jid) redis.call('zadd', queue:prefix('depends'), now, jid) end, remove = function(...) if #arg > 0 then return redis.call('zrem', queue:prefix('depends'), unpack(arg)) end end, length = function() return redis.call('zcard', queue:prefix('depends')) end } queue.throttled = { length = function() return (redis.call('zcard', queue:prefix('throttled')) or 0) end, peek = function(now, min, max) return redis.call('zrange', queue:prefix('throttled'), min, max) end, add = function(...) if #arg > 0 then redis.call('zadd', queue:prefix('throttled'), unpack(arg)) end end, remove = function(...) if #arg > 0 then return redis.call('zrem', queue:prefix('throttled'), unpack(arg)) end end, pop = function(min, max) return redis.call('zremrangebyrank', queue:prefix('throttled'), min, max) end } queue.scheduled = { peek = function(now, offset, count) return redis.call('zrange', queue:prefix('scheduled'), offset, offset + count - 1) end, ready = function(now, offset, count) return redis.call('zrangebyscore', queue:prefix('scheduled'), 0, now, 'LIMIT', offset, count) end, add = function(when, jid) redis.call('zadd', queue:prefix('scheduled'), when, jid) end, remove = function(...) if #arg > 0 then return redis.call('zrem', queue:prefix('scheduled'), unpack(arg)) end end, length = function() return redis.call('zcard', queue:prefix('scheduled')) end } queue.recurring = { peek = function(now, offset, count) return redis.call('zrangebyscore', queue:prefix('recur'), 0, now, 'LIMIT', offset, count) end, ready = function(now, offset, count) end, add = function(when, jid) redis.call('zadd', queue:prefix('recur'), when, jid) end, remove = function(...) if #arg > 0 then return redis.call('zrem', queue:prefix('recur'), unpack(arg)) end end, update = function(increment, jid) redis.call('zincrby', queue:prefix('recur'), increment, jid) end, score = function(jid) return redis.call('zscore', queue:prefix('recur'), jid) end, length = function() return redis.call('zcard', queue:prefix('recur')) end } return queue end function QlessQueue:prefix(group) if group then return QlessQueue.ns..self.name..'-'..group else return QlessQueue.ns..self.name end end function QlessQueue:stats(now, date) date = assert(tonumber(date), 'Stats(): Arg "date" missing or not a number: '.. (date or 'nil')) local bin = date - (date % 86400) local histokeys = { 's0','s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12','s13','s14','s15','s16','s17','s18','s19','s20','s21','s22','s23','s24','s25','s26','s27','s28','s29','s30','s31','s32','s33','s34','s35','s36','s37','s38','s39','s40','s41','s42','s43','s44','s45','s46','s47','s48','s49','s50','s51','s52','s53','s54','s55','s56','s57','s58','s59', 'm1','m2','m3','m4','m5','m6','m7','m8','m9','m10','m11','m12','m13','m14','m15','m16','m17','m18','m19','m20','m21','m22','m23','m24','m25','m26','m27','m28','m29','m30','m31','m32','m33','m34','m35','m36','m37','m38','m39','m40','m41','m42','m43','m44','m45','m46','m47','m48','m49','m50','m51','m52','m53','m54','m55','m56','m57','m58','m59', 'h1','h2','h3','h4','h5','h6','h7','h8','h9','h10','h11','h12','h13','h14','h15','h16','h17','h18','h19','h20','h21','h22','h23', 'd1','d2','d3','d4','d5','d6' } local mkstats = function(name, bin, queue) local results = {} local key = 'ql:s:' .. name .. ':' .. bin .. ':' .. queue local count, mean, vk = unpack(redis.call('hmget', key, 'total', 'mean', 'vk')) count = tonumber(count) or 0 mean = tonumber(mean) or 0 vk = tonumber(vk) results.count = count or 0 results.mean = mean or 0 results.histogram = {} if not count then results.std = 0 else if count > 1 then results.std = math.sqrt(vk / (count - 1)) else results.std = 0 end end local histogram = redis.call('hmget', key, unpack(histokeys)) for i=1,#histokeys do table.insert(results.histogram, tonumber(histogram[i]) or 0) end return results end local retries, failed, failures = unpack(redis.call('hmget', 'ql:s:stats:' .. bin .. ':' .. self.name, 'retries', 'failed', 'failures')) return { retries = tonumber(retries or 0), failed = tonumber(failed or 0), failures = tonumber(failures or 0), wait = mkstats('wait', bin, self.name), run = mkstats('run' , bin, self.name) } end function QlessQueue:peek(now, count) count = assert(tonumber(count), 'Peek(): Arg "count" missing or not a number: ' .. tostring(count)) local jids = self.locks.expired(now, 0, count) self:check_recurring(now, count - #jids) self:check_scheduled(now, count - #jids) table.extend(jids, self.work.peek(count - #jids)) return jids end function QlessQueue:paused() return redis.call('sismember', 'ql:paused_queues', self.name) == 1 end function QlessQueue.pause(now, ...) redis.call('sadd', 'ql:paused_queues', unpack(arg)) end function QlessQueue.unpause(...) redis.call('srem', 'ql:paused_queues', unpack(arg)) end function QlessQueue:pop(now, worker, count) assert(worker, 'Pop(): Arg "worker" missing') count = assert(tonumber(count), 'Pop(): Arg "count" missing or not a number: ' .. tostring(count)) if self:paused() then return {} end redis.call('zadd', 'ql:workers', now, worker) local dead_jids = self:invalidate_locks(now, count) or {} local popped = {} for index, jid in ipairs(dead_jids) do local success = self:pop_job(now, worker, Qless.job(jid)) if success then table.insert(popped, jid) end end if not Qless.throttle(QlessQueue.ns .. self.name):available() then return popped end self:check_recurring(now, count - #dead_jids) self:check_scheduled(now, count - #dead_jids) local pop_retry_limit = tonumber( Qless.config.get(self.name .. '-max-pop-retry') or Qless.config.get('max-pop-retry', 1) ) while #popped < count and pop_retry_limit > 0 do local jids = self.work.peek(count - #popped) or {} if #jids == 0 then break end for index, jid in ipairs(jids) do local job = Qless.job(jid) if job:throttles_acquire(now) then local success = self:pop_job(now, worker, job) if success then table.insert(popped, jid) end else self:throttle(now, job) end end self.work.remove(unpack(jids)) pop_retry_limit = pop_retry_limit - 1 end return popped end function QlessQueue:throttle(now, job) job:throttle(now) self.throttled.add(now, job.jid) local state = unpack(job:data('state')) if state ~= 'throttled' then job:update({state = 'throttled'}) job:history(now, 'throttled', {queue = self.name}) end end function QlessQueue:pop_job(now, worker, job) local state local jid = job.jid local job_state = job:data('state') if not job_state then return false end state = unpack(job_state) job:history(now, 'popped', {worker = worker}) local expires = now + tonumber( Qless.config.get(self.name .. '-heartbeat') or Qless.config.get('heartbeat', 60)) local time = tonumber(redis.call('hget', QlessJob.ns .. jid, 'time') or now) local waiting = now - time self:stat(now, 'wait', waiting) redis.call('hset', QlessJob.ns .. jid, 'time', string.format("%.20f", now)) redis.call('zadd', 'ql:w:' .. worker .. ':jobs', expires, jid) job:update({ worker = worker, expires = expires, state = 'running' }) self.locks.add(expires, jid) local tracked = redis.call('zscore', 'ql:tracked', jid) ~= false if tracked then Qless.publish('popped', jid) end return true end function QlessQueue:stat(now, stat, val) local bin = now - (now % 86400) local key = 'ql:s:' .. stat .. ':' .. bin .. ':' .. self.name local count, mean, vk = unpack( redis.call('hmget', key, 'total', 'mean', 'vk')) count = count or 0 if count == 0 then mean = val vk = 0 count = 1 else count = count + 1 local oldmean = mean mean = mean + (val - mean) / count vk = vk + (val - mean) * (val - oldmean) end val = math.floor(val) if val < 60 then -- seconds redis.call('hincrby', key, 's' .. val, 1) elseif val < 3600 then -- minutes redis.call('hincrby', key, 'm' .. math.floor(val / 60), 1) elseif val < 86400 then -- hours redis.call('hincrby', key, 'h' .. math.floor(val / 3600), 1) else -- days redis.call('hincrby', key, 'd' .. math.floor(val / 86400), 1) end redis.call('hmset', key, 'total', count, 'mean', mean, 'vk', vk) end function QlessQueue:put(now, worker, jid, klass, raw_data, delay, ...) assert(jid , 'Put(): Arg "jid" missing') assert(klass, 'Put(): Arg "klass" missing') local data = assert(cjson.decode(raw_data), 'Put(): Arg "data" missing or not JSON: ' .. tostring(raw_data)) delay = assert(tonumber(delay), 'Put(): Arg "delay" not a number: ' .. tostring(delay)) if #arg % 2 == 1 then error('Odd number of additional args: ' .. tostring(arg)) end local options = {} for i = 1, #arg, 2 do options[arg[i]] = arg[i + 1] end local job = Qless.job(jid) local priority, tags, oldqueue, state, failure, retries, oldworker = unpack(redis.call('hmget', QlessJob.ns .. jid, 'priority', 'tags', 'queue', 'state', 'failure', 'retries', 'worker')) if tags then Qless.tag(now, 'remove', jid, unpack(cjson.decode(tags))) end local retries = assert(tonumber(options['retries'] or retries or 5) , 'Put(): Arg "retries" not a number: ' .. tostring(options['retries'])) local tags = assert(cjson.decode(options['tags'] or tags or '[]' ), 'Put(): Arg "tags" not JSON' .. tostring(options['tags'])) local priority = assert(tonumber(options['priority'] or priority or 0), 'Put(): Arg "priority" not a number' .. tostring(options['priority'])) local depends = assert(cjson.decode(options['depends'] or '[]') , 'Put(): Arg "depends" not JSON: ' .. tostring(options['depends'])) local throttles = assert(cjson.decode(options['throttles'] or '[]'), 'Put(): Arg "throttles" not JSON array: ' .. tostring(options['throttles'])) if #depends > 0 then local new = {} for _, d in ipairs(depends) do new[d] = 1 end local original = redis.call( 'smembers', QlessJob.ns .. jid .. '-dependencies') for _, dep in pairs(original) do if new[dep] == nil then redis.call('srem', QlessJob.ns .. dep .. '-dependents' , jid) redis.call('srem', QlessJob.ns .. jid .. '-dependencies', dep) end end end Qless.publish('log', cjson.encode({ jid = jid, event = 'put', queue = self.name })) job:history(now, 'put', {q = self.name}) if oldqueue then local queue_obj = Qless.queue(oldqueue) queue_obj:remove_job(jid) local old_qid = QlessQueue.ns .. oldqueue for index, tname in ipairs(throttles) do if tname == old_qid then table.remove(throttles, index) end end end if oldworker and oldworker ~= '' then redis.call('zrem', 'ql:w:' .. oldworker .. ':jobs', jid) if oldworker ~= worker then local encoded = cjson.encode({ jid = jid, event = 'lock_lost', worker = oldworker }) Qless.publish('w:' .. oldworker, encoded) Qless.publish('log', encoded) end end if state == 'complete' then redis.call('zrem', 'ql:completed', jid) end for i, tag in ipairs(tags) do Qless.job(jid):insert_tag(now, tag) end if state == 'failed' then failure = cjson.decode(failure) redis.call('lrem', 'ql:f:' .. failure.group, 0, jid) if redis.call('llen', 'ql:f:' .. failure.group) == 0 then redis.call('srem', 'ql:failures', failure.group) end local bin = failure.when - (failure.when % 86400) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. self.name, 'failed' , -1) end table.insert(throttles, QlessQueue.ns .. self.name) data = { 'jid' , jid, 'klass' , klass, 'data' , raw_data, 'priority' , priority, 'tags' , cjson.encode(tags), 'state' , ((delay > 0) and 'scheduled') or 'waiting', 'worker' , '', 'expires' , 0, 'queue' , self.name, 'retries' , retries, 'remaining', retries, 'time' , string.format("%.20f", now), 'throttles', cjson.encode(throttles) } redis.call('hmset', QlessJob.ns .. jid, unpack(data)) for i, j in ipairs(depends) do local state = redis.call('hget', QlessJob.ns .. j, 'state') if (state and state ~= 'complete') then redis.call('sadd', QlessJob.ns .. j .. '-dependents' , jid) redis.call('sadd', QlessJob.ns .. jid .. '-dependencies', j) end end if delay > 0 then if redis.call('scard', QlessJob.ns .. jid .. '-dependencies') > 0 then self.depends.add(now, jid) redis.call('hmset', QlessJob.ns .. jid, 'state', 'depends', 'scheduled', now + delay) else self.scheduled.add(now + delay, jid) end else local job = Qless.job(jid) if redis.call('scard', QlessJob.ns .. jid .. '-dependencies') > 0 then self.depends.add(now, jid) redis.call('hset', QlessJob.ns .. jid, 'state', 'depends') elseif not job:throttles_available() then self:throttle(now, job) else self.work.add(now, priority, jid) end end if redis.call('zscore', 'ql:queues', self.name) == false then redis.call('zadd', 'ql:queues', now, self.name) end if redis.call('zscore', 'ql:tracked', jid) ~= false then Qless.publish('put', jid) end return jid end function QlessQueue:unfail(now, group, count) assert(group, 'Unfail(): Arg "group" missing') count = assert(tonumber(count or 25), 'Unfail(): Arg "count" not a number: ' .. tostring(count)) local jids = redis.call('lrange', 'ql:f:' .. group, -count, -1) local toinsert = {} for index, jid in ipairs(jids) do local job = Qless.job(jid) local data = job:data() job:history(now, 'put', {q = self.name}) redis.call('hmset', QlessJob.ns .. data.jid, 'state' , 'waiting', 'worker' , '', 'expires' , 0, 'queue' , self.name, 'remaining', data.retries or 5) self.work.add(now, data.priority, data.jid) end redis.call('ltrim', 'ql:f:' .. group, 0, -count - 1) if (redis.call('llen', 'ql:f:' .. group) == 0) then redis.call('srem', 'ql:failures', group) end return #jids end function QlessQueue:recur(now, jid, klass, raw_data, spec, ...) assert(jid , 'RecurringJob On(): Arg "jid" missing') assert(klass, 'RecurringJob On(): Arg "klass" missing') assert(spec , 'RecurringJob On(): Arg "spec" missing') local data = assert(cjson.decode(raw_data), 'RecurringJob On(): Arg "data" not JSON: ' .. tostring(raw_data)) if spec == 'interval' then local interval = assert(tonumber(arg[1]), 'Recur(): Arg "interval" not a number: ' .. tostring(arg[1])) local offset = assert(tonumber(arg[2]), 'Recur(): Arg "offset" not a number: ' .. tostring(arg[2])) if interval <= 0 then error('Recur(): Arg "interval" must be greater than 0') end if #arg % 2 == 1 then error('Odd number of additional args: ' .. tostring(arg)) end local options = {} for i = 3, #arg, 2 do options[arg[i]] = arg[i + 1] end options.tags = assert(cjson.decode(options.tags or '{}'), 'Recur(): Arg "tags" must be JSON string array: ' .. tostring( options.tags)) options.priority = assert(tonumber(options.priority or 0), 'Recur(): Arg "priority" not a number: ' .. tostring( options.priority)) options.retries = assert(tonumber(options.retries or 0), 'Recur(): Arg "retries" not a number: ' .. tostring( options.retries)) options.backlog = assert(tonumber(options.backlog or 0), 'Recur(): Arg "backlog" not a number: ' .. tostring( options.backlog)) options.throttles = assert(cjson.decode(options['throttles'] or '{}'), 'Recur(): Arg "throttles" not JSON array: ' .. tostring(options['throttles'])) local count, old_queue = unpack(redis.call('hmget', 'ql:r:' .. jid, 'count', 'queue')) count = count or 0 if old_queue then Qless.queue(old_queue).recurring.remove(jid) end redis.call('hmset', 'ql:r:' .. jid, 'jid' , jid, 'klass' , klass, 'data' , raw_data, 'priority' , options.priority, 'tags' , cjson.encode(options.tags or {}), 'state' , 'recur', 'queue' , self.name, 'type' , 'interval', 'count' , count, 'interval' , interval, 'retries' , options.retries, 'backlog' , options.backlog, 'throttles', cjson.encode(options.throttles or {})) self.recurring.add(now + offset, jid) if redis.call('zscore', 'ql:queues', self.name) == false then redis.call('zadd', 'ql:queues', now, self.name) end return jid else error('Recur(): schedule type "' .. tostring(spec) .. '" unknown') end end function QlessQueue:length() return self.locks.length() + self.work.length() + self.scheduled.length() end function QlessQueue:remove_job(jid) self.work.remove(jid) self.locks.remove(jid) self.throttled.remove(jid) self.depends.remove(jid) self.scheduled.remove(jid) end function QlessQueue:check_recurring(now, count) local moved = 0 local r = self.recurring.peek(now, 0, count) for index, jid in ipairs(r) do local r = redis.call('hmget', 'ql:r:' .. jid, 'klass', 'data', 'priority', 'tags', 'retries', 'interval', 'backlog', 'throttles') local klass, data, priority, tags, retries, interval, backlog, throttles = unpack( redis.call('hmget', 'ql:r:' .. jid, 'klass', 'data', 'priority', 'tags', 'retries', 'interval', 'backlog', 'throttles')) local _tags = cjson.decode(tags) local score = math.floor(tonumber(self.recurring.score(jid))) interval = tonumber(interval) backlog = tonumber(backlog or 0) if backlog ~= 0 then local num = ((now - score) / interval) if num > backlog then score = score + ( math.ceil(num - backlog) * interval ) end end while (score <= now) and (moved < count) do local count = redis.call('hincrby', 'ql:r:' .. jid, 'count', 1) moved = moved + 1 local child_jid = jid .. '-' .. count for i, tag in ipairs(_tags) do Qless.job(child_jid):insert_tag(now, tag) end redis.call('hmset', QlessJob.ns .. child_jid, 'jid' , child_jid, 'klass' , klass, 'data' , data, 'priority' , priority, 'tags' , tags, 'state' , 'waiting', 'worker' , '', 'expires' , 0, 'queue' , self.name, 'retries' , retries, 'remaining', retries, 'time' , string.format("%.20f", score), 'throttles', throttles, 'spawned_from_jid', jid) Qless.job(child_jid):history(score, 'put', {q = self.name}) self.work.add(score, priority, child_jid) score = score + interval self.recurring.add(score, jid) end end end function QlessQueue:check_scheduled(now, count) local scheduled = self.scheduled.ready(now, 0, count) for index, jid in ipairs(scheduled) do local priority = tonumber( redis.call('hget', QlessJob.ns .. jid, 'priority') or 0) self.work.add(now, priority, jid) self.scheduled.remove(jid) redis.call('hset', QlessJob.ns .. jid, 'state', 'waiting') end end function QlessQueue:invalidate_locks(now, count) local jids = {} for index, jid in ipairs(self.locks.expired(now, 0, count)) do local worker, failure = unpack( redis.call('hmget', QlessJob.ns .. jid, 'worker', 'failure')) redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid) local grace_period = tonumber(Qless.config.get('grace-period')) local courtesy_sent = tonumber( redis.call('hget', QlessJob.ns .. jid, 'grace') or 0) local send_message = (courtesy_sent ~= 1) local invalidate = not send_message if grace_period <= 0 then send_message = true invalidate = true end if send_message then if redis.call('zscore', 'ql:tracked', jid) ~= false then Qless.publish('stalled', jid) end Qless.job(jid):history(now, 'timed-out') redis.call('hset', QlessJob.ns .. jid, 'grace', 1) local encoded = cjson.encode({ jid = jid, event = 'lock_lost', worker = worker }) Qless.publish('w:' .. worker, encoded) Qless.publish('log', encoded) self.locks.add(now + grace_period, jid) local bin = now - (now % 86400) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. self.name, 'retries', 1) end if invalidate then redis.call('hdel', QlessJob.ns .. jid, 'grace', 0) local remaining = tonumber(redis.call( 'hincrby', QlessJob.ns .. jid, 'remaining', -1)) if remaining < 0 then self.work.remove(jid) self.locks.remove(jid) self.scheduled.remove(jid) local job = Qless.job(jid) local job_data = Qless.job(jid):data() local queue = job_data['queue'] local group = 'failed-retries-' .. queue job:throttles_release(now) job:history(now, 'failed', {group = group}) redis.call('hmset', QlessJob.ns .. jid, 'state', 'failed', 'worker', '', 'expires', '') redis.call('hset', QlessJob.ns .. jid, 'failure', cjson.encode({ ['group'] = group, ['message'] = 'Job exhausted retries in queue "' .. self.name .. '"', ['when'] = now, ['worker'] = unpack(job:data('worker')) })) redis.call('sadd', 'ql:failures', group) redis.call('lpush', 'ql:f:' .. group, jid) if redis.call('zscore', 'ql:tracked', jid) ~= false then Qless.publish('failed', jid) end Qless.publish('log', cjson.encode({ jid = jid, event = 'failed', group = group, worker = worker, message = 'Job exhausted retries in queue "' .. self.name .. '"' })) local bin = now - (now % 86400) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. self.name, 'failures', 1) redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. self.name, 'failed' , 1) else table.insert(jids, jid) end end end return jids end function QlessQueue.deregister(...) redis.call('zrem', Qless.ns .. 'queues', unpack(arg)) end function QlessQueue.counts(now, name) if name then local queue = Qless.queue(name) local stalled = queue.locks.length(now) queue:check_scheduled(now, queue.scheduled.length()) return { name = name, waiting = queue.work.length(), stalled = stalled, running = queue.locks.length() - stalled, throttled = queue.throttled.length(), scheduled = queue.scheduled.length(), depends = queue.depends.length(), recurring = queue.recurring.length(), paused = queue:paused() } else local queues = redis.call('zrange', 'ql:queues', 0, -1) local response = {} for index, qname in ipairs(queues) do table.insert(response, QlessQueue.counts(now, qname)) end return response end end function QlessRecurringJob:data() local job = redis.call( 'hmget', 'ql:r:' .. self.jid, 'jid', 'klass', 'state', 'queue', 'priority', 'interval', 'retries', 'count', 'data', 'tags', 'backlog') if not job[1] then return nil end return { jid = job[1], klass = job[2], state = job[3], queue = job[4], priority = tonumber(job[5]), interval = tonumber(job[6]), retries = tonumber(job[7]), count = tonumber(job[8]), data = job[9], tags = cjson.decode(job[10]), backlog = tonumber(job[11] or 0) } end function QlessRecurringJob:update(now, ...) local options = {} if redis.call('exists', 'ql:r:' .. self.jid) ~= 0 then for i = 1, #arg, 2 do local key = arg[i] local value = arg[i+1] assert(value, 'No value provided for ' .. tostring(key)) if key == 'priority' or key == 'interval' or key == 'retries' then value = assert(tonumber(value), 'Recur(): Arg "' .. key .. '" must be a number: ' .. tostring(value)) if key == 'interval' then local queue, interval = unpack(redis.call('hmget', 'ql:r:' .. self.jid, 'queue', 'interval')) Qless.queue(queue).recurring.update( value - tonumber(interval), self.jid) end redis.call('hset', 'ql:r:' .. self.jid, key, value) elseif key == 'data' then assert(cjson.decode(value), 'Recur(): Arg "data" is not JSON-encoded: ' .. tostring(value)) redis.call('hset', 'ql:r:' .. self.jid, 'data', value) elseif key == 'klass' then redis.call('hset', 'ql:r:' .. self.jid, 'klass', value) elseif key == 'queue' then local queue_obj = Qless.queue( redis.call('hget', 'ql:r:' .. self.jid, 'queue')) local score = queue_obj.recurring.score(self.jid) queue_obj.recurring.remove(self.jid) Qless.queue(value).recurring.add(score, self.jid) redis.call('hset', 'ql:r:' .. self.jid, 'queue', value) if redis.call('zscore', 'ql:queues', value) == false then redis.call('zadd', 'ql:queues', now, value) end elseif key == 'backlog' then value = assert(tonumber(value), 'Recur(): Arg "backlog" not a number: ' .. tostring(value)) redis.call('hset', 'ql:r:' .. self.jid, 'backlog', value) else error('Recur(): Unrecognized option "' .. key .. '"') end end return true else error('Recur(): No recurring job ' .. self.jid) end end function QlessRecurringJob:tag(...) local tags = redis.call('hget', 'ql:r:' .. self.jid, 'tags') if tags then tags = cjson.decode(tags) local _tags = {} for i,v in ipairs(tags) do _tags[v] = true end for i=1,#arg do if _tags[arg[i]] == nil then table.insert(tags, arg[i]) end end tags = cjson.encode(tags) redis.call('hset', 'ql:r:' .. self.jid, 'tags', tags) return tags else error('Tag(): Job ' .. self.jid .. ' does not exist') end end function QlessRecurringJob:untag(...) local tags = redis.call('hget', 'ql:r:' .. self.jid, 'tags') if tags then tags = cjson.decode(tags) local _tags = {} for i,v in ipairs(tags) do _tags[v] = true end for i = 1,#arg do _tags[arg[i]] = nil end local results = {} for i, tag in ipairs(tags) do if _tags[tag] then table.insert(results, tag) end end tags = cjson.encode(results) redis.call('hset', 'ql:r:' .. self.jid, 'tags', tags) return tags else error('Untag(): Job ' .. self.jid .. ' does not exist') end end function QlessRecurringJob:unrecur() local queue = redis.call('hget', 'ql:r:' .. self.jid, 'queue') if queue then Qless.queue(queue).recurring.remove(self.jid) redis.call('del', 'ql:r:' .. self.jid) return true else return true end end function QlessWorker.deregister(...) redis.call('zrem', 'ql:workers', unpack(arg)) end function QlessWorker.counts(now, worker) local interval = tonumber(Qless.config.get('max-worker-age', 86400)) local workers = redis.call('zrangebyscore', 'ql:workers', 0, now - interval) for index, worker in ipairs(workers) do redis.call('del', 'ql:w:' .. worker .. ':jobs') end redis.call('zremrangebyscore', 'ql:workers', 0, now - interval) if worker then return { jobs = redis.call('zrevrangebyscore', 'ql:w:' .. worker .. ':jobs', now + 8640000, now), stalled = redis.call('zrevrangebyscore', 'ql:w:' .. worker .. ':jobs', now, 0) } else local response = {} local workers = redis.call('zrevrange', 'ql:workers', 0, -1) for index, worker in ipairs(workers) do table.insert(response, { name = worker, jobs = redis.call('zcount', 'ql:w:' .. worker .. ':jobs', now, now + 8640000), stalled = redis.call('zcount', 'ql:w:' .. worker .. ':jobs', 0, now) }) end return response end end function QlessThrottle:data() local data = { id = self.id, maximum = 0 } local throttle = redis.call('hmget', QlessThrottle.ns .. self.id, 'id', 'maximum') if throttle[2] then data.maximum = tonumber(throttle[2]) end return data end function QlessThrottle:set(data, expiration) redis.call('hmset', QlessThrottle.ns .. self.id, 'id', self.id, 'maximum', data.maximum) if expiration > 0 then redis.call('expire', QlessThrottle.ns .. self.id, expiration) end end function QlessThrottle:unset() redis.call('del', QlessThrottle.ns .. self.id) end function QlessThrottle:acquire(jid) if not self:available() then return false end self.locks.add(1, jid) return true end function QlessThrottle:pend(now, jid) self.pending.add(now, jid) end function QlessThrottle:release(now, jid) if self.locks.remove(jid) == 0 then self.pending.remove(jid) end local available_locks = self:locks_available() if self.pending.length() == 0 or available_locks < 1 then return end for _, jid in ipairs(self.pending.peek(0, available_locks - 1)) do local job = Qless.job(jid) local data = job:data() local queue = Qless.queue(data['queue']) queue.throttled.remove(jid) queue.work.add(now, data.priority, jid) end local popped = self.pending.pop(0, available_locks - 1) end function QlessThrottle:available() return self.maximum == 0 or self.locks.length() < self.maximum end function QlessThrottle:ttl() return redis.call('ttl', QlessThrottle.ns .. self.id) end function QlessThrottle:locks_available() if self.maximum == 0 then return 10 end return self.maximum - self.locks.length() end local QlessAPI = {} function QlessAPI.get(now, jid) local data = Qless.job(jid):data() if not data then return nil end return cjson.encode(data) end function QlessAPI.multiget(now, ...) local results = {} for i, jid in ipairs(arg) do table.insert(results, Qless.job(jid):data()) end return cjson.encode(results) end QlessAPI['config.get'] = function(now, key) if not key then return cjson.encode(Qless.config.get(key)) else return Qless.config.get(key) end end QlessAPI['config.set'] = function(now, key, value) return Qless.config.set(key, value) end QlessAPI['config.unset'] = function(now, key) return Qless.config.unset(key) end QlessAPI.queues = function(now, queue) return cjson.encode(QlessQueue.counts(now, queue)) end QlessAPI.complete = function(now, jid, worker, queue, data, ...) return Qless.job(jid):complete(now, worker, queue, data, unpack(arg)) end QlessAPI.failed = function(now, group, start, limit) return cjson.encode(Qless.failed(group, start, limit)) end QlessAPI.fail = function(now, jid, worker, group, message, data) return Qless.job(jid):fail(now, worker, group, message, data) end QlessAPI.jobs = function(now, state, ...) return Qless.jobs(now, state, unpack(arg)) end QlessAPI.retry = function(now, jid, queue, worker, delay, group, message) return Qless.job(jid):retry(now, queue, worker, delay, group, message) end QlessAPI.depends = function(now, jid, command, ...) return Qless.job(jid):depends(now, command, unpack(arg)) end QlessAPI.heartbeat = function(now, jid, worker, data) return Qless.job(jid):heartbeat(now, worker, data) end QlessAPI.workers = function(now, worker) return cjson.encode(QlessWorker.counts(now, worker)) end QlessAPI.track = function(now, command, jid) return cjson.encode(Qless.track(now, command, jid)) end QlessAPI.tag = function(now, command, ...) return cjson.encode(Qless.tag(now, command, unpack(arg))) end QlessAPI.stats = function(now, queue, date) return cjson.encode(Qless.queue(queue):stats(now, date)) end QlessAPI.priority = function(now, jid, priority) return Qless.job(jid):priority(priority) end QlessAPI.log = function(now, jid, message, data) assert(jid, "Log(): Argument 'jid' missing") assert(message, "Log(): Argument 'message' missing") if data then data = assert(cjson.decode(data), "Log(): Argument 'data' not cjson: " .. tostring(data)) end local job = Qless.job(jid) assert(job:exists(), 'Log(): Job ' .. jid .. ' does not exist') job:history(now, message, data) end QlessAPI.peek = function(now, queue, count) local jids = Qless.queue(queue):peek(now, count) local response = {} for i, jid in ipairs(jids) do table.insert(response, Qless.job(jid):data()) end return cjson.encode(response) end QlessAPI.pop = function(now, queue, worker, count) local jids = Qless.queue(queue):pop(now, worker, count) local response = {} for i, jid in ipairs(jids) do table.insert(response, Qless.job(jid):data()) end return cjson.encode(response) end QlessAPI.pause = function(now, ...) return QlessQueue.pause(now, unpack(arg)) end QlessAPI.unpause = function(now, ...) return QlessQueue.unpause(unpack(arg)) end QlessAPI.cancel = function(now, ...) return Qless.cancel(now, unpack(arg)) end QlessAPI.timeout = function(now, ...) for _, jid in ipairs(arg) do Qless.job(jid):timeout(now) end end QlessAPI.put = function(now, me, queue, jid, klass, data, delay, ...) return Qless.queue(queue):put(now, me, jid, klass, data, delay, unpack(arg)) end QlessAPI.requeue = function(now, me, queue, jid, ...) local job = Qless.job(jid) assert(job:exists(), 'Requeue(): Job ' .. jid .. ' does not exist') return QlessAPI.put(now, me, queue, jid, unpack(arg)) end QlessAPI.unfail = function(now, queue, group, count) return Qless.queue(queue):unfail(now, group, count) end QlessAPI.recur = function(now, queue, jid, klass, data, spec, ...) return Qless.queue(queue):recur(now, jid, klass, data, spec, unpack(arg)) end QlessAPI.unrecur = function(now, jid) return Qless.recurring(jid):unrecur() end QlessAPI['recur.get'] = function(now, jid) local data = Qless.recurring(jid):data() if not data then return nil end return cjson.encode(data) end QlessAPI['recur.update'] = function(now, jid, ...) return Qless.recurring(jid):update(now, unpack(arg)) end QlessAPI['recur.tag'] = function(now, jid, ...) return Qless.recurring(jid):tag(unpack(arg)) end QlessAPI['recur.untag'] = function(now, jid, ...) return Qless.recurring(jid):untag(unpack(arg)) end QlessAPI.length = function(now, queue) return Qless.queue(queue):length() end QlessAPI['worker.deregister'] = function(now, ...) return QlessWorker.deregister(unpack(arg)) end QlessAPI['queue.forget'] = function(now, ...) QlessQueue.deregister(unpack(arg)) end QlessAPI['queue.throttle.get'] = function(now, queue) local data = Qless.throttle(QlessQueue.ns .. queue):data() if not data then return nil end return cjson.encode(data) end QlessAPI['queue.throttle.set'] = function(now, queue, max) Qless.throttle(QlessQueue.ns .. queue):set({maximum = max}, 0) end QlessAPI['throttle.set'] = function(now, tid, max, ...) local expiration = unpack(arg) local data = { maximum = max } Qless.throttle(tid):set(data, tonumber(expiration or 0)) end QlessAPI['throttle.get'] = function(now, tid) return cjson.encode(Qless.throttle(tid):data()) end QlessAPI['throttle.delete'] = function(now, tid) return Qless.throttle(tid):unset() end QlessAPI['throttle.locks'] = function(now, tid) return Qless.throttle(tid).locks.members() end QlessAPI['throttle.pending'] = function(now, tid) return Qless.throttle(tid).pending.members() end QlessAPI['throttle.ttl'] = function(now, tid) return Qless.throttle(tid):ttl() end QlessAPI['throttle.release'] = function(now, tid, ...) local throttle = Qless.throttle(tid) for _, jid in ipairs(arg) do throttle:release(now, jid) end end if #KEYS > 0 then error('No Keys should be provided') end local command_name = assert(table.remove(ARGV, 1), 'Must provide a command') local command = assert( QlessAPI[command_name], 'Unknown command ' .. command_name) local now = tonumber(table.remove(ARGV, 1)) local now = assert( now, 'Arg "now" missing or not a number: ' .. (now or 'nil')) return command(now, unpack(ARGV))
mit
liamneit/Cornucopia
Cornucopia/Libs/Sushi-3.0/Classes/Header.lua
1
2487
--[[ Copyright 2008-2015 João Cardoso Sushi is distributed under the terms of the GNU General Public License (or the Lesser GPL). This file is part of Sushi. Sushi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Sushi 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 Sushi. If not, see <http://www.gnu.org/licenses/>. --]] local CallHandler = SushiCallHandler local Header = MakeSushi(3, 'Frame', 'Header', nil, nil, CallHandler) if not Header then return end --[[ Events ]]-- function Header:OnCreate () local Text = self:CreateFontString() Text:SetPoint('TOPLEFT') Text:SetJustifyH('LEFT') local Underline = self:CreateTexture() Underline:SetPoint('BOTTOMRIGHT') Underline:SetPoint('BOTTOMLEFT') Underline:SetColorTexture(1,1,1, .2) Underline:SetHeight(1.2) self:SetScript('OnSizeChanged', self.OnSizeChanged) self.Underline = Underline self.Text = Text end function Header:OnAcquire () CallHandler.OnAcquire (self) self:SetCall('OnParentResize', self.OnParentResize) self:SetFont('GameFontNormal') self:SetUnderlined(nil) self:OnParentResize() self:SetText(nil) end function Header:OnSizeChanged () self.Text:SetWidth(self:GetWidth()) self:SetHeight(self.Text:GetHeight() + (self:IsUnderlined() and 3 or 0)) end function Header:OnParentResize () local parent = self:GetParent() if parent then self:SetWidth(parent:GetWidth() - 20) end end --[[ API ]]-- function Header:SetText (text) self.Text:SetText(text) self:OnSizeChanged() end function Header:GetText () return self.Text:GetText() end function Header:SetFont (font) self.Text:SetFontObject(font) self:OnSizeChanged() end function Header:GetFont () return self.Text:GetFontObject() end function Header:SetUnderlined (enable) if enable then self.Underline:Show() else self.Underline:Hide() end self:OnSizeChanged() end function Header:IsUnderlined () return self.Underline:IsShown() end --[[ Values ]]-- Header.SetLabel = Header.SetText Header.GetLabel = Header.GetText Header.bottom = 5 Header.right = 12 Header.left = 12 Header.top = 5
gpl-3.0
Blackdutchie/Zero-K
LuaUI/Widgets/gui_chili_keyboardmenu.lua
5
33932
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Chili Keyboard Menu", desc = "v0.035 Chili Keyboard Menu", author = "CarRepairer", date = "2012-03-27", license = "GNU GPL, v2 or later", layer = 9991, enabled = false, handler = true, } end ------------------------------------------------- local echo = Spring.Echo ------------------------------------------------ -- config include("keysym.h.lua") local common_commands, states_commands, factory_commands, econ_commands, defense_commands, special_commands, globalCommands, overrides, custom_cmd_actions = include("Configs/integral_menu_commands.lua") local build_menu_use = include("Configs/marking_menu_menus.lua") local initialBuilder = 'armcom1' ------------------------------------------------ -- Chili classes local Chili local Button local Label local Colorbars local Checkbox local Window local Panel local StackPanel local TextBox local Image local Progressbar local Control -- Chili instances local screen0 local window_main local tab_commands, tab_sels, tab_toggles local key_buttons = {} local key_button_images, tab_buttons ------------------------------------------------ -- keys local keyconfig = include("Configs/marking_menu_keys.lua") local keys = keyconfig.qwerty_d.keys local keys_display = keyconfig.qwerty_d.keys_display ------------------------------------------------ -- globals local curCommands = {} local selectedUnits = {} --radial build menu local advance_builder = false local builder_types = {} local builder_types_i = {} local builder_ids_i = {} local curbuilder = 1 local last_cmdid local build_menu = nil local build_menu_selected = nil local menu_level = 0 local customKeyBind = false local build_mode = false local green = '\255\1\255\1' local white = '\255\255\255\255' local red = '\255\255\001\001' local magenta_table = {0.8, 0, 0, 1} local white_table = {1,1,1, 1} local black_table = {0,0,0,1} local tabHeight = 15 local commandButtons = {} local updateCommandsSoon = false local lastCmd, lastColor local curTab = 'none' local keyRows = {} local unboundKeyList = {} local selections = { 'select_all', 'select_half', 'select_one', 'select_idleb', 'select_idleallb', 'select_nonidle', 'select_same', 'select_vissame', 'select_landw', 'selectairw', 'lowhealth', } --predeclared functions local function UpdateButtons() end local function UpdateBuildMenu() end local function StoreBuilders() end local function SetupKeybuttons() end ------------------------------------------------ -- options options_path = 'Settings/HUD Panels/KB Menu' options_order = { 'layout', 'sevenperrow', 'showGlobalCommands', 'goToCommands', 'goToSelections', 'opacity', 'old_menu_at_shutdown' } options = { layout = { name = 'Keyboard Layout', type = 'radioButton', OnChange = function(self) SetupKeybuttons() UpdateButtons() end, value = 'qwerty', items={ {key='qwerty', name='QWERTY', }, {key='qwertz', name='QWERTZ', }, {key='azerty', name='AZERTY', }, }, }, sevenperrow = { name = 'Rows of 7 keys', type = 'bool', desc = 'Each row has 7 keys instead of the 6 default.', OnChange = function(self) SetupKeybuttons() UpdateButtons() end, value = false, }, showGlobalCommands = { name = 'Show Global Commands', type = 'bool', value = false, advanced = true, }, goToCommands = { name = 'Commands...', type = 'button', OnChange = function(self) WG.crude.OpenPath('Game/Command Hotkeys') end }, goToSelections = { name = 'Selections...', type = 'button', OnChange = function(self) WG.crude.OpenPath('Game/Selection Hotkeys') end }, opacity = { name = "Opacity", type = "number", value = 0.4, min = 0, max = 1, step = 0.01, OnChange = function(self) window_main.color = {1,1,1,self.value}; window_main:Invalidate() end, }, old_menu_at_shutdown = { name = 'Reenable Spring Menu at Shutdown', desc = "Upon widget shutdown (manual or upon crash) reenable Spring's original command menu.", type = 'bool', advanced = true, value = true, }, } local function CapCase(str) local str = str:lower() str = str:gsub( '_', ' ' ) str = str:sub(1,1):upper() .. str:sub(2) str = str:gsub( ' (.)', function(x) return (' ' .. x):upper(); end ) return str end local function AddHotkeyOptions() local options_order_tmp_cmd = {} local options_order_tmp_cmd_instant = {} local options_order_tmp_states = {} for cmdname, number in pairs(custom_cmd_actions) do local cmdnamel = cmdname:lower() local cmdname_disp = CapCase(cmdname) options[cmdnamel] = { name = cmdname_disp, type = 'button', action = cmdnamel, path = 'Game/Command Hotkeys', } if number == 2 then options_order_tmp_states[#options_order_tmp_states+1] = cmdnamel --options[cmdnamel].isUnitStateCommand = true elseif number == 3 then options_order_tmp_cmd_instant[#options_order_tmp_cmd_instant+1] = cmdnamel --options[cmdnamel].isUnitInstantCommand = true else options_order_tmp_cmd[#options_order_tmp_cmd+1] = cmdnamel --options[cmdnamel].isUnitCommand = true end end options.lblcmd = { type='label', name='Targeted Commands', path = 'Game/Command Hotkeys',} options.lblcmdinstant = { type='label', name='Instant Commands', path = 'Game/Command Hotkeys',} options.lblstate = { type='label', name='State Commands', path = 'Game/Command Hotkeys',} table.sort(options_order_tmp_cmd) table.sort(options_order_tmp_cmd_instant) table.sort(options_order_tmp_states) options_order[#options_order+1] = 'lblcmd' for i=1, #options_order_tmp_cmd do options_order[#options_order+1] = options_order_tmp_cmd[i] end options_order[#options_order+1] = 'lblcmdinstant' for i=1, #options_order_tmp_cmd_instant do options_order[#options_order+1] = options_order_tmp_cmd_instant[i] end options_order[#options_order+1] = 'lblstate' for i=1, #options_order_tmp_states do options_order[#options_order+1] = options_order_tmp_states[i] end end AddHotkeyOptions() ---------------------------------------------------------------- -- Helper Functions -- [[ local function to_string(data, indent) local str = "" if(indent == nil) then indent = 0 end local indenter = " " -- Check the type if(type(data) == "string") then str = str .. (indenter):rep(indent) .. data .. "\n" elseif(type(data) == "number") then str = str .. (indenter):rep(indent) .. data .. "\n" elseif(type(data) == "boolean") then if(data == true) then str = str .. "true" else str = str .. "false" end elseif(type(data) == "table") then local i, v for i, v in pairs(data) do -- Check for a table in a table if(type(v) == "table") then str = str .. (indenter):rep(indent) .. i .. ":\n" str = str .. to_string(v, indent + 2) else str = str .. (indenter):rep(indent) .. i .. ": " .. to_string(v, 0) end end elseif(type(data) == "function") then str = str .. (indenter):rep(indent) .. 'function' .. "\n" else echo(1, "Error: unknown data type: %s", type(data)) end return str end --]] local function explode(div,str) if (div=='') then --return false local ret = {} local len = str:len() for i=1,len do local char = str:sub(i,i) ret[#ret+1] = char end return ret end local pos,arr = 0,{} -- for each divider found for st,sp in function() return string.find(str,div,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider pos = sp + 1 -- Jump past current divider end table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider return arr end local function CopyTable(outtable,intable) for i,v in pairs(intable) do if (type(v)=='table') then if (type(outtable[i])~='table') then outtable[i] = {} end CopyTable(outtable[i],v) else outtable[i] = v end end end ------------------------------------------------ --functions local function BuildPrev() if last_cmdid then Spring.SetActiveCommand(last_cmdid) end end -- layout handler - its needed for custom commands to work and to delete normal spring menu local function LayoutHandler(xIcons, yIcons, cmdCount, commands) widgetHandler.commands = commands widgetHandler.commands.n = cmdCount widgetHandler:CommandsChanged() local reParamsCmds = {} local customCmds = {} local cnt = 0 local AddCommand = function(command) local cc = {} CopyTable(cc,command ) cnt = cnt + 1 cc.cmdDescID = cmdCount+cnt if (cc.params) then if (not cc.actions) then --// workaround for params local params = cc.params for i=1,#params+1 do params[i-1] = params[i] end cc.actions = params end reParamsCmds[cc.cmdDescID] = cc.params end --// remove api keys (custom keys are prohibited in the engine handler) cc.pos = nil cc.cmdDescID = nil cc.params = nil customCmds[#customCmds+1] = cc end --// preprocess the Custom Commands for i=1,#widgetHandler.customCommands do AddCommand(widgetHandler.customCommands[i]) end for i=1,#globalCommands do AddCommand(globalCommands[i]) end Update() if (cmdCount <= 0) then return "", xIcons, yIcons, {}, customCmds, {}, {}, {}, {}, reParamsCmds, {} --prevent CommandChanged() from being called twice when deselecting all units (copied from ca_layout.lua) end return "", xIcons, yIcons, {}, customCmds, {}, {}, {}, {}, reParamsCmds, {[1337]=9001} end --LayoutHandler local function SetButtonColor(button, color) button.backgroundColor = color button:Invalidate() end local function ClearKeyButtons() for k, v in pairs( key_buttons ) do key_buttons[k]:SetCaption( '' ) key_buttons[k].OnClick = {} --key_buttons[k].OnMouseUp = {} key_buttons[k]:ClearChildren() key_buttons[k].tooltip = nil SetButtonColor( key_buttons[k], white_table ) end end ------------------------------------------------ --build menu functions local function AngleToKey(angle) angle=angle+0 if angle < 0 then angle = angle + 360 end local conv = { [0] = 'E', [45] = 'R', [90] = 'F', [135] = 'V', [180] = 'C', [225] = 'X', [270] = 'S', [315] = 'W', } return conv[angle] end local function KeyToAngle(index) local conv = { E = 0, R = 45, F = 90, V = 135, C = 180, X = 225, S = 270, W = 315, } return conv[index] end local function AddHotkeyLabel( key, text ) label = Label:New { width="100%"; height="100%"; autosize=false; align="left"; valign="top"; caption = green..text; fontSize = 11; fontShadow = true; parent = key_buttons[key]; } end local function CanInitialQueue() return WG.InitialQueue~=nil and not (Spring.GetGameFrame() > 0) end local function AddBuildButton(color) key_buttons['D']:AddChild( Label:New{ caption = 'BUIL'.. green ..'D', fontSize=14, bottom='1', fontShadow = true, } ) key_buttons['D']:AddChild( Image:New { file = builder_ids_i[curbuilder] and "#".. builder_ids_i[curbuilder], file2 = 'LuaUI/Images/nested_buildmenu/frame_Fac.png', width = '100%', height = '80%', } ) key_buttons['D'].OnClick = { function() MakeBuildMenu(); end } if color then SetButtonColor(key_buttons['D'], color) end end local function SetCurTab(tab) if curTab == tab then return end SetButtonColor(tab_buttons[curTab], white_table) curTab = tab SetButtonColor(tab_buttons[curTab], magenta_table) StoreBuilders(selectedUnits) UpdateButtons() end local function NextBuilder() if advance_builder then curbuilder = curbuilder % #builder_types_i + 1 end end local function BuildMode(enable) build_mode = enable if enable then curCommands = {} commandButtons = {} end end local function CommandFunction(cmdid, left,right) --local _,_,left,_,right = Spring.GetMouseState() local alt,ctrl,meta,shift = Spring.GetModKeyState() local index = Spring.GetCmdDescIndex(cmdid) if (left) then Spring.SetActiveCommand(index,1,left,right,alt,ctrl,meta,shift) end if (right) then Spring.SetActiveCommand(index,3,left,right,alt,ctrl,meta,shift) end end local function AddBuildStructureButtonBasic(unitName, hotkey_key, index ) local button1 = key_buttons[hotkey_key] local ud = UnitDefNames[unitName] button1.tooltip = 'Build: ' ..ud.humanName .. ' - ' .. ud.tooltip local label_hotkey if index then --local angle = KeyToAngle(index) AddHotkeyLabel( index, index ) end button1:AddChild( Image:New { file = "#"..ud.id, file2 = WG.GetBuildIconFrame(ud), keepAspect = false; width = '100%', height = '80%', }) button1:AddChild( Label:New{ caption = ud.metalCost .. ' m', height='20%', fontSize = 11, bottom=0, fontShadow = true, } ) button1.OnClick = { function (self, x, y, mouse) local left, right = mouse == 1, mouse == 3 CommandFunction( -(ud.id), left, right ); end } end local function AddBuildStructureButton(item, index) if not item then --grid_menu:AddChild(Label:New{caption=''}) return end local ud = UnitDefNames[item.unit] --[[ if not ud then grid_menu:AddChild(Label:New{caption=''}) return end --]] local func = function (self, x, y, mouse) --if menu_level ~= 0 then if menu_level ~= 0 or not item.items then --account for first level items without subitems local cmdid = build_menu_selected.cmd if (cmdid == nil) then local ud = UnitDefNames[item.unit] if (ud ~= nil) then cmdid = Spring.GetCmdDescIndex(-ud.id) end end if (cmdid) then local alt, ctrl, meta, shift = Spring.GetModKeyState() --local _, _, left, _, right = Spring.GetMouseState() local left, right = mouse == 1, mouse == 3 if (build_menu ~= build_menu_selected) then -- store last item and menu_level to render its back path menu_level = menu_level + 1 -- save menu_level end Spring.SetActiveCommand(cmdid, 1, left, right, alt, ctrl, meta, shift) last_cmdid = cmdid end --BuildMode(false) end if (item.items ~= nil) then -- item has subitems menu_level = menu_level + 1 -- save menu_level build_menu = item build_menu_selected = item UpdateBuildMenu() -- fixme - check this end advance_builder = false end local tooltip1 = (menu_level ~= 0) and ('Build: ' ..ud.humanName .. ' - ' .. ud.tooltip) or ('Category: ' .. item.label) local button1 = key_buttons[index] --button1.OnMouseDown = { function() BuildMode(false); end } button1.OnClick = { func } button1.tooltip = tooltip1 if menu_level == 0 and item.label then button1:AddChild( Label:New{ caption = item.label, fontSize = 11, bottom=0, fontShadow = true, } ) end local label_hotkey if index then --local angle = KeyToAngle(index) AddHotkeyLabel( index, index ) end button1:AddChild( Image:New { file = "#"..ud.id, file2 = WG.GetBuildIconFrame(ud), keepAspect = false; width = '100%', height = '80%', }) if menu_level ~= 0 then button1:AddChild( Label:New{ caption = ud.metalCost .. ' m', height='20%', fontSize = 11, bottom=0, fontShadow = true, } ) end end UpdateBuildMenu = function() ClearKeyButtons() if not build_menu then return end local temptree = {} if (build_menu.items) then --if true then --local items = build_menu.items or {} local items = build_menu.items if build_menu.angle then local index = AngleToKey(build_menu.angle) temptree[index] = build_menu end for _,i in ipairs(items) do local index = AngleToKey(i.angle) temptree[index] = i end local buildKeys = 'WERSDFXCV' local buildKeysLen = buildKeys:len() for i=1,buildKeysLen do local key = buildKeys:sub(i,i) if key == 'D' then AddBuildButton(magenta_table) else AddBuildStructureButton(temptree[key], key) end end end end -- setup menu depending on selected unit(s) local function SetupBuilderMenuData() build_menu = nil build_menu_selected = nil local buildername = builder_types_i[curbuilder] if CanInitialQueue() then buildername = initialBuilder end if buildername then menu_level = 0 build_menu = build_menu_use[buildername] build_menu_selected = build_menu end UpdateBuildMenu() end MakeBuildMenu = function() NextBuilder() advance_builder = true SetupBuilderMenuData() if build_menu then BuildMode(true) end end StoreBuilders = function(units) builder_types = {} builder_types_i = {} builder_ids_i = {} curbuilder = 1 for _, unitID in ipairs(units) do local ud = UnitDefs[Spring.GetUnitDefID(unitID)] if ud and ud.isBuilder and build_menu_use[ud.name] then if not builder_types[ud.name] then builder_types[ud.name] = true builder_types_i[#builder_types_i + 1] = ud.name builder_ids_i[#builder_ids_i + 1] = ud.id end end end end --------- local function AddCustomCommands(selectedUnits) if CanInitialQueue() then selectedUnits = {'a'} end for _, unitID in ipairs(selectedUnits) do local ud if CanInitialQueue() then ud = UnitDefNames[initialBuilder] else ud = UnitDefs[Spring.GetUnitDefID(unitID)] end if ud and ud.isBuilder and build_menu_use[ud.name] then table.insert(widgetHandler.customCommands, { id = CMD_RADIALBUILDMENU, name = 'Build', type = CMDTYPE.ICON, tooltip = 'Build a structure.', cursor = 'Repair', action = 'radialbuildmenu', params = { }, --texture = 'LuaUI/Images/commands/Bold/retreat.png', pos = {CMD.MOVE_STATE,CMD.FIRE_STATE, }, }) table.insert(widgetHandler.customCommands, { id = CMD_BUILDPREV, name = 'Build Previous', type = CMDTYPE.ICON, tooltip = 'Build the previous structure.', cursor = 'Repair', action = 'buildprev', params = { }, pos = {CMD.MOVE_STATE,CMD.FIRE_STATE, }, }) end end end local function SetupTabs() tab_buttons = {} local tabs = { none = 'Commands', ctrl = 'Selection '..green..'(Ctrl)', alt = 'States ' ..green..'(Alt)', meta = green..'(Spacebar)', unbound = 'Other', } local tabs_i = { 'none', 'ctrl', 'alt', 'meta', 'unbound' } tabCount = #tabs_i for i, tab in ipairs(tabs_i) do local data = tabs[tab] local caption = data local width = (100 / tabCount) tab_buttons[tab] = Button:New{ parent = window_main, --name = '', caption = caption, --tooltip = '', backgroundColor = white_table, OnClick = { function() SetCurTab(tab) BuildMode(false) end }, x = (width * (i-1)) .. '%', bottom = 0, width = width .. '%', height = tabHeight .. '%', } end SetCurTab('none') end SetupKeybuttons = function() for _, button in pairs( key_buttons ) do button:Dispose() end key_buttons = {} key_button_images = {} if options.layout.value == 'qwertz' then keyRows = options.sevenperrow.value and { 'QWERTZU', 'ASDFGHJ', 'YXCVBNM' } or { 'QWERTZ', 'ASDFGH', 'YXCVBN' } elseif options.layout.value == 'azerty' then keyRows = options.sevenperrow.value and { 'AZERTYU', 'QSDFGHJ', 'WXCVBN,' } or { 'AZERTY', 'QSDFGH', 'WXCVBN' } else keyRows = options.sevenperrow.value and { 'QWERTYU', 'ASDFGHJ', 'ZXCVBNM' } or { 'QWERTY', 'ASDFGH', 'ZXCVBN' } end local width, height height = window_main.height local ratio = (keyRows[1]:len() + 0.8) / (3 + 0.5) width = ratio * height window_main:Resize(width, height) local rows = keyRows local colnum = 0 local offset_perc = 4 for _, row in ipairs(rows) do local row_length = row:len() for rownum=1,row_length do local key = row:sub(rownum,rownum) local button_width_perc = (100 - offset_perc * (#rows-1) ) / row_length local button_height_perc = (100 - tabHeight) / #rows local x = ((rownum-1) * button_width_perc + offset_perc * colnum) .. '%' local y = colnum * button_height_perc .. '%' local width = button_width_perc .. '%' local height = button_height_perc .. '%' -- [[ local color = {1,1,1,1} if ({Y=1,H=1,N=1})[key] then color = {0,0,0,0.6} end --]] key_buttons[key] = Button:New{ parent = window_main, caption = '-', backgroundColor = color, x = x, y = y, width = width, height = height, } end colnum = colnum + 1 end local unboundKeys = table.concat( keyRows ) unboundKeyList = explode( '', unboundKeys ) end --sorts commands into categories local function ProcessCommand(cmd) if not cmd.hidden and cmd.id ~= CMD.PAGES then if (cmd.type == CMDTYPE.ICON_MODE and cmd.params ~= nil and #cmd.params > 1) then curCommands[#curCommands+1] = cmd elseif common_commands[cmd.id] then curCommands[#curCommands+1] = cmd --elseif factory_commands[cmd.id] then --elseif econ_commands[cmd.id] then --elseif defense_commands[cmd.id] then elseif special_commands[cmd.id] then --curently terraform curCommands[#curCommands+1] = cmd elseif UnitDefs[-(cmd.id)] then curCommands[#curCommands+1] = cmd else curCommands[#curCommands+1] = cmd end end end local function UpdateButton( hotkey_key, hotkey, name, fcn, tooltip, texture, color ) key_buttons[hotkey_key].OnClick = { fcn } key_buttons[hotkey_key].tooltip = tooltip AddHotkeyLabel( hotkey_key, hotkey ) if texture and texture ~= "" then if type(texture) == 'table' then texture = texture[1] end local image = Image:New { width="90%"; height= "90%"; bottom = nil; y="5%"; x="5%"; keepAspect = true, file = texture; parent = key_buttons[hotkey_key]; } else --key_buttons[hotkey_key]:SetCaption( name:gsub(' ', '\n') ) end key_buttons[hotkey_key]:SetCaption( name and name:gsub(' ', '\n') or '' ) if color then SetButtonColor(key_buttons[hotkey_key], color) end end local function BreakDownHotkey(hotkey) local hotkey_len = hotkey:len() local hotkey_key = hotkey:sub(hotkey_len, hotkey_len) local hotkey_mod = hotkey:lower():find('ctrl') and 'ctrl' or hotkey:lower():find('alt') and 'alt' or hotkey:lower():find('meta') and 'meta' or '' return hotkey_key, hotkey_mod end local function SetupCommands( modifier ) --AddCustomCommands(Spring.GetSelectedUnits()) BuildMode(false) local commands = widgetHandler.commands local customCommands = widgetHandler.customCommands curCommands = {} commandButtons = {} -- [=[ for i = 1, #commands do ProcessCommand(commands[i]) end for i = 1, #customCommands do ProcessCommand(customCommands[i]) end for i = 1, #globalCommands do ProcessCommand(globalCommands[i]) end --]=] ClearKeyButtons() if modifier == 'none' then modifier = ''; end --moved to SetupKeybuttons --local unboundKeys = table.concat( keyRows ) --local unboundKeyList = explode( '', unboundKeys ) local unboundKeyIndex = 1 local ignore = {} -- [=[ if options.showGlobalCommands.value then for letterInd=1,26 do local letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' local letter = letters:sub(letterInd, letterInd) local hotkey_key = letter local actions local modifiers = {'', 'ctrl', 'alt', 'meta'} for j=1,#modifiers do local modifier2 = modifiers[j] local modifierKb = (modifier2 ~= '') and (modifier2 .. '+') or '' actions = Spring.GetKeyBindings(modifierKb .. hotkey_key) --if not ignore[hotkey_key] and actions and #actions > 0 then if actions and #actions > 0 then for i=1,#actions do local actionData = actions[i] local actionCmd,actionExtra = actionData.command, actionData.extra if not(actionCmd) then actionCmd,actionExtra = next(actionData) end assert(actionCmd) local buildCommand = actionCmd:find('buildunit_') if not custom_cmd_actions[ actionCmd ] and actionCmd ~= 'radialbuildmenu' and not buildCommand then local actionOption = WG.crude.GetActionOption(actionCmd) local actionName = actionOption and actionOption.name local actionDesc = actionOption and actionOption.desc local label = actionName or actionCmd local tooltip = actionDesc or (label .. ' ' .. actionExtra) local action = actionExtra and actionExtra ~= '' and actionCmd .. ' ' .. actionExtra or actionCmd if label == 'luaui' then label = actionExtra end --create fake command and add it to list curCommands[#curCommands+1] = { type = '', id = 99999, name = label, tooltip = tooltip, action = action, } end end end end end --for letterInd=1,26 end --if options.showGlobalCommands.value --]=] -- [=[ --for i, cmd in ipairs( curCommands ) do for i = 1, #curCommands do local cmd = curCommands[i] local hotkey = cmd.action and WG.crude.GetHotkey(cmd.action) or '' local hotkey_key, hotkey_mod = BreakDownHotkey(hotkey) --echo(CMD[cmd.id], cmd.name, hotkey_key, hotkey_mod) if not ignore[hotkey_key] then if ( (modifier == 'unbound' and hotkey_key == '') or not key_buttons[hotkey_key] ) and cmd.type ~= CMDTYPE.NEXT and cmd.type ~= CMDTYPE.PREV and cmd.id >= 0 and cmd.id ~= CMD_RADIALBUILDMENU then if unboundKeyList[unboundKeyIndex] then hotkey_key = unboundKeyList[unboundKeyIndex] hotkey_mod = 'unbound' unboundKeyIndex = unboundKeyIndex + 1 end end if modifier == '' and cmd.id == CMD_RADIALBUILDMENU then AddBuildButton() ignore['D'] = true elseif hotkey_mod == modifier and key_buttons[hotkey_key] then local override = overrides[cmd.id] -- command overrides local texture = override and override.texture or cmd.texture local isState = (cmd.type == CMDTYPE.ICON_MODE and #cmd.params > 1) or states_commands[cmd.id] --is command a state toggle command? if isState and override then texture = override.texture[cmd.params[1]+1] end local _,cmdid,_,cmdname = Spring.GetActiveCommand() local color = cmd.disabled and black_table if cmd.id == cmdid then color = magenta_table end local label = cmd.name if texture and texture ~= '' then label = '' end if cmd.name == 'Morph' or cmd.name == red .. 'Stop' then hotkey = cmd.name end if cmd.id < 0 then AddBuildStructureButtonBasic( cmd.name, hotkey_key, hotkey ) else if cmd.id == 99999 then UpdateButton( hotkey_key, hotkey, label, function() Spring.SendCommands( cmd.action ); end, cmd.tooltip, texture, color ) else UpdateButton( hotkey_key, hotkey, label, function (self, x, y, mouse) local left, right = mouse == 1, mouse == 3 CommandFunction( cmd.id, left, right ); end, cmd.tooltip, texture, color ) end end ignore[hotkey_key] = true end commandButtons[cmd.id] = key_buttons[hotkey_key] end --if not ignore[hotkey_key] then end --for i = 1, #curCommands do --]=] -- [=[ --for i, selection in ipairs(selections) do for i = 1, #selections do local selection = selections[i] --local option = options[selection] local option = WG.GetWidgetOption( 'Select Keys','Game/Selection Hotkeys', selection ) --returns empty table if problem if option.action then local hotkey = WG.crude.GetHotkey(option.action) or '' local hotkey_key, hotkey_mod = BreakDownHotkey(hotkey) --echo(option.action, hotkey_key, hotkey_mod) if hotkey_mod == modifier and key_buttons[hotkey_key] then local override = overrides[selection] -- command overrides local texture = override and override.texture UpdateButton( hotkey_key, hotkey, option.name, function() Spring.SendCommands(option.action) end, option.tooltip, texture ) ignore[hotkey_key] = true end end end --]=] end --SetupCommands UpdateButtons = function() SetupCommands( curTab ) end ------------------------------------------------ --callins function widget:Initialize() widgetHandler:ConfigLayoutHandler(LayoutHandler) Spring.ForceLayoutUpdate() widget:SelectionChanged(Spring.GetSelectedUnits()) -- setup Chili Chili = WG.Chili Button = Chili.Button Label = Chili.Label Colorbars = Chili.Colorbars Checkbox = Chili.Checkbox Window = Chili.Window Panel = Chili.Panel StackPanel = Chili.StackPanel TextBox = Chili.TextBox Image = Chili.Image Progressbar = Chili.Progressbar Control = Chili.Control screen0 = Chili.Screen0 -- setup chili controls window_main = Window:New{ parent = screen0, dockable = true, name = "keyboardmenu", x=200,y=300, width = 400, height = 220, padding = {5,5,5,5}, draggable = false, tweakDraggable = true, resizable = false, tweakResizable = true, dragUseGrip = false, fixedRatio = true, color = {1,1,1,options.opacity.value}, } local configButton = Button:New{ parent = window_main, caption = '', tooltip = 'Configure Hotkeys', backgroundColor = white_table, OnClick = { function() WG.crude.OpenPath('Settings/HUD Panels/KB Menu') WG.crude.ShowMenu() --make epic Chili menu appear. end }, bottom = tabHeight .. '%', x = 0, width = (tabHeight/2) .. '%', height = tabHeight.. '%', } local image = Image:New { width="100%", height= "100%", --bottom = nil, --y="5%"; x="5%", keepAspect = true, file = 'LuaUI/Images/epicmenu/settings.png', parent = configButton, } SetupKeybuttons() SetupTabs() widgetHandler.AddAction = function (_, cmd, func, data, types) return widgetHandler.actionHandler:AddAction(widget, cmd, func, data, types) end widgetHandler.RemoveAction = function (_, cmd, types) return widgetHandler.actionHandler:RemoveAction(widget, cmd, types) end widgetHandler:AddAction("radialbuildmenu", MakeBuildMenu, nil, "t") if not customKeyBind then Spring.SendCommands("bind d radialbuildmenu") end widgetHandler:AddAction("buildprev", BuildPrev, nil, "t") if not customKeyBind then --Spring.SendCommands("bind d buildprev") end end function widget:Shutdown() widgetHandler:ConfigLayoutHandler(options.old_menu_at_shutdown.value) --true: activate Default menu, false: activate dummy (empty) menu, nil: disable menu & CommandChanged() callins . See Layout.lua Spring.ForceLayoutUpdate() if not customKeyBind then Spring.SendCommands("unbind d radialbuildmenu") end widgetHandler:RemoveAction("radialbuildmenu") if not customKeyBind then --Spring.SendCommands("unbind d buildprev") end widgetHandler:RemoveAction("buildprev") end function widget:KeyPress(key, modifier) if build_mode then if not build_menu or key == KEYSYMS.ESCAPE then -- cancel menu BuildMode(false) return true end if modifier.shift then return false end local angle = keys[key] if angle == nil then return end --local index = AngleToIndex(angle) local index = AngleToKey(angle) --local pressbutton = grid_menu:GetChildByName(index+0) local pressbutton = key_buttons[index] if pressbutton then if #(pressbutton.OnClick) > 0 then pressbutton.OnClick[1]() end return true end end if key == KEYSYMS.LCTRL or key == KEYSYMS.RCTRL then SetCurTab('ctrl') elseif key == KEYSYMS.LALT or key == KEYSYMS.RALT then SetCurTab('alt') elseif key == KEYSYMS.LMETA or key == KEYSYMS.RMETA or key == KEYSYMS.SPACE then SetCurTab('meta') end end function widget:KeyRelease(key) if build_mode then return end if key == KEYSYMS.LCTRL or key == KEYSYMS.RCTRL or key == KEYSYMS.LALT or key == KEYSYMS.LALT or key == KEYSYMS.LMETA or key == KEYSYMS.RMETA or key == KEYSYMS.SPACE then local alt, ctrl, meta, shift = Spring.GetModKeyState() SetCurTab( ctrl and 'ctrl' or alt and 'alt' or meta and 'meta' or 'none' ) end end function widget:MousePress(x,y,button) if build_mode and button == 3 then UpdateButtons() Spring.SetActiveCommand(0) BuildMode(false) return true end end --local selectionHasChanged function widget:SelectionChanged(sel) --echo('selchanged') selectedUnits = sel --selectionHasChanged = true -- updating here causes error because commandchanged needs to find whether unit is builder or not end function widget:CommandsChanged() --echo ('commands changed') -- updating here causes async error when clearing hotkey labels, two commandschanged occur at once AddCustomCommands(selectedUnits) updateCommandsSoon = true end -- this is needed to highlight active command function widget:DrawScreen() local _,cmdid,_,cmdname = Spring.GetActiveCommand() if cmdid ~= lastCmd then if cmdid and commandButtons[cmdid] then local button = commandButtons[cmdid] lastColor = button.backgroundColor SetButtonColor(button, magenta_table) end if lastCmd ~= nil and commandButtons[lastCmd] then local button = commandButtons[lastCmd] SetButtonColor(button, lastColor) end lastCmd = cmdid end end local timer = 0 function widget:Update() --no param, see below local s = Spring.GetLastUpdateSeconds() -- needed because of Update() call in this function timer = timer + s if timer > 0.5 then timer = 0 --updating here seems to solve the issue if the widget layer is sufficiently large if updateCommandsSoon then updateCommandsSoon = false StoreBuilders(selectedUnits) if not( build_mode and #builder_ids_i > 0 ) then UpdateButtons() end --selectionHasChanged = false end end end function widget:CommandNotify(cmdID, cmdParams, cmdOptions) if cmdID == CMD_RADIALBUILDMENU then MakeBuildMenu() return true elseif cmdID == CMD_BUILDPREV then BuildPrev() return true elseif cmdID < 0 then UpdateButtons() end end
gpl-2.0
thurt/arangodb
3rdParty/V8-4.3.61/tools/gcmole/gccause.lua
157
2313
-- Copyright 2011 the V8 project authors. All rights reserved. -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are -- met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above -- copyright notice, this list of conditions and the following -- disclaimer in the documentation and/or other materials provided -- with the distribution. -- * Neither the name of Google Inc. nor the names of its -- contributors may be used to endorse or promote products derived -- from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- This is an auxiliary tool that reads gccauses file generated by -- gcmole.lua and prints tree of the calls that can potentially cause a GC -- inside a given function. -- -- Usage: lua tools/gcmole/gccause.lua <function-name-pattern> -- assert(loadfile "gccauses")() local P = ... local T = {} local function TrackCause(name, lvl) io.write((" "):rep(lvl or 0), name, "\n") if GC[name] then local causes = GC[name] for i = 1, #causes do local f = causes[i] if not T[f] then T[f] = true TrackCause(f, (lvl or 0) + 1) end if f == '<GC>' then break end end end end for name, _ in pairs(GC) do if name:match(P) then T = {} TrackCause(name) end end
apache-2.0
Dyelan/API-Rues
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-2.0
Blackdutchie/Zero-K
effects/lasers.lua
5
34173
-- gatorlaserflash -- flash1red2 -- flashlazer -- lasers_sparks1 -- lasers_melt1 -- flash1orange -- comlaserflash -- flash1purple -- lasers_melt3 -- flash1blue -- flash1green -- flash1red -- lasers_melt2 -- lasers_sparksr1 -- flash1yellow -- flash1white -- coregreen return { ["gatorlaserflash"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 1, flashalpha = 0.9, flashsize = 10.5, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, sparkage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_SPARKS1]], pos = [[0, 0, 0]], }, }, }, ["flash1red2"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 1, flashalpha = 0.9, flashsize = 20, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, sparkage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_SPARKSR1]], pos = [[0, 0, 0]], }, }, }, ["flashlazer"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.4, flashsize = 12, ttl = 120, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0,0,1]], dir = [[-1 r2,-1 r2,-1 r2]], length = 7.5, width = 15, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["lasers_sparks1"] = { sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["lasers_melt1"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.6, flashsize = 3.5, ttl = 40, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, }, ["flash1orange"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 1, [2] = 0.25, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[1,0.25,0]], dir = [[-1 r2,-1 r2,-1 r2]], length = 3, width = 5, lengthGrowth = 0.1, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 40, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["comlaserflash"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 13, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1,0,0]], dir = [[-5 r10,-5 r10,-5 r10]], length = 6, width = 2, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 7.5, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1purple"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 0.6, [2] = 0.2, [3] = 0.4, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0.6, 0.2, 0.41]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 40, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["lasers_melt3"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.6, flashsize = 6, ttl = 80, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1,0,0]], dir = [[-5 r10,-5 r10,-5 r10]], length = 6, width = 2, }, }, }, ["flash1blue"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 20, ttl = 3, color = { [1] = 0, [2] = 0, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0,0,1]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1bluedark"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 20, ttl = 3, color = { [1] = 0, [2] = 0, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0,0,1]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 4, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1green"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 15, ttl = 3, color = { [1] = 0, [2] = 1, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, }, ["flash2purple"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 15, ttl = 3, color = { [1] = 0.6, [2] = 0, [3] = 0.7, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0.4,0,0.5]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 10, particlelife = 10, particlelifespread = 2, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1red"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 1, flashalpha = 0.9, flashsize = 20, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1,0,0]], dir = [[-5 r10,-5 r10,-5 r10]], length = 6, width = 2, }, }, sparkage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_SPARKS1]], pos = [[0, 0, 0]], }, }, }, ["lasers_melt2"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.6, flashsize = 6, ttl = 80, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, }, ["lasers_sparksr1"] = { sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 5, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1yellow"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 1, [2] = 1, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 15, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1white"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 1, [2] = 1, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 15, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["coregreen"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 30, ttl = 5, color = { [1] = 0, [2] = 1, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[0,1,0]], dir = [[-7 r14,-7 r14,-7 r14]], length = 16, width = 6, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 80, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1teal"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 0.2, [2] = 0.5, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 15, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flashslow"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 0.5, flashsize = 25, ttl = 10, color = { [1] = 0.6, [2] = 0, [3] = 0.7, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:SLOW_MELT]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0.4,0,0.5]], dir = [[-1 r2,-1 r2,-1 r2]], length = 4, width = 8, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1.0 0.2 1.0 0.01 0.9 0.3 0.9 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 5, particlelife = 7, particlelifespread = 3, particlesize = 6, particlesizespread = 2.5, particlespeed = 4, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["slow_melt"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.4, flashsize = 6, ttl = 80, color = { [1] = 1, [2] = 0.0, [3] = 1, }, }, }, ["flashslowwithsparks"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 0.5, flashsize = 25, ttl = 10, color = { [1] = 0.6, [2] = 0, [3] = 0.7, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:SLOW_MELT]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.04, color = [[0.4,0,0.5]], dir = [[-1 r2,-1 r2,-1 r2]], length = 4, width = 8, }, }, sparks_purple = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1.0 0.2 1.0 0.01 0.9 0.3 0.9 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 5, particlelife = 8, particlelifespread = 3, particlesize = 6, particlesizespread = 2.5, particlespeed = 4, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, sparks_yellow = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 10, particlelife = 18, particlelifespread = 2, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, }
gpl-2.0
jjimenezg93/ai-behaviours
esqueleto/sample/test.lua
1
1276
MOAISim.openWindow("game", 1024, 768) viewport = MOAIViewport.new() viewport:setSize (1024, 768) viewport:setScale (1024, -768) layer = MOAILayer2D.new() layer:setViewport(viewport) MOAISim.pushRenderPass(layer) texture_name = "dragon.png" gfxQuad = MOAIGfxQuad2D.new() gfxQuad:setTexture(texture_name) char_size = 64 gfxQuad:setRect(-char_size/2, -char_size/2, char_size/2, char_size/2) gfxQuad:setUVRect(0, 0, 1, 1) prop = MOAIProp2D.new() prop:setDeck(gfxQuad) entity = Character.new() -- Add prop to be the renderable for this character entity:setProp(prop, layer) -- Start the character (allow calls to OnUpdate) entity:start() entity:setLoc(-350, -300) entity:setRot(180) entity:setLinearVel(60, 50) entity:setAngularVel(30) -- Enable Debug Draw debug = MOAIDrawDebug.get(); layer:setDrawDebug(debug) -- Add this character to draw debug MOAIDrawDebug.insertEntity(entity) mouseX = 0 mouseY = 0 function onClick(down) entity:setLoc(mouseX, mouseY) --entity:setTarget(mouseX, mouseY) --entity:setRot(-135) --entity:setLinearVel(0, 0) --entity:setAngularVel(0) end function pointerCallback(x, y) mouseX, mouseY = layer:wndToWorld(x, y) end MOAIInputMgr.device.mouseLeft:setCallback(onClick) MOAIInputMgr.device.pointer:setCallback(pointerCallback)
mit
alireza1998/gfx2
plugins/anti-procrastination.lua
1
1176
-- Spam / Procrastination check -- Admonish someone if he sends more than N_MESSAGES messages in TIME_INTERVAL -- Useful for group chats, particulary work chats and similar local TIME_INTERVAL = 180 -- seconds local N_MESSAGES = 4 function store_message(msg) key = 'chat:'..msg.to.id..':flood:'..msg.from.id..':'..msg.date redis:setex(key, TIME_INTERVAL, msg.text) end function run(msg, matches) if not msg.to.type == 'chat' then return nil end local datetime = os.date("*t", msg.date) if (datetime.wday-1) % 6 == 0 or datetime.hour >= 18 or datetime.hour < 9 or (datetime.hour >= 13 and datetime.hour < 14) then return nil end store_message(msg) key = 'chat:'..msg.to.id..':flood:'..msg.from.id messages = redis:keys(key..':*') if #messages >= N_MESSAGES then for i, key in ipairs(messages) do redis:del(key) end local sender = get_name(msg) return sender:gsub("^%l", string.upper) .. ' stop messaging and get back to work!' end return false end return { description = "Call out people sending too many messages in a short time", patterns = { "." }, run = run }
gpl-2.0
protomech/epgp-dkp-reloaded
libs/AceGUI-3.0/widgets/AceGUIWidget-ColorPicker.lua
24
5432
--[[----------------------------------------------------------------------------- ColorPicker Widget -------------------------------------------------------------------------------]] local Type, Version = "ColorPicker", 22 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local pairs = pairs -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: ShowUIPanel, HideUIPanel, ColorPickerFrame, OpacitySliderFrame --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] local function ColorCallback(self, r, g, b, a, isAlpha) if not self.HasAlpha then a = 1 end self:SetColor(r, g, b, a) if ColorPickerFrame:IsVisible() then --colorpicker is still open self:Fire("OnValueChanged", r, g, b, a) else --colorpicker is closed, color callback is first, ignore it, --alpha callback is the final call after it closes so confirm now if isAlpha then self:Fire("OnValueConfirmed", r, g, b, a) end end end --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function ColorSwatch_OnClick(frame) HideUIPanel(ColorPickerFrame) local self = frame.obj if not self.disabled then ColorPickerFrame:SetFrameStrata("FULLSCREEN_DIALOG") ColorPickerFrame:SetFrameLevel(frame:GetFrameLevel() + 10) ColorPickerFrame:SetClampedToScreen(true) ColorPickerFrame.func = function() local r, g, b = ColorPickerFrame:GetColorRGB() local a = 1 - OpacitySliderFrame:GetValue() ColorCallback(self, r, g, b, a) end ColorPickerFrame.hasOpacity = self.HasAlpha ColorPickerFrame.opacityFunc = function() local r, g, b = ColorPickerFrame:GetColorRGB() local a = 1 - OpacitySliderFrame:GetValue() ColorCallback(self, r, g, b, a, true) end local r, g, b, a = self.r, self.g, self.b, self.a if self.HasAlpha then ColorPickerFrame.opacity = 1 - (a or 0) end ColorPickerFrame:SetColorRGB(r, g, b) ColorPickerFrame.cancelFunc = function() ColorCallback(self, r, g, b, a, true) end ShowUIPanel(ColorPickerFrame) end AceGUI:ClearFocus() end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetHeight(24) self:SetWidth(200) self:SetHasAlpha(false) self:SetColor(0, 0, 0, 1) self:SetDisabled(nil) self:SetLabel(nil) end, -- ["OnRelease"] = nil, ["SetLabel"] = function(self, text) self.text:SetText(text) end, ["SetColor"] = function(self, r, g, b, a) self.r = r self.g = g self.b = b self.a = a or 1 self.colorSwatch:SetVertexColor(r, g, b, a) end, ["SetHasAlpha"] = function(self, HasAlpha) self.HasAlpha = HasAlpha end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if self.disabled then self.frame:Disable() self.text:SetTextColor(0.5, 0.5, 0.5) else self.frame:Enable() self.text:SetTextColor(1, 1, 1) end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Button", nil, UIParent) frame:Hide() frame:EnableMouse(true) frame:SetScript("OnEnter", Control_OnEnter) frame:SetScript("OnLeave", Control_OnLeave) frame:SetScript("OnClick", ColorSwatch_OnClick) local colorSwatch = frame:CreateTexture(nil, "OVERLAY") colorSwatch:SetWidth(19) colorSwatch:SetHeight(19) colorSwatch:SetTexture("Interface\\ChatFrame\\ChatFrameColorSwatch") colorSwatch:SetPoint("LEFT") local texture = frame:CreateTexture(nil, "BACKGROUND") texture:SetWidth(16) texture:SetHeight(16) texture:SetTexture(1, 1, 1) texture:SetPoint("CENTER", colorSwatch) texture:Show() local checkers = frame:CreateTexture(nil, "BACKGROUND") checkers:SetWidth(14) checkers:SetHeight(14) checkers:SetTexture("Tileset\\Generic\\Checkers") checkers:SetTexCoord(.25, 0, 0.5, .25) checkers:SetDesaturated(true) checkers:SetVertexColor(1, 1, 1, 0.75) checkers:SetPoint("CENTER", colorSwatch) checkers:Show() local text = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight") text:SetHeight(24) text:SetJustifyH("LEFT") text:SetTextColor(1, 1, 1) text:SetPoint("LEFT", colorSwatch, "RIGHT", 2, 0) text:SetPoint("RIGHT") --local highlight = frame:CreateTexture(nil, "HIGHLIGHT") --highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight") --highlight:SetBlendMode("ADD") --highlight:SetAllPoints(frame) local widget = { colorSwatch = colorSwatch, text = text, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
bsd-3-clause
AmyBSOD/ToME-SX
src/lua/code.lua
1
1739
-- tolua: code class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1999 -- $Id: code.lua,v 1.2 2001/11/26 23:00:23 darkgod Exp $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Code class -- Represents Lua code to be compiled and included -- in the initialization function. -- The following fields are stored: -- text = text code classCode = { text = '', _base = classFeature, } settag(classCode,tolua_tag) -- register code function classCode:register () -- clean Lua code local s = clean(self.text) if not s then error("parser error in embedded code") end -- convert to C output('\n { /* begin embedded lua code */\n') output(' static unsigned char B[] = {\n ') local t={n=0} local b = gsub(s,'(.)',function (c) local e = '' %t.n=%t.n+1 if %t.n==15 then %t.n=0 e='\n ' end return format('%3u,%s',strbyte(c),e) end ) output(b..strbyte(" ")) output('\n };\n') output(' lua_dobuffer(tolua_S,(char*)B,sizeof(B),"tolua: embedded Lua code");') output(' } /* end of embedded lua code */\n\n') end -- Print method function classCode:print (ident,close) print(ident.."Code{") print(ident.." text = [["..self.text.."]],") print(ident.."}"..close) end -- Internal constructor function _Code (t) t._base = classCode settag(t,tolua_tag) append(t) return t end -- Constructor -- Expects a string representing the code text function Code (l) return _Code { text = l } end
gpl-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/lore/age-pyre.lua
1
1447
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org -------------------------------------------------------------------------- -- Age of Pyre -------------------------------------------------------------------------- newLore{ id = "broken-atamathon", category = "age of pyre", name = "Atamathon, the giant golem", lore = [[This giant golem was constructed by the Halflings during the Pyre Wars to fight the orcs, but was felled by Garkul the Devourer. Its body is made of marble, its joints of solid voratun, and its eyes of purest ruby. One of its eyes seems to be missing. At over 40 feet high it towers above you. Someone foolish has tried to reconstruct it, but it seems like it misses an eye to be completed.]] }
gpl-3.0
donat-b/The-Powder-Toy
src/luascripts/scriptmanager.lua
1
39709
--Cracker64's Autorun Script Manager --The autorun to end all autoruns --Version 3.5 --TODO: --manual file addition (that can be anywhere and any extension) --Moving window (because why not) --some more API functions --prettier, organize code --CHANGES: --Version 3.5: Lua5.2 support, TPT 91.0 platform API support, [] can be used to scroll, misc fixes --Version 3.4: some new buttons, better tooltips, fix 'Change dir' button, fix broken buttons on OS X --Version 3.3: fix apostophes in filenames, allow authors to rename their scripts on the server --Version 3.2: put MANAGER stuff in table, fix displaying changelogs --Version 3.1: Organize scripts less randomly, fix scripts being run twice, fix other bugs --central script / update server at starcatcher.us / delete local scripts / lots of other things by jacob1 v3.0 --Scan all subdirectories in scripts folder! v2.25 --Remove step hooks, v87 fixes them --Socket is now default in v87+ , horray, everyone can now use update features without extra downloads. --Handles up to 50 extra step functions, up from the default 5 (not including the manager's step) v2.1 --Other various nice API functions --Scripts can store/retrieve settings through the manager, see comments below v2.0 --Small fillrect change for v85, boxes can have backgrounds v1.92 --Support spaces in exe names v1.91 --Auto-update for OTHER scripts now works, is a bit messy, will fix later, but nothing should change for users to use this -- Place a line '--VER num UPDATE link' in one of the first four lines of the file, see my above example -- The link at top downloads a file that contains ONLY version,full link,and prints the rest(changelog). See my link for example if not socket then error("TPT version not supported") end if MANAGER then error("manager is already running") end if tpt.version.jacob1s_mod == 30 and tpt.version.jacob1s_mod_minor == 0 then return end local scriptversion = 7 MANAGER = {["version"] = "3.5", ["scriptversion"] = scriptversion, ["hidden"] = true} local TPT_LUA_PATH = 'scripts' local PATH_SEP = '\\' local OS = "WIN32" local jacobsmod = tpt.version.jacob1s_mod local CHECKUPDATE = false local EXE_NAME if platform then OS = platform.platform() if OS ~= "WIN32" and OS ~= "WIN64" then PATH_SEP = '/' end EXE_NAME = platform.exeName() local temp = EXE_NAME:reverse():find(PATH_SEP) EXE_NAME = EXE_NAME:sub(#EXE_NAME-temp+2) else if os.getenv('HOME') then PATH_SEP = '/' if fs.exists("/Applications") then OS = "MACOSX" else OS = "LIN64" end end if OS == "WIN32" or OS == "WIN64" then EXE_NAME = jacobsmod and "Jacob1\'s Mod.exe" or "Powder.exe" elseif OS == "MACOSX" then EXE_NAME = "powder-x" --can't restart on OS X (if using < 91.0) else EXE_NAME = jacobsmod and "Jacob1\'s Mod" or "powder" end end local filenames = {} local num_files = 0 --downloaded scripts aren't stored in filenames local localscripts = {} local onlinescripts = {} local running = {} local requiresrestart=false local online = false local first_online = true local updatetable --temporarily holds info on script manager updates local gen_buttons local sidebutton local download_file local settings = {} math.randomseed(os.time()) math.random() math.random() math.random() --some filler randoms --get line that can be saved into scriptinfo file local function scriptInfoString(info) --Write table into data format if type(info)~="table" then return end local t = {} for k,v in pairs(info) do table.insert(t,k..":\""..v.."\"") end local rstr = table.concat(t,","):gsub("\r",""):gsub("\n","\\n") return rstr end --read a scriptinfo line local function readScriptInfo(list) if not list then return {} end local scriptlist = {} for i in list:gmatch("[^\n]+") do local t = {} local ID = 0 for k,v in i:gmatch("(%w+):\"([^\"]*)\"") do t[k]= tonumber(v) or v:gsub("\r",""):gsub("\\n","\n") end scriptlist[t.ID] = t end return scriptlist end --save settings local function save_last() local savestring="" for script,v in pairs(running) do savestring = savestring.." \""..script.."\"" end savestring = "SAV "..savestring.."\nDIR "..TPT_LUA_PATH for k,t in pairs(settings) do for n,v in pairs(t) do savestring = savestring.."\nSET "..k.." "..n..":\""..v.."\"" end end local f if TPT_LUA_PATH == "scripts" then f = io.open(TPT_LUA_PATH..PATH_SEP.."autorunsettings.txt", "w") else f = io.open("autorunsettings.txt", "w") end if f then f:write(savestring) f:close() end f = io.open(TPT_LUA_PATH..PATH_SEP.."downloaded"..PATH_SEP.."scriptinfo", "w") if f then for k,v in pairs(localscripts) do f:write(scriptInfoString(v).."\n") end f:close() end end local function load_downloaded() local f = io.open(TPT_LUA_PATH..PATH_SEP.."downloaded"..PATH_SEP.."scriptinfo","r") if f then local lines = f:read("*a") f:close() localscripts = readScriptInfo(lines) for k,v in pairs(localscripts) do if k ~= 1 then if not v["ID"] or not v["name"] or not v["description"] or not v["path"] or not v["version"] then localscripts[k] = nil elseif not fs.exists(TPT_LUA_PATH.."/"..v["path"]:gsub("\\","/")) then localscripts[k] = nil end end end end end --load settings before anything else local function load_last() local f = io.open(TPT_LUA_PATH..PATH_SEP.."autorunsettings.txt","r") if not f then f = io.open("autorunsettings.txt","r") end if f then local lines = {} local line = f:read("*l") while line do table.insert(lines,(line:gsub("\r",""))) line = f:read("*l") end f:close() for i=1, #lines do local tok=lines[i]:sub(1,3) local str=lines[i]:sub(5) if tok=="SAV" then for word in string.gmatch(str, "\"(.-)\"") do running[word] = true end elseif tok=="EXE" then EXE_NAME=str elseif tok=="DIR" then TPT_LUA_PATH=str elseif tok=="SET" then local ident,name,val = string.match(str,"(.-) (.-):\"(.-)\"") if settings[ident] then settings[ident][name]=val else settings[ident]={[name]=val} end end end end load_downloaded() end load_last() --get list of files in scripts folder local function load_filenames() filenames = {} local function searchRecursive(directory) local dirlist = fs.list(directory) if not dirlist then return end for i,v in ipairs(dirlist) do local file = directory.."/"..v if fs.isDirectory(file) and v ~= "downloaded" then searchRecursive(file) elseif fs.isFile(file) then if file:find("%.lua$") then local toinsert = file:sub(#TPT_LUA_PATH+2) if OS == "WIN32" or OS == "WIN64" then toinsert = toinsert:gsub("/", "\\") --not actually required end table.insert(filenames, toinsert) end end end end searchRecursive(TPT_LUA_PATH) table.sort(filenames, function(first,second) return first:lower() < second:lower() end) end --ui object stuff local ui_base local ui_box local ui_line local ui_text local ui_button local ui_scrollbar local ui_tooltip local ui_checkbox local ui_console local ui_window local tooltip ui_base = { new = function() local b={} b.drawlist = {} function b:drawadd(f) table.insert(self.drawlist,f) end function b:draw(...) for _,f in ipairs(self.drawlist) do if type(f)=="function" then f(self,...) end end end b.movelist = {} function b:moveadd(f) table.insert(self.movelist,f) end function b:onmove(x,y) for _,f in ipairs(self.movelist) do if type(f)=="function" then f(self,x,y) end end end return b end } ui_box = { new = function(x,y,w,h,r,g,b) local box=ui_base.new() box.x=x box.y=y box.w=w box.h=h box.x2=x+w box.y2=y+h box.r=r or 255 box.g=g or 255 box.b=b or 255 function box:setcolor(r,g,b) self.r=r self.g=g self.b=b end function box:setbackground(r,g,b,a) self.br=r self.bg=g self.bb=b self.ba=a end box.drawbox=true box.drawbackground=false box:drawadd(function(self) if self.drawbackground then tpt.fillrect(self.x,self.y,self.w+1,self.h+1,self.br,self.bg,self.bb,self.ba) end if self.drawbox then tpt.drawrect(self.x,self.y,self.w,self.h,self.r,self.g,self.b) end end) box:moveadd(function(self,x,y) if x then self.x=self.x+x self.x2=self.x2+x end if y then self.y=self.y+y self.y2=self.y2+y end end) return box end } ui_line = { new=function(x,y,x2,y2,r,g,b) local line=ui_box.new(x,y,x2-x,y2-y,r,g,b) --Line is essentially a box, but with a different draw line.drawlist={} line:drawadd(function(self) tpt.drawline(self.x,self.y,self.x2,self.y2,self.r,self.g,self.b) end) return line end } ui_text = { new = function(text,x,y,r,g,b) local txt = ui_base.new() txt.text = text txt.x=x or 0 txt.y=y or 0 txt.r=r or 255 txt.g=g or 255 txt.b=b or 255 function txt:setcolor(r,g,b) self.r=r self.g=g self.b=b end txt:drawadd(function(self,x,y) tpt.drawtext(x or self.x,y or self.y,self.text,self.r,self.g,self.b) end) txt:moveadd(function(self,x,y) if x then self.x=self.x+x end if y then self.y=self.y+y end end) function txt:process() return false end return txt end, --Scrolls while holding mouse over newscroll = function(text,x,y,vis,r,g,b) local txt = ui_text.new(text,x,y,r,g,b) if tpt.textwidth(text)<vis then return txt end txt.visible=vis txt.length=string.len(text) txt.start=1 txt.drawlist={} --reset draw txt.timer=socket.gettime()+3 function txt:cuttext(self) local last = self.start+1 while tpt.textwidth(self.text:sub(self.start,last))<txt.visible and last<=self.length do last = last+1 end self.last=last-1 end txt:cuttext(txt) txt.minlast=txt.last-1 txt.ppl=((txt.visible-6)/(txt.length-txt.minlast+1)) txt:drawadd(function(self,x,y) if socket.gettime() > self.timer then if self.last >= self.length then self.start = 1 self:cuttext(self) self.timer = socket.gettime()+3 else self.start = self.start + 1 self:cuttext(self) if self.last >= self.length then self.timer = socket.gettime()+3 else self.timer = socket.gettime()+.15 end end end tpt.drawtext(x or self.x,y or self.y, self.text:sub(self.start,self.last) ,self.r,self.g,self.b) end) function txt:process(mx,my,button,event,wheel) if event==3 then local newlast = math.floor((mx-self.x)/self.ppl)+self.minlast if newlast<self.minlast then newlast=self.minlast end if newlast>0 and newlast~=self.last then local newstart=1 while tpt.textwidth(self.text:sub(newstart,newlast))>= self.visible do newstart=newstart+1 end self.start=newstart self.last=newlast self.timer = socket.gettime()+3 end end end return txt end } ui_scrollbar = { new = function(x,y,h,t,m) local bar = ui_base.new() --use line object as base? bar.x=x bar.y=y bar.h=h bar.total=t bar.numshown=m bar.pos=0 bar.length=math.floor((1/math.ceil(bar.total-bar.numshown+1))*bar.h) bar.soffset=math.floor(bar.pos*((bar.h-bar.length)/(bar.total-bar.numshown))) function bar:update(total,shown,pos) self.pos=pos or 0 if self.pos<0 then self.pos=0 end self.total=total self.numshown=shown self.length= math.floor((1/math.ceil(self.total-self.numshown+1))*self.h) self.soffset= math.floor(self.pos*((self.h-self.length)/(self.total-self.numshown))) end function bar:move(wheel) self.pos = self.pos-wheel if self.pos < 0 then self.pos=0 end if self.pos > (self.total-self.numshown) then self.pos=(self.total-self.numshown) end self.soffset= math.floor(self.pos*((self.h-self.length)/(self.total-self.numshown))) end bar:drawadd(function(self) if self.total > self.numshown then tpt.drawline(self.x,self.y+self.soffset,self.x,self.y+self.soffset+self.length) end end) bar:moveadd(function(self,x,y) if x then self.x=self.x+x end if y then self.y=self.y+y end end) function bar:process(mx,my,button,event,wheel) if wheel~=0 and not MANAGER.hidden then if self.total > self.numshown then local previous = self.pos self:move(wheel) if self.pos~=previous then return previous-self.pos end end end --possibly click the bar and drag? return false end return bar end } ui_button = { new = function(x,y,w,h,f,text) local b = ui_box.new(x,y,w,h) b.f=f b.t=ui_text.new(text,x+2,y+2) b.drawbox=false b.clicked=false b.almostselected=false b.invert=true b:setbackground(127,127,127,125) b:drawadd(function(self) if self.invert and self.almostselected then self.almostselected=false tpt.fillrect(self.x,self.y,self.w,self.h) local tr=self.t.r local tg=self.t.g local tb=self.t.b b.t:setcolor(0,0,0) b.t:draw() b.t:setcolor(tr,tg,tb) else if tpt.mousex>=self.x and tpt.mousex<=self.x2 and tpt.mousey>=self.y and tpt.mousey<=self.y2 then self.drawbackground=true else self.drawbackground=false end b.t:draw() end end) b:moveadd(function(self,x,y) self.t:onmove(x,y) end) function b:process(mx,my,button,event,wheel) local clicked = self.clicked if event==2 then self.clicked = false end if mx<self.x or mx>self.x2 or my<self.y or my>self.y2 then return false end if event==1 then self.clicked=true elseif clicked then if event==3 then self.almostselected=true end if event==2 then self:f() end return true end end return b end } ui_tooltip = { new = function(x,y,w,text) local b = ui_box.new(x,y-1,w,0) function b:updatetooltip(tooltip) self.tooltip = tooltip self.length = #tooltip self.lines = 1 local linebreak,lastspace = 0,nil for i=0,#self.tooltip do local width = tpt.textwidth(tooltip:sub(linebreak,i+1)) if width > self.w/2 and tooltip:sub(i,i):match("[%s,_%.%-?!]") then lastspace = i end local isnewline = (self.tooltip:sub(i,i) == '\n') if width > self.w or isnewline then local pos = (i==#tooltip or not lastspace) and i or lastspace self.lines = self.lines + 1 if self.tooltip:sub(pos,pos) == ' ' then self.tooltip = self.tooltip:sub(1,pos-1).."\n"..self.tooltip:sub(pos+1) elseif not isnewline then self.length = self.length + 1 self.tooltip = self.tooltip:sub(1,pos-1).."\n"..self.tooltip:sub(pos) i = i + 1 pos = pos + 1 end linebreak = pos+1 lastspace = nil end end self.h = self.lines*12+2 --self.w = tpt.textwidth(self.tooltip)+3 self.drawbox = tooltip ~= "" self.drawbackground = tooltip ~= "" end function b:settooltip(tooltip_) tooltip:onmove(tpt.mousex+5-tooltip.x, tpt.mousey+5-tooltip.y) tooltip:updatetooltip(tooltip_) end b:updatetooltip(text) b:setbackground(0,0,0,255) b.drawbackground = true b:drawadd(function(self) if self.tooltip ~= "" then tpt.drawtext(self.x+1,self.y+2,self.tooltip) end self:updatetooltip("") end) function b:process(mx,my,button,event,wheel) end return b end } ui_checkbox = { up_button = function(x,y,w,h,f,text) local b=ui_button.new(x,y,w,h,f,text) b.canupdate=false return b end, new_button = function(x,y,w,h,splitx,f,f2,text,localscript) local b = ui_box.new(x,y,splitx,h) b.f=f b.f2=f2 b.localscript=localscript b.splitx = splitx b.t=ui_text.newscroll(text,x+24,y+2,splitx-24) b.clicked=false b.selected=false b.checkbut=ui_checkbox.up_button(x+splitx+9,y,33,9,ui_button.scriptcheck,"Update") b.drawbox=false b:setbackground(127,127,127,100) b:drawadd(function(self) if self.t.text == "" then return end self.drawbackground = false if tpt.mousey >= self.y and tpt.mousey < self.y2 then if tpt.mousex >= self.x and tpt.mousex < self.x+8 then if self.localscript then tooltip:settooltip("delete this script") else tooltip:settooltip("view script in browser") end elseif tpt.mousex>=self.x and tpt.mousex<self.x2 then local script if online and onlinescripts[self.ID]["description"] then script = onlinescripts[self.ID] elseif not online and localscripts[self.ID] then script = localscripts[self.ID] end if script then tooltip:settooltip(script["name"].." by "..script["author"].."\n\n"..script["description"]) end self.drawbackground = true elseif tpt.mousex >= self.x2 then if tpt.mousex < self.x2+9 and self.running then tooltip:settooltip(online and "downloaded" or "running") elseif tpt.mousex >= self.x2+9 and tpt.mousex < self.x2+43 and self.checkbut.canupdate and onlinescripts[self.ID] and onlinescripts[self.ID]["changelog"] then tooltip:settooltip(onlinescripts[self.ID]["changelog"]) end end end self.t:draw() if self.localscript then if self.deletealmostselected then self.deletealmostselected = false tpt.drawtext(self.x+1, self.y+1, "\134", 255, 48, 32, 255) else tpt.drawtext(self.x+1, self.y+1, "\134", 160, 48, 32, 255) end tpt.drawtext(self.x+1, self.y+1, "\133", 255, 255, 255, 255) else tpt.drawtext(self.x+1, self.y+1, "\147", 255, 200, 80, 255) end tpt.drawrect(self.x+12,self.y+1,8,8) if self.almostselected then self.almostselected=false tpt.fillrect(self.x+12,self.y+1,8,8,150,150,150) elseif self.selected then tpt.fillrect(self.x+12,self.y+1,8,8) end local filepath = self.ID and localscripts[self.ID] and localscripts[self.ID]["path"] or self.t.text if self.running then tpt.drawtext(self.x+self.splitx+2,self.y+2,online and "D" or "R") end if self.checkbut.canupdate then self.checkbut:draw() end end) b:moveadd(function(self,x,y) self.t:onmove(x,y) self.checkbut:onmove(x,y) end) function b:process(mx,my,button,event,wheel) if self.f2 and mx <= self.x+8 then if event==1 then self.clicked = 1 elseif self.clicked == 1 then if event==3 then self.deletealmostselected = true end if event==2 then self:f2() end end elseif self.f and mx<=self.x+self.splitx then if event==1 then self.clicked = 2 elseif self.clicked == 2 then if event==3 then self.almostselected=true end if event==2 then self:f() end self.t:process(mx,my,button,event,wheel) end else if self.checkbut.canupdate then self.checkbut:process(mx,my,button,event,wheel) end end return true end return b end, new = function(x,y,w,h) local box = ui_box.new(x,y,w,h) box.list={} box.numlist = 0 box.max_lines = math.floor(box.h/10)-1 box.max_text_width = math.floor(box.w*0.8) box.splitx=x+box.max_text_width box.scrollbar = ui_scrollbar.new(box.x2-2,box.y+11,box.h-12,0,box.max_lines) box.lines={ ui_line.new(box.x+1,box.y+10,box.x2-1,box.y+10,170,170,170), ui_line.new(box.x+22,box.y+10,box.x+22,box.y2-1,170,170,170), ui_line.new(box.splitx,box.y+10,box.splitx,box.y2-1,170,170,170), ui_line.new(box.splitx+9,box.y+10,box.splitx+9,box.y2-1,170,170,170), } function box:updatescroll() self.scrollbar:update(self.numlist,self.max_lines) end function box:clear() self.list={} self.numlist=0 end function box:add(f,f2,text,localscript) local but = ui_checkbox.new_button(self.x,self.y+1+((self.numlist+1)*10),tpt.textwidth(text)+4,10,self.max_text_width,f,f2,text,localscript) table.insert(self.list,but) self.numlist = #self.list return but end box:drawadd(function (self) tpt.drawtext(self.x+24,self.y+2,"Files in "..TPT_LUA_PATH.." folder") tpt.drawtext(self.splitx+11,self.y+2,"Update") for i,line in ipairs(self.lines) do line:draw() end self.scrollbar:draw() local restart = false for i,check in ipairs(self.list) do local filepath = check.ID and localscripts[check.ID] and localscripts[check.ID]["path"] or check.t.text if not check.selected and running[filepath] then restart = true end if i>self.scrollbar.pos and i<=self.scrollbar.pos+self.max_lines then check:draw() end end requiresrestart = restart and not online end) box:moveadd(function(self,x,y) for i,line in ipairs(self.lines) do line:onmove(x,y) end for i,check in ipairs(self.list) do check:onmove(x,y) end end) function box:scroll(amount) local move = amount*10 if move==0 then return end for i,check in ipairs(self.list) do check:onmove(0,move) end end function box:process(mx,my,button,event,wheel) if mx<self.x or mx>self.x2 or my<self.y or my>self.y2-7 then return false end local scrolled = self.scrollbar:process(mx,my,button,event,wheel) if scrolled then self:scroll(scrolled) end local which = math.floor((my-self.y-11)/10)+1 if which>0 and which<=self.numlist then self.list[which+self.scrollbar.pos]:process(mx,my,button,event,wheel) end if event == 2 then for i,v in ipairs(self.list) do v.clicked = false end end return true end return box end } ui_console = { new = function(x,y,w,h) local con = ui_box.new(x,y,w,h) con.shown_lines = math.floor(con.h/10) con.max_lines = 300 con.max_width = con.w-4 con.lines = {} con.scrollbar = ui_scrollbar.new(con.x2-2,con.y+1,con.h-2,0,con.shown_lines) con:drawadd(function(self) self.scrollbar:draw() local count=0 for i,line in ipairs(self.lines) do if i>self.scrollbar.pos and i<= self.scrollbar.pos+self.shown_lines then line:draw(self.x+3,self.y+3+(count*10)) count = count+1 end end end) con:moveadd(function(self,x,y) self.scrollbar:onmove(x,y) end) function con:clear() self.lines = {} self.scrollbar:update(0,con.shown_lines) end function con:addstr(str,r,g,b) str = tostring(str) local nextl = str:find('\n') while nextl do local line = str:sub(1,nextl-1) self:addline(line,r,g,b) str = str:sub(nextl+1) nextl = str:find('\n') end self:addline(str,r,g,b) --anything leftover end function con:addline(line,r,g,b) if not line or line=="" then return end --No blank lines table.insert(self.lines,ui_text.newscroll(line,self.x,0,self.max_width,r,g,b)) if #self.lines>self.max_lines then table.remove(self.lines,1) end self.scrollbar:update(#self.lines,self.shown_lines,#self.lines-self.shown_lines) end function con:process(mx,my,button,event,wheel) if mx<self.x or mx>self.x2 or my<self.y or my>self.y2 then return false end self.scrollbar:process(mx,my,button,event,wheel) local which = math.floor((my-self.y-1)/10)+1 if which>0 and which<=self.shown_lines and self.lines[which+self.scrollbar.pos] then self.lines[which+self.scrollbar.pos]:process(mx,my,button,event,wheel) end return true end return con end } ui_window = { new = function(x,y,w,h) local w=ui_box.new(x,y,w,h) w.sub={} function w:add(m,name) if name then w[name]=m end table.insert(self.sub,m) end w:drawadd(function(self) for i,sub in ipairs(self.sub) do sub:draw() end end) w:moveadd(function(self,x,y) for i,sub in ipairs(self.sub) do sub:onmove(x,y) end end) function w:process(mx,my,button,event,wheel) if mx<self.x or mx>self.x2 or my<self.y or my>self.y2 then if button == 0 then return end ui_button.sidepressed() return true end local ret for i,sub in ipairs(self.sub) do if sub:process(mx,my,button,event,wheel) then ret = true end end return ret end return w end } --Main window with everything! local mainwindow = ui_window.new(50,50,525,300) mainwindow:setbackground(10,10,10,235) mainwindow.drawbackground=true mainwindow:add(ui_console.new(275,148,300,189),"menuconsole") mainwindow:add(ui_checkbox.new(50,80,225,257),"checkbox") tooltip = ui_tooltip.new(0,1,250,"") --Some API functions you can call from other scripts --put 'using_manager=MANAGER ~= nil' or similar in your scripts, using_manager will be true if the manager is active --Print a message to the manager console, can be colored function MANAGER.print(msg,...) mainwindow.menuconsole:addstr(msg,...) end --downloads and returns a file, so you can do whatever... local download_file function MANAGER.download(url) return download_file(url) end function MANAGER.scriptinfo(id) local url = "http://starcatcher.us/scripts/main.lua" if id then url = url.."?info="..id end local info = download_file(url) infotable = readScriptInfo(info) return id and infotable[id] or infotable end --Get various info about the system (operating system, script directory, path seperator, if socket is loaded) function MANAGER.sysinfo() return {["OS"]=OS, ["scriptDir"]=TPT_LUA_PATH, ["pathSep"]=PATH_SEP, ["exeName"] = EXE_NAME} end --Save a setting in the autorun settings file, ident should be your script name no one else would use. --Name is variable name, val is the value which will be saved/returned as a string function MANAGER.savesetting(ident,name,val) ident = tostring(ident) name = tostring(name) val = tostring(val) if settings[ident] then settings[ident][name]=val else settings[ident]={[name]=val} end save_last() end --Get a previously saved value, if it has one function MANAGER.getsetting(ident,name) if settings[ident] then return settings[ident][name] end return nil end --delete a setting, leave name nil to delete all of ident function MANAGER.delsetting(ident,name) if settings[ident] then if name then settings[ident][name]=nil else settings[ident]=nil end save_last() end end --mniip's download thing (mostly) local pattern = "http://w*%.?(.-)(/.*)" function download_file(url) local _,_,host,rest = url:find(pattern) if not host or not rest then MANAGER.print("Bad link") return end local conn=socket.tcp() if not conn then return end local succ=pcall(conn.connect,conn,host,80) conn:settimeout(5) if not succ then return end local userAgent = "PowderToy/"..tpt.version.major.."."..tpt.version.minor.."."..tpt.version.build.." ("..((OS == "WIN32" or OS == "WIN64") and "WIN; " or (os == "MACOSX" and "OSX; " or "LIN; "))..(jacobsmod and "M1" or "M0")..") SCRIPT/"..MANAGER.version succ,resp,something=pcall(conn.send,conn,"GET "..rest.." HTTP/1.1\r\nHost: "..host.."\r\nConnection: close\r\nUser-Agent: "..userAgent.."\r\n\n") if not succ then return end local data="" local c="" while c do c=conn:receive("*l") if c then data=data.."\n"..c end end if data=="" then MANAGER.print("no data") return end local first,last,code = data:find("HTTP/1%.1 (.-) .-\n") while last do data = data:sub(last+1) first,last,header = data:find("^([^\n]-:.-)\n") --read something from headers? if header then if tonumber(code)==302 then local _,_,new = header:find("^Location: (.*)") if new then return download_file(new) end end end end if host:find("pastebin.com") then --pastebin adds some weird numbers _,_,data=data:find("\n[^\n]*\n(.*)\n.+\n$") end return data end --Downloads to a location local function download_script(ID,location) local file = download_file("http://starcatcher.us/scripts/main.lua?get="..ID) if file then f=io.open(location,"w") f:write(file) f:close() return true end return false end --Restart exe (if named correctly) local function do_restart() save_last() if platform then platform.restart() end if OS == "WIN32" or OS == "WIN64" then os.execute("TASKKILL /IM \""..EXE_NAME.."\" /F &&START .\\\""..EXE_NAME.."\"") elseif OS == "OSX" then MANAGER.print("Can't restart on OS X when using game versions less than 91.0, please manually close and reopen The Powder Toy") return else os.execute("killall -s KILL \""..EXE_NAME.."\" && ./\""..EXE_NAME.."\"") end MANAGER.print("Restart failed, do you have the exe name right?",255,0,0) end local function open_link(url) if platform then platform.openLink(url) else local command = (OS == "WIN32" or OS == "WIN64") and "start" or (OS == "MACOSX" and "open" or "xdg-open") os.execute(command.." "..url) end end --TPT interface local function step() if jacobsmod then tpt.fillrect(0,0,gfx.WIDTH,gfx.HEIGHT,0,0,0,150) else tpt.fillrect(-1,-1,gfx.WIDTH,gfx.HEIGHT,0,0,0,150) end mainwindow:draw() tpt.drawtext(280,140,"Console Output:") if requiresrestart then tpt.drawtext(280,88,"Disabling a script requires a restart for effect!",255,50,50) end tpt.drawtext(55,55,"Click a script to toggle, hit DONE when finished") tpt.drawtext(474,55,"Script Manager v"..MANAGER.version)--479 for simple versions tooltip:draw() end local function mouseclick(mousex,mousey,button,event,wheel) sidebutton:process(mousex,mousey,button,event,wheel) if MANAGER.hidden then return true end if mousex>612 or mousey>384 then return false end mainwindow:process(mousex,mousey,button,event,wheel) return false end local jacobsmod_old_menu_check = false local function keypress(key,nkey,modifier,event) if jacobsmod and key == 'o' and event == 1 then jacobsmod_old_menu_check = true end if nkey==27 and not MANAGER.hidden then MANAGER.hidden=true return false end if MANAGER.hidden then return end if event == 1 then if key == "[" then mainwindow:process(mainwindow.x+30, mainwindow.y+30, 0, 2, 1) elseif key == "]" then mainwindow:process(mainwindow.x+30, mainwindow.y+30, 0, 2, -1) end end return false end --small button on right to bring up main menu local WHITE = {255,255,255,255} local BLACK = {0,0,0,255} local ICON = math.random(2) --pick a random icon local lua_letters= {{{2,2,2,7},{2,7,4,7},{6,7,6,11},{6,11,8,11},{8,7,8,11},{10,11,12,11},{10,11,10,15},{11,13,11,13},{12,11,12,15},}, {{2,3,2,13},{2,14,7,14},{4,3,4,12},{4,12,7,12},{7,3,7,12},{9,3,12,3},{9,3,9,14},{10,8,11,8},{12,3,12,14},}} local function smallstep() gfx.drawRect(sidebutton.x, sidebutton.y+1, sidebutton.w+1, sidebutton.h+1,200,200,200) local color=WHITE if not MANAGER.hidden then step() gfx.fillRect(sidebutton.x, sidebutton.y+1, sidebutton.w+1, sidebutton.h+1) color=BLACK end for i,dline in ipairs(lua_letters[ICON]) do tpt.drawline(dline[1]+sidebutton.x,dline[2]+sidebutton.y,dline[3]+sidebutton.x,dline[4]+sidebutton.y,color[1],color[2],color[3]) end if jacobsmod_old_menu_check then if tpt.oldmenu()==0 and sidebutton.y > 150 then sidebutton:onmove(0, -256) elseif tpt.oldmenu()==1 and sidebutton.y < 150 then sidebutton:onmove(0, 256) end jacobsmod_old_menu_check = false end end --button functions on click function ui_button.reloadpressed(self) load_filenames() load_downloaded() gen_buttons() mainwindow.checkbox:updatescroll() if num_files == 0 then MANAGER.print("No scripts found in '"..TPT_LUA_PATH.."' folder",255,255,0) fs.makeDirectory(TPT_LUA_PATH) else MANAGER.print("Reloaded file list, found "..num_files.." scripts") end end function ui_button.selectnone(self) for i,but in ipairs(mainwindow.checkbox.list) do but.selected = false end end function ui_button.consoleclear(self) mainwindow.menuconsole:clear() end function ui_button.changedir(self) local last = TPT_LUA_PATH local new = tpt.input("Change search directory","Enter the folder where your scripts are",TPT_LUA_PATH,TPT_LUA_PATH) if new~=last and new~="" then fs.removeFile(last..PATH_SEP.."autorunsettings.txt") MANAGER.print("Directory changed to "..new,255,255,0) TPT_LUA_PATH = new end ui_button.reloadpressed() save_last() end function ui_button.uploadscript(self) if not online then local command = (OS == "WIN32" or OS == "WIN64") and "start" or (OS == "MACOSX" and "open" or "xdg-open") os.execute(command.." "..TPT_LUA_PATH) else open_link("http://starcatcher.us/scripts/#submit-page") end end local lastpaused function ui_button.sidepressed(self) if TPTMP and TPTMP.chatHidden == false then print("minimize TPTMP before opening the manager") return end MANAGER.hidden = not MANAGER.hidden ui_button.localview() if not MANAGER.hidden then lastpaused = tpt.set_pause() tpt.set_pause(1) ui_button.reloadpressed() else tpt.set_pause(lastpaused) end end local donebutton function ui_button.donepressed(self) MANAGER.hidden = true for i,but in ipairs(mainwindow.checkbox.list) do local filepath = but.ID and localscripts[but.ID]["path"] or but.t.text if but.selected then if requiresrestart then running[filepath] = true else if not running[filepath] then local status,err = pcall(dofile,TPT_LUA_PATH..PATH_SEP..filepath) if not status then MANAGER.print(err,255,0,0) print(err) but.selected = false else MANAGER.print("Started "..filepath) running[filepath] = true end end end elseif running[filepath] then running[filepath] = nil end end if requiresrestart then do_restart() return end save_last() end function ui_button.downloadpressed(self) for i,but in ipairs(mainwindow.checkbox.list) do if but.selected then --maybe do better display names later local displayName local function get_script(butt) local script = download_file("http://starcatcher.us/scripts/main.lua?get="..butt.ID) displayName = "downloaded"..PATH_SEP..butt.ID.." "..onlinescripts[butt.ID].author.."-"..onlinescripts[butt.ID].name..".lua" local name = TPT_LUA_PATH..PATH_SEP..displayName if not fs.exists(TPT_LUA_PATH..PATH_SEP.."downloaded") then fs.makeDirectory(TPT_LUA_PATH..PATH_SEP.."downloaded") end local file = io.open(name, "w") if not file then error("could not open "..name) end file:write(script) file:close() if localscripts[butt.ID] and localscripts[butt.ID]["path"] ~= displayName then local oldpath = localscripts[butt.ID]["path"] fs.removeFile(TPT_LUA_PATH.."/"..oldpath:gsub("\\","/")) running[oldpath] = nil end localscripts[butt.ID] = onlinescripts[butt.ID] localscripts[butt.ID]["path"] = displayName dofile(name) end local status,err = pcall(get_script, but) if not status then MANAGER.print(err,255,0,0) print(err) but.selected = false else MANAGER.print("Downloaded and started "..but.t.text) running[displayName] = true end end end MANAGER.hidden = true ui_button.localview() save_last() end function ui_button.pressed(self) self.selected = not self.selected end function ui_button.delete(self) --there is no tpt.confirm() yet if tpt.input("Delete File", "Delete "..self.t.text.."?", "yes", "no") == "yes" then local filepath = self.ID and localscripts[self.ID]["path"] or self.t.text fs.removeFile(TPT_LUA_PATH.."/"..filepath:gsub("\\","/")) if running[filepath] then running[filepath] = nil end if localscripts[self.ID] then localscripts[self.ID] = nil end save_last() ui_button.localview() load_filenames() gen_buttons() end end function ui_button.viewonline(self) open_link("http://starcatcher.us/scripts/#"..self.ID) end function ui_button.scriptcheck(self) local oldpath = localscripts[self.ID]["path"] local newpath = "downloaded"..PATH_SEP..self.ID.." "..onlinescripts[self.ID].author.."-"..onlinescripts[self.ID].name..".lua" if download_script(self.ID,TPT_LUA_PATH..PATH_SEP..newpath) then self.canupdate = false localscripts[self.ID] = onlinescripts[self.ID] localscripts[self.ID]["path"] = newpath if oldpath ~= newpath then fs.removeFile(TPT_LUA_PATH.."/"..oldpath:gsub("\\","/")) if running[oldpath] then running[newpath],running[oldpath] = running[oldpath],nil end end if running[newpath] then do_restart() else save_last() MANAGER.print("Updated "..onlinescripts[self.ID]["name"]) end end end function ui_button.doupdate(self) if jacobsmod and jacobsmod >= 30 then fileSystem.move("scriptmanager.lua", "scriptmanagerold.lua") download_script(1, 'scriptmanager.lua') else fileSystem.move("autorun.lua", "autorunold.lua") download_script(1, 'autorun.lua') end localscripts[1] = updatetable[1] do_restart() end local uploadscriptbutton function ui_button.localview(self) if online then online = false gen_buttons() donebutton.t.text = "DONE" donebutton.w = 29 donebutton.x2 = donebutton.x + donebutton.w donebutton.f = ui_button.donepressed uploadscriptbutton.t.text = "\147 Script Folder" end end function ui_button.onlineview(self) if not online then online = true gen_buttons() donebutton.t.text = "DOWNLOAD" donebutton.w = 55 donebutton.x2 = donebutton.x + donebutton.w donebutton.f = ui_button.downloadpressed uploadscriptbutton.t.text = "Upload Script" end end --add buttons to window donebutton = ui_button.new(55,339,29,10,ui_button.donepressed,"DONE") mainwindow:add(donebutton) mainwindow:add(ui_button.new(134,339,40,10,ui_button.sidepressed,"CANCEL")) --mainwindow:add(ui_button.new(152,339,29,10,ui_button.selectnone,"NONE")) local nonebutton = ui_button.new(62,81,8,8,ui_button.selectnone,"") nonebutton.drawbox = true mainwindow:add(nonebutton) mainwindow:add(ui_button.new(538,339,33,10,ui_button.consoleclear,"CLEAR")) mainwindow:add(ui_button.new(278,67,39,10,ui_button.reloadpressed,"RELOAD")) mainwindow:add(ui_button.new(378,67,51,10,ui_button.changedir,"Change dir")) uploadscriptbutton = ui_button.new(478,67,79,10,ui_button.uploadscript,"\147 Script Folder") mainwindow:add(uploadscriptbutton) local tempbutton = ui_button.new(60, 65, 30, 10, ui_button.localview, "Local") tempbutton.drawbox = true mainwindow:add(tempbutton) tempbutton = ui_button.new(100, 65, 35, 10, ui_button.onlineview, "Online") tempbutton.drawbox = true mainwindow:add(tempbutton) sidebutton = ui_button.new(gfx.WIDTH-16,134,14,15,ui_button.sidepressed,'') if jacobsmod and tpt.oldmenu()==1 then sidebutton:onmove(0, 256) end local function gen_buttons_local() local count = 0 local sorted = {} for k,v in pairs(localscripts) do if v.ID ~= 1 then table.insert(sorted, v) end end table.sort(sorted, function(first,second) return first.name:lower() < second.name:lower() end) for i,v in ipairs(sorted) do local check = mainwindow.checkbox:add(ui_button.pressed,ui_button.delete,v.name,true) check.ID = v.ID if running[v.path] then check.running = true check.selected = true end count = count + 1 end if #sorted >= 5 and #filenames >= 5 then mainwindow.checkbox:add(nil, nil, "", false) --empty space to separate things end for i=1,#filenames do local check = mainwindow.checkbox:add(ui_button.pressed,ui_button.delete,filenames[i],true) if running[filenames[i]] then check.running = true check.selected = true end end num_files = count + #filenames end local function gen_buttons_online() local list = download_file("http://starcatcher.us/scripts/main.lua") onlinescripts = readScriptInfo(list) local sorted = {} for k,v in pairs(onlinescripts) do table.insert(sorted, v) end table.sort(sorted, function(first,second) return first.ID < second.ID end) for k,v in pairs(sorted) do local check = mainwindow.checkbox:add(ui_button.pressed, ui_button.viewonline, v.name, false) check.ID = v.ID check.checkbut.ID = v.ID if localscripts[v.ID] then check.running = true if tonumber(v.version) > tonumber(localscripts[check.ID].version) then check.checkbut.canupdate = true end end end if first_online then first_online = false local updateinfo = download_file("http://starcatcher.us/scripts/main.lua?info=1") updatetable = readScriptInfo(updateinfo) if not updatetable[1] then return end if tonumber(updatetable[1].version) > scriptversion then local updatebutton = ui_button.new(278,127,40,10,ui_button.doupdate,"UPDATE") updatebutton.t:setcolor(25,255,25) mainwindow:add(updatebutton) MANAGER.print("A script manager update is available! Click UPDATE",25,255,55) MANAGER.print(updatetable[1].changelog,25,255,55) end end end gen_buttons = function() mainwindow.checkbox:clear() if online then gen_buttons_online() else gen_buttons_local() end mainwindow.checkbox:updatescroll() end gen_buttons() --register manager first tpt.register_step(smallstep) --load previously running scripts local started = "" for prev,v in pairs(running) do local status,err = pcall(dofile,TPT_LUA_PATH..PATH_SEP..prev) if not status then MANAGER.print(err,255,0,0) running[prev] = nil else started=started.." "..prev local newbut = mainwindow.checkbox:add(ui_button.pressed,prev,nil,false) newbut.selected=true end end save_last() if started~="" then MANAGER.print("Auto started"..started) end tpt.register_mouseevent(mouseclick) tpt.register_keypress(keypress)
gpl-3.0
Blackdutchie/Zero-K
scripts/spherecloaker.lua
15
2991
local head = piece 'head' local hips = piece 'hips' local chest = piece 'chest' local rthigh = piece 'rthigh' local lthigh = piece 'lthigh' local lshin = piece 'lshin' local rshin = piece 'rshin' local rfoot = piece 'rfoot' local lfoot = piece 'lfoot' local disc = piece 'disc' local cloaker = piece 'cloaker' local SIG_MOVE = 1 include "constants.lua" local function Walk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) while true do Turn(rthigh, y_axis, 0, math.rad(135)) Turn(lthigh, y_axis, 0, math.rad(130)) Turn(rthigh, z_axis, math.rad(0), math.rad(135)) Turn(lthigh, z_axis, math.rad(0), math.rad(130)) Turn(lfoot, z_axis, math.rad(0), math.rad(130)) Turn(rfoot, z_axis, math.rad(0), math.rad(130)) Turn(rshin, x_axis, math.rad(85), math.rad(260)) Turn(rthigh, x_axis, math.rad(-100), math.rad(135)) Turn(lthigh, x_axis, math.rad(30), math.rad(135)) Turn(chest, y_axis, math.rad(10), math.rad(60)) WaitForMove(hips, y_axis) Move(hips, y_axis, 1.2, 4.2) WaitForMove(hips, y_axis) Turn(rshin, x_axis, math.rad(10), math.rad(315)) Move(hips, y_axis, 0, 4.2) Turn(lshin, x_axis, math.rad(85), math.rad(260)) Turn(lthigh, x_axis, math.rad(-100), math.rad(135)) Turn(rthigh, x_axis, math.rad(30), math.rad(135)) Turn(chest, y_axis, math.rad(-10), math.rad(60)) WaitForMove(hips, y_axis) Move(hips, y_axis, 1.2, 4.2) WaitForMove(hips, y_axis) Turn(lshin, x_axis, math.rad(10), math.rad(315)) Move(hips, y_axis, 0, 4.2) end end local function StopWalk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) Turn(lfoot, x_axis, 0, math.rad(395)) Turn(rfoot, x_axis, 0, math.rad(395)) Turn(rthigh, x_axis, 0, math.rad(235)) Turn(lthigh, x_axis, 0, math.rad(230)) Turn(lshin, x_axis, 0, math.rad(235)) Turn(rshin, x_axis, 0, math.rad(230)) Turn(rthigh, y_axis, math.rad(-20), math.rad(135)) Turn(lthigh, y_axis, math.rad(20), math.rad(130)) Turn(rthigh, z_axis, math.rad(-3), math.rad(135)) Turn(lthigh, z_axis, math.rad(3), math.rad(130)) Turn(lfoot, z_axis, math.rad(-3), math.rad(130)) Turn(rfoot, z_axis, math.rad(3), math.rad(130)) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(StopWalk) end function script.Activate() Spin(disc, z_axis, math.rad(90)) end function script.Deactivate() Spin(disc, z_axis, 0) end function script.Create() StartThread(SmokeUnit, {head, hips, chest}) Turn(hips, x_axis, math.rad(45)) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= 0.25) then Explode(hips, sfxNone) Explode(chest, sfxNone) Explode(head, sfxFall + sfxFire) return 1 elseif (severity <= 0.5) then Explode(hips, sfxShatter) Explode(chest, sfxShatter) Explode(head, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit) return 1 end Explode(hips, sfxShatter) Explode(chest, sfxShatter) Explode(head, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit) return 2 end
gpl-2.0
teslamint/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_status/processes.lua
75
1236
-- 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. f = SimpleForm("processes", translate("Processes"), translate("This list gives an overview over currently running system processes and their status.")) f.reset = false f.submit = false t = f:section(Table, luci.sys.process.list()) t:option(DummyValue, "PID", translate("PID")) t:option(DummyValue, "USER", translate("Owner")) t:option(DummyValue, "COMMAND", translate("Command")) t:option(DummyValue, "%CPU", translate("CPU usage (%)")) t:option(DummyValue, "%MEM", translate("Memory usage (%)")) hup = t:option(Button, "_hup", translate("Hang Up")) hup.inputstyle = "reload" function hup.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 1) end term = t:option(Button, "_term", translate("Terminate")) term.inputstyle = "remove" function term.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 15) end kill = t:option(Button, "_kill", translate("Kill")) kill.inputstyle = "reset" function kill.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 9) end return f
apache-2.0
Blackdutchie/Zero-K
units/trem.lua
5
6415
unitDef = { unitname = [[trem]], name = [[Tremor]], description = [[Heavy Saturation Artillery Tank]], acceleration = 0.05952, brakeRate = 0.124, buildCostEnergy = 1500, buildCostMetal = 1500, builder = false, buildPic = [[TREM.png]], buildTime = 1500, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[34 34 50]], collisionVolumeTest = 1, collisionVolumeType = [[cylZ]], corpse = [[DEAD]], customParams = { description_de = [[Schwerer Saturation Artillerie Panzer]], description_bp = [[Tanque de artilharia pesado]], description_fr = [[Artillerie Lourde]], description_pl = [[Ciezka artyleria]], helptext = [[The principle behind the Tremor is simple: flood an area with enough shots, and you'll hit something at least once. Slow, clumsy, vulnerable and extremely frightening, the Tremor works best against high-density target areas, where its saturation shots are most likely to do damage. It pulverizes shields in seconds and its shells smooth terrain.]], helptext_bp = [[O princípio por trás do Tremor é simples: encha uma área com tiros suficientes, e voç? acertará algo pelo menos uma vez. Lento, atrapalhado, vulnerável e extremamente assustador, Tremor funciona melhor contra áreas-alvo de alta densidade, onde seus tiros de saturaç?o tem maior probabilidade de causar dano.]], helptext_fr = [[Le principe du Tremor est simple: inonder une zone de tirs plasma gr?ce ? son triple canon, avec une chance de toucher quelquechose. Par d?finition impr?cis, le Tremor est l'outil indispensable de destruction de toutes les zones ? h'aute densit? d'ennemis.]], helptext_de = [[Das Prinzip hinter dem Tremor ist einfach: flute ein Areal mit genug Schüssen und du wirst irgendwas, wenigstens einmal, treffen. Langsam, schwerfällig, anfällig und extrem beängstigend ist der Tremor, weshalb er gegen dichbesiedelte Gebiete sinnvoll einzusetzen ist.]], helptext_pl = [[Tremor zalewa okolice gradem pociskow, co doskonale sprawdza sie przeciwko duzym zgrupowaniom wrogich jednostek i tarczom i wyrownuje teren.]], modelradius = [[17]], }, explodeAs = [[BIG_UNIT]], footprintX = 4, footprintZ = 4, highTrajectory = 1, iconType = [[tanklrarty]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, mass = 392, maxDamage = 2045, maxSlope = 18, maxVelocity = 1.7, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TANK4]], moveState = 0, noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP]], objectName = [[cortrem.s3o]], seismicSignature = 4, selfDestructAs = [[BIG_UNIT]], sfxtypes = { explosiongenerators = { [[custom:wolvmuzzle1]], }, }, side = [[CORE]], sightDistance = 660, smoothAnim = true, trackOffset = 20, trackStrength = 8, trackStretch = 1, trackType = [[StdTank]], trackWidth = 38, turninplace = 0, turnRate = 312, workerTime = 0, weapons = { { def = [[PLASMA]], badTargetCategory = [[SWIM LAND SHIP HOVER]], mainDir = [[0 0 1]], maxAngleDif = 270, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]], }, }, weaponDefs = { PLASMA = { name = [[Rapid-Fire Plasma Artillery]], accuracy = 1400, areaOfEffect = 160, avoidFeature = false, avoidGround = false, craterBoost = 0, craterMult = 0, customParams = { gatherradius = [[192]], smoothradius = [[96]], smoothmult = [[0.25]], lups_noshockwave = [[1]], }, damage = { default = 135, planes = 135, subs = 7, }, explosionGenerator = [[custom:tremor]], impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, myGravity = 0.1, range = 1300, reloadtime = 0.36, soundHit = [[weapon/cannon/cannon_hit2]], soundStart = [[weapon/cannon/tremor_fire]], turret = true, weaponType = [[Cannon]], weaponVelocity = 420, }, }, featureDefs = { DEAD = { description = [[Wreckage - Tremor]], blocking = true, category = [[corpses]], damage = 2045, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, height = [[8]], hitdensity = [[100]], metal = 600, object = [[tremor_dead_new.s3o]], reclaimable = true, reclaimTime = 600, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Tremor]], blocking = false, category = [[heaps]], damage = 2045, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, height = [[2]], hitdensity = [[100]], metal = 300, object = [[debris2x2a.s3o]], reclaimable = true, reclaimTime = 300, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ trem = unitDef })
gpl-2.0
xAleXXX007x/Witcher-RolePlay
witcherrp/plugins/crafting/sh_recipies.lua
1
41057
local PLUGIN = PLUGIN --Алхимия local RECIPE = {} RECIPE.uid = "priparka_making" RECIPE.name = "Целебная припарка" RECIPE.category = "Алхимия" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Останавливает заражение и ускоряет заживление раны." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.25 } RECIPE.requiredattrib = { ["alch"] = 0 } RECIPE.items = { ["plesen"] = 1, ["mirt"] = 2 } RECIPE.result = { ["priparka"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "durman_making" RECIPE.name = "Дурман" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Выпивший уходит в состояние сна." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.25 } RECIPE.requiredattrib = { ["alch"] = 5 } RECIPE.items = { ["water"] = 1, ["pautinnik"] = 1, ["voronglaz"] = 2, ["goat_horn"] = 1, } RECIPE.result = { ["durman"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "armor_potion_making" RECIPE.name = "Зелье Каменной Кожи" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Повышает физическую защиту." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.5 } RECIPE.requiredattrib = { ["alch"] = 30 } RECIPE.items = { ["spirt"] = 1, ["shibalci"] = 2, ["sporin"] = 2, ["bear_fat"] = 1, } RECIPE.result = { ["armor_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "nightvision_making" RECIPE.name = "Зелье Кошачьего Зрения" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Усиляет восприятие света." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.5 } RECIPE.requiredattrib = { ["alch"] = 15 } RECIPE.items = { ["spirt"] = 1, ["pautinnik"] = 3, ["berberika"] = 2 } RECIPE.result = { ["nightvision"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "end_potion_making" RECIPE.name = "Зелье повышения выносливости" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Временно повышает выносливость выпившего." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.5 } RECIPE.requiredattrib = { ["alch"] = 20 } RECIPE.items = { ["spirt"] = 1, ["giacinia"] = 3, ["sporin"] = 1, ["bear_fat"] = 1, } RECIPE.result = { ["end_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "stm_potion_making" RECIPE.name = "Зелье Змеиной Ловкости" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Временно повышает ловкость выпившего." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.5 } RECIPE.requiredattrib = { ["alch"] = 25 } RECIPE.items = { ["spirt"] = 1, ["balissa"] = 1, ["plesen"] = 1, ["petrushka"] = 2, ["goat_horn"] = 1, } RECIPE.result = { ["stm_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "strenght_potion_making" RECIPE.name = "Зелье Змеиной Ловкости" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Временно повышает ловкость выпившего." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.5 } RECIPE.requiredattrib = { ["alch"] = 25 } RECIPE.items = { ["spirt"] = 1, ["plesen"] = 1, ["han"] = 1, ["verbena"] = 4, ["wolf_klik"] = 1, } RECIPE.result = { ["strenght_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "raffars_potion_making" RECIPE.name = "Зелье Раффара Белого" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Моментально восстанавливает здоровье, лечит переломы и кровотечение." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 1 } RECIPE.requiredattrib = { ["alch"] = 50 } RECIPE.items = { ["alkagest"] = 1, ["plesen"] = 1, ["han"] = 1, ["verbena"] = 4, } RECIPE.result = { ["raffars_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "stamina_potion_making" RECIPE.name = "Зелье выносливости" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Временно ускоряет восстановление выносливости." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 1 } RECIPE.requiredattrib = { ["alch"] = 20 } RECIPE.items = { ["alkagest"] = 1, ["chemerica"] = 1, ["mirt"] = 1, ["voronglaz"] = 4, ["wolf_klik"] = 1, } RECIPE.result = { ["stamina_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "speed_potion_making" RECIPE.name = "Настой скорости" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Временно увеличивает скорость бега." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 1 } RECIPE.requiredattrib = { ["alch"] = 10 } RECIPE.items = { ["spirt"] = 1, ["verbena"] = 2, ["shibalci"] = 1, ["balissa"] = 2, ["wolf_klik"] = 1, } RECIPE.result = { ["stamina_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "otvar_making" RECIPE.name = "Целебный отвар" RECIPE.category = "Алхимия" RECIPE.model = Model( "models/items/provisions/potions/life_potion.mdl" ) RECIPE.desc = "Целебный отвар, выпив который, можно быстро залечить раны." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 1 } RECIPE.requiredattrib = { ["alch"] = 5 } RECIPE.items = { ["spirt"] = 1, ["han"] = 2, ["verbena"] = 2, } RECIPE.result = { ["otvar"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "fishteh_making" RECIPE.name = "Фисштех" RECIPE.category = "Алхимия" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Приготовить первоклассный фисштех." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 1 } RECIPE.requiredattrib = { ["alch"] = 15 } RECIPE.items = { ["sporin"] = 1, ["shibalci"] = 2, ["alkagest"] = 1, } RECIPE.result = { ["fishteh"] = 1, ["water_empty"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "antidrunk_making" RECIPE.name = "Средство против опьянения" RECIPE.category = "Алхимия: зелья" RECIPE.model = Model( "models/items/provisions/potions/cure_poison_potion.mdl" ) RECIPE.desc = "Почти моментально устраняет алкогольное опьянение." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 0.5 } RECIPE.requiredattrib = { ["alch"] = 5 } RECIPE.items = { ["water"] = 1, ["verbena"] = 2, ["petrushka"] = 2, } RECIPE.result = { ["antidrunk_potion"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "alkagest_making" RECIPE.name = "Алкагест" RECIPE.category = "Алхимия: алкоголь" RECIPE.model = Model( "models/props/furnitures/gob/l6_jar/l6_jar.mdl" ) RECIPE.desc = "Первоклассная основа для эликсиров." RECIPE.noBlueprint = true RECIPE.place = 7 RECIPE.updateattrib = { ["alch"] = 2.5 } RECIPE.requiredattrib = { ["alch"] = 5 } RECIPE.items = { ["temvodka"] = 1, ["nilfvodka"] = 1, ["omela"] = 2, } RECIPE.result = { ["alkagest"] = 2, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "mahspirt_making" RECIPE.name = "Махакамский спирт" RECIPE.category = "Алхимия: алкоголь" RECIPE.model = Model( "models/props/furnitures/gob/l6_jar/l6_jar.mdl" ) RECIPE.desc = "Спирт по махакамскому рецепту." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["alch"] = 1 } RECIPE.requiredattrib = { ["alch"] = 20 } RECIPE.items = { ["spirt"] = 1, ["mirt"] = 2 } RECIPE.result = { ["mahspirt"] = 1, } RECIPES:Register( RECIPE ) --Кулинария: алкоголь local RECIPE = {} RECIPE.uid = "sbiten_making" RECIPE.name = "Сбитень" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Приготовить освежающий напиток из меда и пряностей." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 10 } RECIPE.items = { ["water"] = 1, ["honey"] = 1, ["spice"] = 2, } RECIPE.result = { ["sbiten"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "rakia_making" RECIPE.name = "Ракия" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Напиток, получаемый путем брожения." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 15 } RECIPE.items = { ["water"] = 1, ["apple"] = 3, ["spice"] = 1, } RECIPE.result = { ["rakia"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "kvas_making" RECIPE.name = "Квас" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Приготовить освежающий напиток из хлеба." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 10 } RECIPE.items = { ["water"] = 1, ["bread"] = 1 } RECIPE.result = { ["kvas"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "pivo_making" RECIPE.name = "Пиво" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Сварить светлое пшеничное пиво." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.75 } RECIPE.requiredattrib = { ["cook"] = 20 } RECIPE.items = { ["water"] = 1, ["seed_wheat"] = 1 } RECIPE.result = { ["pivo"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "medovuha_making" RECIPE.name = "Медовуха" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Алкогольный напиток на основе меда." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 30 } RECIPE.items = { ["water"] = 1, ["honey"] = 1 } RECIPE.result = { ["medovuha"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "samogon_making" RECIPE.name = "Самогон" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Очень крепкий самогон на лепестках чемерицы." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1.25 } RECIPE.requiredattrib = { ["cook"] = 40 } RECIPE.items = { ["water"] = 1, ["chemerica"] = 2 } RECIPE.result = { ["samogon"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "vodka_making" RECIPE.name = "Водка" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Водно-спиртовое изделие." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1.5 } RECIPE.requiredattrib = { ["cook"] = 50 } RECIPE.items = { ["water"] = 1, ["potato"] = 1 } RECIPE.result = { ["vodka"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spirt_making" RECIPE.name = "Спирт" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Чистейший спирт. Лучше использовать в медицине." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1.5 } RECIPE.requiredattrib = { ["cook"] = 15 } RECIPE.items = { ["vodka"] = 2, } RECIPE.result = { ["spirt"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "nastoy_making" RECIPE.name = "Самогон из мандрагоры" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Высококачественная основа для эликсиров." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 2 } RECIPE.requiredattrib = { ["cook"] = 70 } RECIPE.items = { ["spirt"] = 1, ["mandragora"] = 2 } RECIPE.result = { ["nastoy"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "temvodka_making" RECIPE.name = "Темерская ржаная водка" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Местные пьянчуги называют ржаную водку своим хлебом насущным." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 2.25 } RECIPE.requiredattrib = { ["cook"] = 25 } RECIPE.items = { ["spirt"] = 1, ["flour"] = 1, } RECIPE.result = { ["temvodka"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "nilfvodka_making" RECIPE.name = "Нильфгаардская лимонная водка" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Лимоны в этих краях не растут, но заменить их можно лепестками гиацинии." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 2.25 } RECIPE.requiredattrib = { ["cook"] = 25 } RECIPE.items = { ["spirt"] = 1, ["giacinia"] = 1, } RECIPE.result = { ["nilfvodka"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "wine_making" RECIPE.name = "Вино" RECIPE.category = "Кулинария: напитки" RECIPE.model = Model( "models/toussaint_bottle8.mdl" ) RECIPE.desc = "Вино из винограда. Добавить немного гиацинии для аромата." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 2.5 } RECIPE.requiredattrib = { ["cook"] = 45 } RECIPE.items = { ["water"] = 1, ["grape"] = 2, ["giacinia"] = 1, } RECIPE.result = { ["wine"] = 1, } RECIPES:Register( RECIPE ) --Крафт на коленке local RECIPE = {} RECIPE.uid = "good_healthkit_making" RECIPE.name = "Полевой набор медика" RECIPE.category = "Медицина" RECIPE.model = Model( "models/toussaint_box1.mdl" ) RECIPE.desc = "Собрать все необходимое для оказания первой помощи." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["mdc"] = 1 } RECIPE.requiredattrib = { ["mdc"] = 20 } RECIPE.items = { ["splint"] = 2, ["bandage"] = 2, ["priparka"] = 2, ["otvar"] = 2, ["spirt"] = 2, ["iron"] = 1, } RECIPE.result = { ["good_healthkit"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "healthkit_making" RECIPE.name = "Аптечка" RECIPE.category = "Медицина" RECIPE.model = Model( "models/items/provisions/food_ratio/food_ratio02.mdl" ) RECIPE.desc = "Может помочь при первой помощи." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["mdc"] = 0.5 } RECIPE.requiredattrib = { ["mdc"] = 10 } RECIPE.items = { ["cloth"] = 3, ["bandage"] = 2, ["priparka"] = 2, } RECIPE.result = { ["healthkit"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "poor_healthkit_making" RECIPE.name = "Самодельная аптечка" RECIPE.category = "Медицина" RECIPE.model = Model( "models/items/provisions/food_ratio/food_ratio02.mdl" ) RECIPE.desc = "Может помочь при первой помощи." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["mdc"] = 0.25 } RECIPE.requiredattrib = { ["mdc"] = 5 } RECIPE.items = { ["cloth"] = 2, ["poor_bandage"] = 2, ["priparka"] = 1, } RECIPE.result = { ["pure_healthkit"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "tie_making" RECIPE.name = "Веревка" RECIPE.category = "Разное" RECIPE.model = Model( "models/props/tools/humans/rope_rigging_sml.mdl" ) RECIPE.desc = "Скрутив несколько лоскутов ткани, можно сделать веревку." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cloth"] = 0.25 } RECIPE.requiredattrib = { ["cloth"] = 0 } RECIPE.items = { ["cloth"] = 3, } RECIPE.result = { ["tie"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "poor_bandage_making" RECIPE.name = "Самодельный бинт" RECIPE.category = "Медицина" RECIPE.model = Model( "models/toussaint_paper13.mdl" ) RECIPE.desc = "Может помочь при первой помощи." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["mdc"] = 0.25 } RECIPE.requiredattrib = { ["mdc"] = 0 } RECIPE.items = { ["cloth"] = 1, } RECIPE.result = { ["poor_bandage"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "splint_making" RECIPE.name = "Самодельная шина" RECIPE.category = "Медицина" RECIPE.model = Model( "models/toussaint_paper13.mdl" ) RECIPE.desc = "Связать палки веревкой." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["mdc"] = 0.25 } RECIPE.requiredattrib = { ["mdc"] = 0 } RECIPE.items = { ["stick"] = 2, ["tie"] = 2 } RECIPE.result = { ["splint"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "glue_making" RECIPE.name = "Клей" RECIPE.category = "Разное" RECIPE.model = Model( "models/skyrim/ingredients/firesaltpile.mdl" ) RECIPE.desc = "Смешать растолчённый уголь с расплавленной смолой." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["str"] = 0 } RECIPE.requiredattrib = { ["str"] = 0 } RECIPE.items = { ["pitch"] = 2, ["coal"] = 1 } RECIPE.result = { ["glue"] = 3, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "grain_making" RECIPE.name = "Зерно" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Обработать колосья пшеницы." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["wheat"] = 2 } RECIPE.result = { ["seed_wheat"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_stone_making" RECIPE.name = "Груз камня" RECIPE.category = "Транспортировка: Запаковка" RECIPE.model = Model( "models/container3.mdl" ) RECIPE.desc = "Запаковать несколько булыжников." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["stone"] = 4 } RECIPE.result = { ["container_stone"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_stonebig_making" RECIPE.name = "Большой груз камня" RECIPE.category = "Транспортировка: Запаковка" RECIPE.model = Model( "models/container.mdl" ) RECIPE.desc = "Запаковать несколько малых грузов камня." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["container_stone"] = 4 } RECIPE.result = { ["container_stonebig"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_wood_making" RECIPE.name = "Груз древесины" RECIPE.category = "Транспортировка: Запаковка" RECIPE.model = Model( "models/container3.mdl" ) RECIPE.desc = "Запаковать несколько бревен." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["wood"] = 4 } RECIPE.result = { ["container_wood"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_woodbig_making" RECIPE.name = "Большой груз древесины" RECIPE.category = "Транспортировка: Запаковка" RECIPE.model = Model( "models/container.mdl" ) RECIPE.desc = "Запаковать несколько малых грузов древесины." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["container_wood"] = 4 } RECIPE.result = { ["container_woodbig"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_stone_unpack" RECIPE.name = "Распаковать груз камня" RECIPE.category = "Транспортировка: Распаковка" RECIPE.model = Model( "models/container3.mdl" ) RECIPE.desc = "Распаковать несколько булыжников." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["container_stone"] = 1 } RECIPE.result = { ["stone"] = 4, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_stonebig_unpack" RECIPE.name = "Распаковать большой груз камня" RECIPE.category = "Транспортировка: Распаковка" RECIPE.model = Model( "models/container.mdl" ) RECIPE.desc = "Распаковать несколько малых грузов камня." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["container_stonebig"] = 1 } RECIPE.result = { ["container_stone"] = 4, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_wood_unpack" RECIPE.name = "Распаковать груз древесины" RECIPE.category = "Транспортировка: Распаковка" RECIPE.model = Model( "models/container3.mdl" ) RECIPE.desc = "Распаковать несколько бревен." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["container_wood"] = 1 } RECIPE.result = { ["wood"] = 4, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "container_woodbig_unpack" RECIPE.name = "Распаковать большой груз древесины" RECIPE.category = "Транспортировка: Распаковка" RECIPE.model = Model( "models/container.mdl" ) RECIPE.desc = "Распаковать несколько малых грузов древесины." RECIPE.noBlueprint = true RECIPE.place = 8 RECIPE.updateattrib = { ["cook"] = 0 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["container_woodbig"] = 1 } RECIPE.result = { ["container_wood"] = 4, } RECIPES:Register( RECIPE ) --Кулинария local RECIPE = {} RECIPE.uid = "water_pure" RECIPE.name = "Чистая вода" RECIPE.category = "Разное" RECIPE.model = Model( "models/props/furnitures/gob/l6_jar/l6_jar.mdl" ) RECIPE.desc = "Стоит вскипятить водичку, чтобы не заболеть чем-нибудь." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["str"] = 0 } RECIPE.requiredattrib = { ["str"] = 0 } RECIPE.items = { ["water_dirt"] = 1, } RECIPE.result = { ["water"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spice_making" RECIPE.name = "Пряности" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть сушеную траву и засыпать в мешочек." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["balissa"] = 1 } RECIPE.result = { ["spice"] = 2, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spice1_making" RECIPE.name = "Пряности" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть сушеную траву и засыпать в мешочек." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["berberika"] = 1 } RECIPE.result = { ["spice"] = 2, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spice2_making" RECIPE.name = "Пряности" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть сушеную траву и засыпать в мешочек." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["verbena"] = 1 } RECIPE.result = { ["spice"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spice3_making" RECIPE.name = "Пряности" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть сушеную траву и засыпать в мешочек." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["mirt"] = 1 } RECIPE.result = { ["spice"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spice4_making" RECIPE.name = "Пряности" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть сушеную траву и засыпать в мешочек." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["pautinnik"] = 1 } RECIPE.result = { ["spice"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spice5_making" RECIPE.name = "Пряности" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть сушеную траву и засыпать в мешочек." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["voronglaz"] = 1 } RECIPE.result = { ["spice"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "spice6_making" RECIPE.name = "Пряности" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть сушеную траву и засыпать в мешочек." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["giacinia"] = 1 } RECIPE.result = { ["spice"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "flour_making" RECIPE.name = "Мука" RECIPE.category = "Разное" RECIPE.model = Model( "models/items/jewels/purses/big_purse.mdl" ) RECIPE.desc = "Перемолоть зерно в муку." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.2 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["seed_wheat"] = 2 } RECIPE.result = { ["flour"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "stufat_making" RECIPE.name = "Стуфат" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/plates7.mdl" ) RECIPE.desc = "Тушеная козлятина." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 20 } RECIPE.items = { ["goat_grill"] = 2, ["onion"] = 1, ["water"] = 1, ["bowl"] = 1, } RECIPE.result = { ["stufat"] = 1, ["water_empty"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "shnicel_making" RECIPE.name = "Шницель" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/aoc_outdoor/meat_03.mdl" ) RECIPE.desc = "Нежная оленина." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 25 } RECIPE.items = { ["deer_meat"] = 2, ["onion"] = 1, } RECIPE.result = { ["shnicel"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "perko_making" RECIPE.name = "Пёркёльт" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/plates7.mdl" ) RECIPE.desc = "Тушеная с луком и специями курица." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 15 } RECIPE.items = { ["chicken"] = 1, ["onion"] = 2, ["spice"] = 1, ["water"] = 1, } RECIPE.result = { ["perko"] = 1, ["water_empty"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "knedlik_making" RECIPE.name = "Кнедлик" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/items/provisions/bread01/bread01_cooked.mdl" ) RECIPE.desc = "Отварное изделие из картофеля по форме напоминающее батон." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 35 } RECIPE.items = { ["potato"] = 3, ["flour"] = 1, ["spice"] = 1, ["water"] = 1, } RECIPE.result = { ["knedlik"] = 1, ["water_empty"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "colduni_making" RECIPE.name = "Колдуны" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/props_phx/misc/potato.mdl" ) RECIPE.desc = "Простейшая еда обладающая волшебным вкусом." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 5 } RECIPE.items = { ["fish"] = 2, ["egg"] = 1, ["flour"] = 2, ["water"] = 1, } RECIPE.result = { ["colduni"] = 1, ["water_empty"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "chewapchichi_making" RECIPE.name = "Чевапчичи" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/props_phx/misc/potato.mdl" ) RECIPE.desc = "Колбаски из мяса с луком, хорошо идут с хлебом." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 10 } RECIPE.items = { ["deer_meat"] = 2, ["onion"] = 2, } RECIPE.result = { ["chewapchichi"] = 2, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "blini_making" RECIPE.name = "Блины" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/items/provisions/pie/pie.mdl" ) RECIPE.desc = "Если нет тарелки, можно есть с лопаты." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 10 } RECIPE.items = { ["egg"] = 2, ["flour"] = 1, ["water"] = 1, } RECIPE.result = { ["water_empty"] = 1, ["blini"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "bear_grill_making" RECIPE.name = "Тушеная медвежатина" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/aoc_outdoor/meat_03.mdl" ) RECIPE.desc = "Не дели шкуру неубитого медведя. Неизвестно, распространяется ли эта поговорка на мясо." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 10 } RECIPE.items = { ["bear_meat"] = 1, ["onion"] = 2, ["tomato"] = 2, ["spice"] = 1, } RECIPE.result = { ["bear_grill"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "guvecho_making" RECIPE.name = "Гувеч" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/plates7.mdl" ) RECIPE.desc = "Куриный гуляш с добавлением лука, помидоров и картофеля." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 40 } RECIPE.items = { ["bowl"] = 1, ["chicken"] = 1, ["onion"] = 1, ["tomato"] = 2, ["potato"] = 1, ["spice"] = 1, } RECIPE.result = { ["guvecho"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "bread_making" RECIPE.name = "Хлеб" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/items/provisions/bread01/bread01_cooked.mdl" ) RECIPE.desc = "Подумой." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["flour"] = 2, ["water"] = 1, ["egg"] = 1, } RECIPE.result = { ["bread"] = 1, ["water_empty"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "kasha_making" RECIPE.name = "Пшеничная каша" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/plates7.mdl" ) RECIPE.desc = "Промыть крупу, залить водой и поставить к огню. Не забывать помешивать!" RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.5 } RECIPE.requiredattrib = { ["cook"] = 1 } RECIPE.items = { ["seed_wheat"] = 2, ["water"] = 1, } RECIPE.result = { ["kasha"] = 1, ["water_empty"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "bakedpotato_making" RECIPE.name = "Печёный картофель" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/props_phx/misc/potato.mdl" ) RECIPE.desc = "Поместить картофель в печь. Легче лёгкого." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.4 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["potato"] = 1, } RECIPE.result = { ["bakedpotato"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "grilled_goatmeat_making" RECIPE.name = "Жареная козлятина" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/items/provisions/ribs/ribs_cooked.mdl" ) RECIPE.desc = "Прожарить на огне." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.75 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["goat_meat"] = 1, ["spice"] = 1, } RECIPE.result = { ["goat_grill"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "grilled_wolfmeat_making" RECIPE.name = "Жареная волчатина" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/items/provisions/ribs/ribs_cooked.mdl" ) RECIPE.desc = "Прожарить на огне." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 0.75 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["wolf_meat"] = 1, ["spice"] = 1, } RECIPE.result = { ["wolf_grill"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "grilled_deermeat_making" RECIPE.name = "Вяленая оленина" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/items/provisions/ham_dry/ham_dry.mdl" ) RECIPE.desc = "Подкинуть ароматных травок в угли и закрыть хайло." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 0 } RECIPE.items = { ["deer_meat"] = 1, ["spice"] = 1 } RECIPE.result = { ["deer_val"] = 1, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "gulash_making" RECIPE.name = "Гуляш" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/plates7.mdl" ) RECIPE.desc = "Тушёная оленина с овощами." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 15 } RECIPE.items = { ["deer_meat"] = 1, ["water"] = 1, ["onion"] = 1, ["potato"] = 2, ["tomato"] = 1, ["flour"] = 1, ["bowl"] = 4, } RECIPE.result = { ["gulash"] = 4, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "sausage_making" RECIPE.name = "Колбаса" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/aoc_outdoor/sausage_01.mdl" ) RECIPE.desc = "Засунуть в промытую кишку скотины мясо другой скотины. Или этой же." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 20 } RECIPE.items = { ["goat_meat"] = 1, } RECIPE.result = { ["sausage"] = 2, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "zalivaka_making" RECIPE.name = "Махакамская заливайка" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/plates7.mdl" ) RECIPE.desc = "'Чтобы заливайку махакамскую приготовить, нужно следующее:'" RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 2 } RECIPE.requiredattrib = { ["cook"] = 50 } RECIPE.items = { ["deer_val"] = 1, ["pautinnik"] = 2, ["water"] = 1, ["onion"] = 2, ["potato"] = 2, ["flour"] = 1, ["bowl"] = 4 } RECIPE.result = { ["zalivaka"] = 4, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "omlet_making" RECIPE.name = "Омлет с колбасой и травами" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/items/provisions/pie/pie.mdl" ) RECIPE.desc = "Взболтать несколько яиц и поместить на сковороду." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1 } RECIPE.requiredattrib = { ["cook"] = 15 } RECIPE.items = { ["egg"] = 2, ["sausage"] = 1, ["spice"] = 1, } RECIPE.result = { ["omlet"] = 2, } RECIPES:Register( RECIPE ) local RECIPE = {} RECIPE.uid = "pureshka_making" RECIPE.name = "Картошка пюре с котлетками" RECIPE.category = "Кулинария: пища" RECIPE.model = Model( "models/plates7.mdl" ) RECIPE.desc = "Да ты поторопись! А то подгорит." RECIPE.noBlueprint = true RECIPE.place = 2 RECIPE.updateattrib = { ["cook"] = 1.5 } RECIPE.requiredattrib = { ["cook"] = 25 } RECIPE.items = { ["bear_meat"] = 1, ["potato"] = 2, ["spice"] = 1, ["bowl"] = 4, } RECIPE.result = { ["pureshka"] = 4, } RECIPES:Register( RECIPE ) --[[local RECIPE = {} RECIPE.uid = "steel_cuirass_smithing" RECIPE.name = "Стальная кираса" RECIPE.category = "Кузнечное ремесло" RECIPE.model = Model( "models/aoc_armour/gknight_breastplate.mdl" ) RECIPE.desc = "Кираса из крепкой стали." RECIPE.noBlueprint = true RECIPE.place = 3 RECIPE.updateattrib = { ["smith"] = 0.1 } RECIPE.requiredattrib = { ["smith"] = 3 } RECIPE.items = { ["iron"] = 8, ["leatherstrips"] = 4, } RECIPE.result = { ["cuirass"] = 1, } RECIPES:Register( RECIPE ) ]]
mit
gwash/ion-3
build/mkman.lua
3
7982
-- -- build/mkman.lua -- -- Translates bindings from Ion configuration into a listing for -- manual pages. -- -- Translations {{{ local translations={} local function gettext(x) local t=translations[x] if not t or t=="" then return x else return t end end local function TR(x, ...) return string.format(gettext(x), ...) end local function read_translations(pofile) local f, err=io.open(pofile) if not f then error(err) end local msgid, msgstr, st, en for l in f:lines() do if string.find(l, "^msgid") then if msgid then assert(msgstr) translations[msgid]=msgstr msgstr=nil end st, en, msgid=string.find(l, '^msgid%s*"(.*)"%s*$') elseif string.find(l, "^msgstr") then assert(msgid and not msgstr) st, en, msgstr=string.find(l, '^msgstr%s*"(.*)"%s*$') elseif not (string.find(l, "^%s*#") or string.find(l, "^%s*$")) then local st, en, str=string.find(l, '^%s*"(.*)"%s*$') assert(msgid or msgstr) if not msgstr then msgid=msgid..str else msgstr=msgstr..str end end end if msgid then assert(msgstr) translations[msgid]=msgstr end f:close() end -- }}} -- File parsing {{{ local function dobindings(fn, bindings) local p={} local dummy = function() end p.META="Mod1+" p.ALTMETA="" p.dopath=dummy p.defmenu=dummy p.defctxmenu=dummy p.menuentry=dummy p.submenu=dummy p.submap_enter=dummy p.submap_leave=dummy p.submap_wait=dummy p.ioncore={ set=dummy, } function p.bdoc(text) return {action = "doc", text = text} end function p.submap(kcb_, list) if not list then return function(lst) return p.submap(kcb_, lst) end end return {action = "kpress", kcb = kcb_, submap = list} end local function putcmd(cmd, guard, t) t.cmd=cmd t.guard=guard return t end function p.kpress(keyspec, cmd, guard) return putcmd(cmd, guard, {action = "kpress", kcb = keyspec}) end function p.kpress_wait(keyspec, cmd, guard) return putcmd(cmd, guard, {action = "kpress_wait", kcb = keyspec}) end local function mact(act_, kcb_, cmd, guard) local st, en, kcb2_, area_=string.find(kcb_, "([^@]*)@(.*)") return putcmd(cmd, guard, { action = act_, kcb = (kcb2_ or kcb_), area = area_, }) end function p.mclick(buttonspec, cmd, guard) return mact("mclick", buttonspec, cmd, guard) end function p.mdblclick(buttonspec, cmd, guard) return mact("mdblclick", buttonspec, cmd, guard) end function p.mpress(buttonspec, cmd, guard) return mact("mpress", buttonspec, cmd, guard) end function p.mdrag(buttonspec, cmd, guard) return mact("mdrag", buttonspec, cmd, guard) end function ins(t, v) if not t.seen then t.seen={} end if (not v.kcb) or v.submap then -- Submap rebinds are not presently handled table.insert(t, v) else local id=v.action..":"..v.kcb..":"..(v.area or "") local i=t.seen[id] if i then t[i].invalid=true end if v.cmd then table.insert(t, v) t.seen[id]=#t else -- Unbind only t.seen[id]=nil end end end function p.defbindings(context, bnd) if not bindings[context] then bindings[context]={} else -- Reset documentation table.insert(bindings[context], { action = "doc", text = nil }) end for _, v in ipairs(bnd) do ins(bindings[context], v) end end local env=setmetatable({}, { __index=p, __newindex=function(x) error("Setting global "..tostring(x)) end, }) setfenv(fn, env) fn() return bindings end local function parsefile(f, bindings) local fn, err=loadfile(f) if not fn then error(err) end return dobindings(fn, bindings) end -- }}} -- Binding output {{{ local function docgroup_bindings(bindings) local out={} local outi=0 local function parsetable(t, prefix) --for _, v in ipairs(t) do -- ipairs doesn't like nil values, that e.g. submap_wait dummy might generate for i=1,#t do local v=t[i] if v and not v.invalid then if v.kcb then v.kcb=string.gsub(v.kcb, "AnyModifier%+", "") end if v.action=="doc" then if outi==0 or #out[outi].bindings>0 then outi=outi+1 end out[outi]={doc=v.text, bindings={}} elseif v.submap then parsetable(v.submap, prefix..v.kcb.." ") else assert(out[outi]) v.kcb=prefix..v.kcb table.insert(out[outi].bindings, v) end end end end if outi~=0 and #out[outi].bindings==0 then out[outi]=nil end parsetable(bindings, "") return out end local function combine_bindings(v) local nact={ ["mpress"]=TR("press"), ["mclick"]=TR("click"), ["mdrag"]=TR("drag"), ["mdblclick"]=TR("double click"), } local first=true local s="" for _, b in ipairs(v.bindings) do if not first then s=s..', ' end first=false if b.action=="kpress" or b.action=="kpress_wait" then s=s..b.kcb else if not b.area then s=s..TR("%s %s", b.kcb, nact[b.action]) else s=s..TR("%s %s at %s", b.kcb, nact[b.action], b.area) end end end return s end local function write_bindings_man(db) local function write_binding_man(v) return '.TP\n.B '..combine_bindings(v)..'\n'..gettext(v.doc or "?")..'\n' end local s="" for _, v in ipairs(db) do if #(v.bindings)>0 then s=s..write_binding_man(v) end end return s end -- }}} -- Main {{{ local infile local outfile local bindings={} local replaces={} local function doargs(a) local i=1 while i<=#a do if a[i]=='-o' then outfile=a[i+1] i=i+2 elseif a[i]=='-i' then infile=a[i+1] i=i+2 elseif a[i]=='-D' then replaces[a[i+1]]=a[i+2] i=i+3 elseif a[i]=='-po' then read_translations(a[i+1]) i=i+2 else parsefile(a[i], bindings) i=i+1 end end end doargs({...}) local f, err=io.open(infile) if not f then error(err) end local of, oerr=io.open(outfile, 'w+') if not of then error(oerr) end for l in f:lines() do l=string.gsub(l, '%s*BINDINGS:([%w%.%-]+)%s*', function(s) if not bindings[s] then --error('No bindings for '..s) return "?" end local db=docgroup_bindings(bindings[s]) return write_bindings_man(db) end) for pat, rep in pairs(replaces) do l=string.gsub(l, pat, rep) end of:write(l..'\n') end -- }}}
lgpl-2.1
kuoruan/lede-luci
applications/luci-app-travelmate/luasrc/model/cbi/travelmate/wifi_edit.lua
7
6487
-- Copyright 2017-2018 Dirk Brenken (dev@brenken.org) -- This is free software, licensed under the Apache License, Version 2.0 local fs = require("nixio.fs") local uci = require("luci.model.uci").cursor() local http = require("luci.http") m = SimpleForm("edit", translate("Edit Wireless Uplink Configuration")) m.submit = translate("Save") m.cancel = translate("Back to overview") m.reset = false function m.on_cancel() http.redirect(luci.dispatcher.build_url("admin/services/travelmate/stations")) end m.hidden = { cfg = http.formvalue("cfg") } local s = uci:get_all("wireless", m.hidden.cfg) if s ~= nil then wssid = m:field(Value, "ssid", translate("SSID")) wssid.datatype = "rangelength(1,32)" wssid.default = s.ssid or "" bssid = m:field(Value, "bssid", translate("BSSID")) bssid.datatype = "macaddr" bssid.default = s.bssid or "" s.cipher = "auto" if string.match(s.encryption, '\+') and not string.match(s.encryption, '^wep') then s.pos = string.find(s.encryption, '\+') s.cipher = string.sub(s.encryption, s.pos + 1) s.encryption = string.sub(s.encryption, 0, s.pos - 1) end if s.encryption and s.encryption ~= "none" then if string.match(s.encryption, '^wep') then encr = m:field(ListValue, "encryption", translate("Encryption")) encr:value("wep", "WEP") encr:value("wep+open", "WEP Open System") encr:value("wep+mixed", "WEP mixed") encr:value("wep+shared", "WEP Shared Key") encr.default = s.encryption wkey = m:field(Value, "key", translate("Passphrase")) wkey.datatype = "wepkey" elseif string.match(s.encryption, '^psk') then encr = m:field(ListValue, "encryption", translate("Encryption")) encr:value("psk", "WPA PSK") encr:value("psk-mixed", "WPA/WPA2 mixed") encr:value("psk2", "WPA2 PSK") encr.default = s.encryption ciph = m:field(ListValue, "cipher", translate("Cipher")) ciph:value("auto", translate("Automatic")) ciph:value("ccmp", translate("Force CCMP (AES)")) ciph:value("tkip", translate("Force TKIP")) ciph:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)")) ciph.default = s.cipher wkey = m:field(Value, "key", translate("Passphrase")) wkey.datatype = "wpakey" elseif string.match(s.encryption, '^wpa') then encr = m:field(ListValue, "encryption", translate("Encryption")) encr:value("wpa", "WPA Enterprise") encr:value("wpa-mixed", "WPA/WPA2 Enterprise mixed") encr:value("wpa2", "WPA2 Enterprise") encr.default = s.encryption ciph = m:field(ListValue, "cipher", translate("Cipher")) ciph:value("auto", translate("Automatic")) ciph:value("ccmp", translate("Force CCMP (AES)")) ciph:value("tkip", translate("Force TKIP")) ciph:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)")) ciph.default = s.cipher eaptype = m:field(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("tls", "TLS") eaptype:value("ttls", "TTLS") eaptype:value("peap", "PEAP") eaptype:value("fast", "FAST") eaptype.default = s.eap_type or "peap" authentication = m:field(ListValue, "auth", translate("Authentication")) authentication:value("PAP") authentication:value("CHAP") authentication:value("MSCHAP") authentication:value("MSCHAPV2") authentication:value("EAP-GTC") authentication:value("EAP-MD5") authentication:value("EAP-MSCHAPV2") authentication:value("EAP-TLS") authentication:value("auth=PAP") authentication:value("auth=MSCHAPV2") authentication.default = s.auth or "EAP-MSCHAPV2" ident = m:field(Value, "identity", translate("Identity")) ident.default = s.identity or "" wkey = m:field(Value, "password", translate("Passphrase")) wkey.datatype = "wpakey" cacert = m:field(Value, "ca_cert", translate("Path to CA-Certificate")) cacert.rmempty = true cacert.default = s.ca_cert or "" clientcert = m:field(Value, "client_cert", translate("Path to Client-Certificate")) clientcert:depends("eap_type","tls") clientcert.rmempty = true clientcert.default = s.client_cert or "" privkey = m:field(Value, "priv_key", translate("Path to Private Key")) privkey:depends("eap_type","tls") privkey.rmempty = true privkey.default = s.priv_key or "" privkeypwd = m:field(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends("eap_type","tls") privkeypwd.datatype = "wpakey" privkeypwd.password = true privkeypwd.rmempty = true privkeypwd.default = s.priv_key_pwd or "" end wkey.password = true wkey.default = s.key or s.password end else m.on_cancel() end function wssid.write(self, section, value) uci:set("wireless", m.hidden.cfg, "ssid", wssid:formvalue(section)) uci:set("wireless", m.hidden.cfg, "bssid", bssid:formvalue(section)) if s.encryption and s.encryption ~= "none" then if string.match(s.encryption, '^wep') then uci:set("wireless", m.hidden.cfg, "encryption", encr:formvalue(section)) uci:set("wireless", m.hidden.cfg, "key", wkey:formvalue(section) or "") elseif string.match(s.encryption, '^psk') then if ciph:formvalue(section) ~= "auto" then uci:set("wireless", m.hidden.cfg, "encryption", encr:formvalue(section) .. "+" .. ciph:formvalue(section)) else uci:set("wireless", m.hidden.cfg, "encryption", encr:formvalue(section)) end uci:set("wireless", m.hidden.cfg, "key", wkey:formvalue(section) or "") elseif string.match(s.encryption, '^wpa') then if ciph:formvalue(section) ~= "auto" then uci:set("wireless", m.hidden.cfg, "encryption", encr:formvalue(section) .. "+" .. ciph:formvalue(section)) else uci:set("wireless", m.hidden.cfg, "encryption", encr:formvalue(section)) end uci:set("wireless", m.hidden.cfg, "eap_type", eaptype:formvalue(section)) uci:set("wireless", m.hidden.cfg, "auth", authentication:formvalue(section)) uci:set("wireless", m.hidden.cfg, "identity", ident:formvalue(section) or "") uci:set("wireless", m.hidden.cfg, "password", wkey:formvalue(section) or "") uci:set("wireless", m.hidden.cfg, "ca_cert", cacert:formvalue(section) or "") uci:set("wireless", m.hidden.cfg, "client_cert", clientcert:formvalue(section) or "") uci:set("wireless", m.hidden.cfg, "priv_key", privkey:formvalue(section) or "") uci:set("wireless", m.hidden.cfg, "priv_key_pwd", privkeypwd:formvalue(section) or "") end end uci:save("wireless") uci:commit("wireless") luci.sys.call("env -i /bin/ubus call network reload >/dev/null 2>&1") m.on_cancel() end return m
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/zones/south-beach/objects.lua
1
1185
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Talents = require "engine.interface.ActorTalents" local Stats = require "engine.interface.ActorStats" local DamageType = require "engine.DamageType" load("/data/general/objects/objects-maj-eyal.lua") newEntity{ base = "BASE_CLOTH_ARMOR", define_as = "MELINDA_BIKINI", name = "beach bikini", cost = 0.5, material_level = 1, moddable_tile = "special/bikini1", egos = false, egos_chance = false, }
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/achievements/lore.lua
1
2899
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newAchievement{ name = "Tales of the Spellblaze", id = "SPELLBLAZE_LORE", desc = [[Learned the eight chapters of the Spellblaze Chronicles.]], show = "full", mode = "player", can_gain = function(self, who, obj) if not game.party:knownLore("spellblaze-chronicles-1") then return false end if not game.party:knownLore("spellblaze-chronicles-2") then return false end if not game.party:knownLore("spellblaze-chronicles-3") then return false end if not game.party:knownLore("spellblaze-chronicles-4") then return false end if not game.party:knownLore("spellblaze-chronicles-5") then return false end if not game.party:knownLore("spellblaze-chronicles-6") then return false end if not game.party:knownLore("spellblaze-chronicles-7") then return false end if not game.party:knownLore("spellblaze-chronicles-8") then return false end return true end } newAchievement{ name = "The Legend of Garkul", id = "GARKUL_LORE", desc = [[Learned the five chapters of the Legend of Garkul.]], show = "full", mode = "player", can_gain = function(self, who, obj) if not game.party:knownLore("garkul-history-1") then return false end if not game.party:knownLore("garkul-history-2") then return false end if not game.party:knownLore("garkul-history-3") then return false end if not game.party:knownLore("garkul-history-4") then return false end if not game.party:knownLore("garkul-history-5") then return false end return true end, on_gain = function() game:unlockBackground("garkul", "Garkul") end, } newAchievement{ name = "A different point of view", id = "ORC_LORE", desc = [[Learned the five chapters of Orc history through loremaster Hadak's tales.]], show = "full", mode = "player", can_gain = function(self, who, obj) if not game.party:knownLore("orc-history-1") then return false end if not game.party:knownLore("orc-history-2") then return false end if not game.party:knownLore("orc-history-3") then return false end if not game.party:knownLore("orc-history-4") then return false end if not game.party:knownLore("orc-history-5") then return false end return true end }
gpl-3.0
wilbefast/snowman-ludumdare31
src/gameobjects/Particle.lua
1
3161
--[[ (C) Copyright 2014 William Dyce All rights reserved. This program and the accompanying materials are made available under the terms of the GNU Lesser General Public License (LGPL) version 2.1 which accompanies this distribution, and is available at http://www.gnu.org/licenses/lgpl-2.1.html This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. --]] local Particle = { type = GameObject.newType("Particle") } local n_particles = 0 --[[------------------------------------------------------------ Fire --]]-- local Fire = Class { type = Particle.type, FRICTION = 6, init = function(self, x, y, dx, dy, dz, sizeMult) GameObject.init(self, x, y, 0) self.dx, self.dy, self.dz = dx, dy, dz or 0 self.z = 0 self.t = 0 self.red = 200 + math.random()*55 self.green = 200 + math.random()*25 self.blue = 10 + math.random()*5 self.dieSpeed = 1.3 + 1.2*math.random() self.sizeMult = (sizeMult or 1) size = self.sizeMult*8 self.size = size*(1 + 0.5*math.random()) n_particles = n_particles + 1 end, } Fire:include(GameObject) function Fire:update(dt) self.t = self.t + self.dieSpeed*dt*(1 + n_particles/75) self.r = math.max(0, math.sin(self.t*math.pi)*self.size) if self.t > 1 then self.purge = true end GameObject.update(self, dt) self.z = self.z + self.dz*dt end function Fire:draw(x, y) x, y = self.x, self.y love.graphics.setColor(self.red, self.green, self.blue) useful.oval("fill", x, y - self.z, self.r, self.r) useful.bindWhite() light(x, y, self.z, (1 - self.t)*self.sizeMult) light(x, y - self.z, 0, (1 - self.t)*self.sizeMult) end function Fire:onPurge() n_particles = n_particles - 1 end Particle.Fire = Fire --[[------------------------------------------------------------ Smoke --]]-- local Smoke = Class { type = Particle.type, FRICTION = 100, init = function(self, x, y, dx, dy, dz, size) GameObject.init(self, x, y, 0) self.dx, self.dy, self.dz = dx, dy, dz or 0 self.z = 0 self.t = 0 self.a = 50 + math.random()*55 size = (size or 1)*10 self.size = size*(1 + 0.5)*math.random() self.dieSpeed = 0.5 + math.random()*0.7 n_particles = n_particles + 1 end, } Smoke:include(GameObject) function Smoke:update(dt) self.t = self.t + self.dieSpeed*dt*(1 + n_particles/75) self.r = math.max(1, math.sin(self.t*math.pi)*self.size) if self.t > 1 then self.purge = true end GameObject.update(self, dt) self.z = self.z + self.dz*dt end function Smoke:draw(x, y) local r = self.r local shad_r = math.min(r, 32*r/self.z) useful.pushCanvas(SHADOW_CANVAS) useful.oval("fill", x, y, shad_r, shad_r*VIEW_OBLIQUE) useful.popCanvas() love.graphics.setColor(self.a, self.a, self.a) useful.oval("fill", x, y - self.z, r, r) useful.bindWhite() end function Smoke:onPurge() n_particles = n_particles - 1 end Particle.Smoke = Smoke --[[------------------------------------------------------------ Export --]]-- return Particle
mit
hexahedronic/basewars
basewars_free/gamemode/modules/player_util.lua
2
3897
MODULE.Name = "Util_Player" MODULE.Author = "Q2F2 & Ghosty" local tag = "BaseWars.Util_Player" local PLAYER = debug.getregistry().Player if SERVER then util.AddNetworkString(tag) end function MODULE:HandleNetMessage(len, ply) local Mode = net.ReadUInt(1) if CLIENT then local ply = LocalPlayer() if Mode == 0 then local text = net.ReadString() local col = net.ReadColor() self:Notification(ply, text, col) end end end net.Receive(tag, Curry(MODULE.HandleNetMessage)) function MODULE:Notification(ply, text, col) if SERVER then net.Start(tag) net.WriteUInt(0, 1) net.WriteString(text) net.WriteColor(col) if ply then net.Send(ply) else net.Broadcast() end BaseWars.UTIL.Log(ply, " -> ", text) return end MsgC(col, text, "\n") BaseWars.Notify:Add(text, col) end local notification = Curry(MODULE.Notification) Notify = notification PLAYER.Notify = notification function MODULE:NotificationAll(text, col) self:Notification(nil, text, col) end NotifyAll = Curry(MODULE.NotificationAll) function MODULE:Spawn(ply) local col = ply:GetInfo("cl_playercolor") ply:SetPlayerColor(Vector(col)) local col = Vector(ply:GetInfo("cl_weaponcolor")) if col:Length() == 0 then col = Vector(0.001, 0.001, 0.001) end ply:SetWeaponColor(col) end hook.Add("PlayerSpawn", tag .. ".Spawn", Curry(MODULE.Spawn)) function MODULE:EnableFlashlight(ply) ply:AllowFlashlight(true) end hook.Add("PlayerSpawn", tag .. ".EnableFlashlight", Curry(MODULE.EnableFlashlight)) function MODULE:PlayerSetHandsModel(ply, ent) local PlayerModel = player_manager.TranslateToPlayerModelName(ply:GetModel()) local HandsInfo = player_manager.TranslatePlayerHands(PlayerModel) if HandsInfo then ent:SetModel(HandsInfo.model) ent:SetSkin(HandsInfo.skin) ent:SetBodyGroups(HandsInfo.body) end end hook.Add("PlayerSetHandsModel", tag .. ".PlayerSetHandsModel", Curry(MODULE.PlayerSetHandsModel)) function MODULE:Stuck(ply, pos) local t = {} t.start = pos or ply:GetPos() t.endpos = t.start t.filter = ply t.mask = MASK_PLAYERSOLID t.mins = ply:OBBMins() t.maxs = ply:OBBMaxs() t = util.TraceHull(t) local ent = t.Entity return t.StartSolid or (ent and (ent:IsWorld() or IsValid(ent))) end PLAYER.Stuck = Curry(MODULE.Stuck) local function FindPassableSpace(ply, direction, step) local OldPos = ply:GetPos() local Origin = ply:GetPos() for i = 1, 11 do Origin = Origin + (step * direction) if not ply:Stuck(Origin) then return true, Origin end end return false, OldPos end function MODULE:UnStuck(ply, ang, scale) local NewPos = ply:GetPos() local OldPos = NewPos if not ply:Stuck() then return end local Ang = ang or ply:GetAngles() local Forward = Ang:Forward() local Right = Ang:Right() local Up = Ang:Up() local SearchScale = scale or 3 local Found Found, NewPos = FindPassableSpace(ply, Forward, -SearchScale) if not Found then Found, NewPos = FindPassableSpace(ply, Right, SearchScale) if not Found then Found, NewPos = FindPassableSpace(ply, Right, -SearchScale) if not Found then Found, NewPos = FindPassableSpace(ply, Up, -SearchScale) if not Found then Found, NewPos = FindPassableSpace(ply, Up, SearchScale) if not Found then Found, NewPos = FindPassableSpace(ply, Forward, SearchScale) if not Found then return false end end end end end end if OldPos == NewPos then return false else local HitString = math.floor(NewPos.x) .. "," .. math.floor(NewPos.y) .. "," .. math.floor(NewPos.z) BaseWars.UTIL.Log("USTK EVENT: ", ply, " -> [", HitString, "]") ply:SetPos(NewPos) return true end end PLAYER.UnStuck = Curry(MODULE.UnStuck)
mit
imblackman/bot
plugins/myinfo.lua
1
1563
-- Begin myinfo.lua local function run(msg, matches) if matches[1]:lower() == 'اطلاعات من' then function get_id(arg, data) local username if data.first_name_ then if data.username_ then username = '@'..data.username_ else username = 'یوزرنیم وجود ندارد❌❗️' end local telNum if data.phone_number_ then telNum = '+'..data.phone_number_ else telNum = '----' end local lastName if data.last_name_ then lastName = data.last_name_ else lastName = '----' end local rank if is_sudo(msg) then rank = 'سودو👤' elseif is_owner(msg) then rank = 'مدیر👤' elseif is_admin(msg) then rank = 'ادمین👤' elseif is_mod(msg) then rank = 'معاون👤' else rank = 'عضو عادی👤' end local text = '👤📄❄️اطلاعات شما:\n1⃣اسم اول:: '..data.first_name_..'\n2⃣اسم دوم: '..lastName..'\n🛂یوزرنیم: '..username..'\n👤ایدی: '..data.id_..'\nℹ️ایدی گروه: '..arg.chat_id..'\n📱شماره تلفن: '..telNum..' \n👥مقام: '..rank..'' tdcli.sendMessage(arg.chat_id, msg.id_, 1, text, 1, 'html') end end tdcli_function({ ID = 'GetUser', user_id_ = msg.sender_user_id_, }, get_id, {chat_id=msg.chat_id_, user_id=msg.sendr_user_id_}) end end return { patterns = { "^اطلاعات من$" }, run = run } -- END -- By @To0fan -- CHANNEL: @LuaError -- We Are The Best :-)
gpl-3.0
kuoruan/lede-luci
applications/luci-app-qos/luasrc/model/cbi/qos/qos.lua
36
2367
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" m = Map("qos", translate("Quality of Service"), translate("With <abbr title=\"Quality of Service\">QoS</abbr> you " .. "can prioritize network traffic selected by addresses, " .. "ports or services.")) s = m:section(TypedSection, "interface", translate("Interfaces")) s.addremove = true s.anonymous = false e = s:option(Flag, "enabled", translate("Enable")) e.rmempty = false c = s:option(ListValue, "classgroup", translate("Classification group")) c:value("Default", translate("default")) c.default = "Default" s:option(Flag, "overhead", translate("Calculate overhead")) s:option(Flag, "halfduplex", translate("Half-duplex")) dl = s:option(Value, "download", translate("Download speed (kbit/s)")) dl.datatype = "and(uinteger,min(1))" ul = s:option(Value, "upload", translate("Upload speed (kbit/s)")) ul.datatype = "and(uinteger,min(1))" s = m:section(TypedSection, "classify", translate("Classification Rules")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true s.sortable = true t = s:option(ListValue, "target", translate("Target")) t:value("Priority", translate("priority")) t:value("Express", translate("express")) t:value("Normal", translate("normal")) t:value("Bulk", translate("low")) local uci = require "luci.model.uci" uci.cursor():foreach("qos", "class", function (section) local n = section[".name"] if string.sub(n,-string.len("_down"))~="_down" then t:value(n) end end) t.default = "Normal" srch = s:option(Value, "srchost", translate("Source host")) srch.rmempty = true srch:value("", translate("all")) wa.cbi_add_knownips(srch) dsth = s:option(Value, "dsthost", translate("Destination host")) dsth.rmempty = true dsth:value("", translate("all")) wa.cbi_add_knownips(dsth) p = s:option(Value, "proto", translate("Protocol")) p:value("", translate("all")) p:value("tcp", "TCP") p:value("udp", "UDP") p:value("icmp", "ICMP") p.rmempty = true ports = s:option(Value, "ports", translate("Ports")) ports.rmempty = true ports:value("", translate("all")) bytes = s:option(Value, "connbytes", translate("Number of bytes")) comment = s:option(Value, "comment", translate("Comment")) return m
apache-2.0
saraedum/luci-packages-old
applications/luci-statistics/luasrc/statistics/i18n.lua
9
2465
--[[ Luci statistics - diagram i18n helper (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- 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 self.i18n.loadc("rrdtool") self.i18n.loadc("statistics") 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._translate( self, key, alt ) local val = self.i18n.string(key) if val ~= key then return val else return alt end 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 self:_translate( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self:_translate( string.format( "stat_ds_%s_%s", source.type, source.instance ), self:_translate( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self:_translate( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
apache-2.0
tdelc/EmptyEpsilon
scripts/scenario_51_deliverAmbassador.lua
1
53027
-- Name: Deliver Ambassador Gremus -- Description: Unrest on Goltin 7 requires the skills of ambassador Gremus. Your mission: transport the ambassador wherever needed. You may encounter resistance. --- --- You are not flying a destroyer bristling with weapons. You are on a transport freighter with weapons bolted on as an afterthought. These weapons are pointed behind you to deter any marauding pirates. You won't necessarily be able to just destroy any enemies that might attempt to stop you from accomplishing your mission, you may have to evade. The navy wants you to succeed, so has fitted your ship with warp drive and a single diverse ordnance weapons tube which includes nuclear capability. If you get lost or forget your orders, check in with stations for information. --- --- Player ship: Template model: Flavia P. Falcon. Suggest turning music volume to 10% and sound volume to 100% on server --- --- Version 2 -- Type: Mission -- Variation[Hard]: More enemies -- Variation[Easy]: Fewer enemies require("utils.lua") function init() playerCallSign = "Carolina" player = PlayerSpaceship():setFaction("Human Navy"):setTemplate("Flavia P.Falcon") player:setPosition(22400, 18200):setCallSign(playerCallSign) -- Create various stations of various size, purpose and faction. outpost41 = SpaceStation():setTemplate("Small Station"):setFaction("Human Navy"):setCommsScript(""):setCommsFunction(commsStation) outpost41:setPosition(22400, 16100):setCallSign("Outpost-41"):setDescription("Strategically located human station") outpost17 = SpaceStation():setTemplate("Small Station"):setFaction("Independent") outpost17:setPosition(52400, -26150):setCallSign("Outpost-17") outpost26 = SpaceStation():setTemplate("Small Station"):setFaction("Independent") outpost26:setPosition(-42400, -32150):setCallSign("Outpost-26") outpost13 = SpaceStation():setTemplate("Small Station"):setFaction("Independent"):setCommsScript(""):setCommsFunction(commsStation) outpost13:setPosition(12600, 27554):setCallSign("Outpost-13"):setDescription("Gathering point for asteroid miners") outpost57 = SpaceStation():setTemplate("Small Station"):setFaction("Kraylor") outpost57:setPosition(63630, 47554):setCallSign("Outpost-57") science22 = SpaceStation():setTemplate("Small Station"):setFaction("Independent") science22:setPosition(11200, 67554):setCallSign("Science-22") science37 = SpaceStation():setTemplate("Small Station"):setFaction("Human Navy"):setCommsScript(""):setCommsFunction(commsStation) science37:setPosition(-18200, -32554):setCallSign("Science-37"):setDescription("Observatory") bpcommnex = SpaceStation():setTemplate("Small Station"):setFaction("Independent"):setCommsScript(""):setCommsFunction(commsStation) bpcommnex:setPosition(-53500,84000):setCallSign("BP Comm Nex"):setDescription("Balindor Prime Communications Nexus") goltincomms = SpaceStation():setTemplate("Small Station"):setFaction("Independent") goltincomms:setPosition(93150,24387):setCallSign("Goltin Comms") stationOrdinkal = SpaceStation():setTemplate("Medium Station"):setFaction("Independent"):setCommsScript(""):setCommsFunction(commsStation) stationOrdinkal:setPosition(-14600, 47554):setCallSign("Ordinkal"):setDescription("Trading Post") stationNakor = SpaceStation():setTemplate("Medium Station"):setFaction("Independent"):setCommsScript(""):setCommsFunction(commsStation) stationNakor:setPosition(-34310, -37554):setCallSign("Nakor"):setDescription("Science and trading hub") stationKelfist = SpaceStation():setTemplate("Medium Station"):setFaction("Kraylor") stationKelfist:setPosition(44640, 13554):setCallSign("Kelfist") stationFranklin = SpaceStation():setTemplate("Large Station"):setFaction("Human Navy"):setCommsScript(""):setCommsFunction(commsStation) stationFranklin:setPosition(-24640, -13554):setCallSign("Franklin"):setDescription("Civilian and military station") stationBroad = SpaceStation():setTemplate("Large Station"):setFaction("Independent") stationBroad:setPosition(44340, 63554):setCallSign("Broad"):setDescription("Trading Post") stationBazamoana = SpaceStation():setTemplate("Large Station"):setFaction("Independent") stationBazamoana:setPosition(35, 87):setCallSign("Bazamoana"):setDescription("Trading Nexus") stationPangora = SpaceStation():setTemplate("Huge Station"):setFaction("Human Navy"):setCommsScript(""):setCommsFunction(commsStation) stationPangora:setPosition(72340, -23554):setCallSign("Pangora"):setDescription("Major military installation") -- Give out some initial reputation points. Give more for easier difficulty levels stationFranklin:addReputationPoints(50.0) if getScenarioVariation() ~= "Hard" then stationFranklin:addReputationPoints(100.0) end -- Create some asteroids and nebulae createRandomAlongArc(Asteroid, 40, 30350, 20000, 11000, 310, 45, 1700) createRandomAlongArc(Asteroid, 65, 20000, 20000, 15000, 80, 160, 3500) createRandomAlongArc(Asteroid, 100, -30000, 38000, 35000, 270, 340, 3500) createObjectsOnLine(-29000, 3000, -50000, 3000, 400, Asteroid, 13, 8, 800) createObjectsOnLine(-50000, 3000, -60000, 5000, 400, Asteroid, 8, 6, 800) createObjectsOnLine(-60000, 5000, -70000, 7000, 400, Asteroid, 5, 4, 800) createRandomAlongArc(Asteroid, 800, 60000, -20000, 190000, 140, 210, 60000) createRandomAlongArc(Nebula, 11, -20000, 40000, 30000, 20, 160, 11000) createRandomAlongArc(Nebula, 18, 70000, -50000, 55000, 90, 180, 18000) -- Have players face a hostile enemy right away (more if difficulty is harder) kraylorChaserList = {} kraylorChaser1 = CpuShip():setTemplate("Phobos T3"):setFaction("Kraylor"):setPosition(24000,18200):setHeading(270) kraylorChaser1:orderAttack(player):setScanned(true) table.insert(kraylorChaserList,kraylorChaser1) if getScenarioVariation() ~= "Easy" then kraylorChaser2 = CpuShip():setTemplate("Phobos T3"):setFaction("Kraylor"):setPosition(24000,18600):setHeading(270) kraylorChaser2:orderFlyFormation(kraylorChaser1,0,400):setScanned(true) table.insert(kraylorChaserList,kraylorChaser2) end if getScenarioVariation() == "Hard" then kraylorChaser3 = CpuShip():setTemplate("Phobos T3"):setFaction("Kraylor"):setPosition(24000,17800):setHeading(270) kraylorChaser3:orderFlyFormation(kraylorChaser1,0,-400):setScanned(true) table.insert(kraylorChaserList,kraylorChaser3) end -- Take station and transport generation script and use with modifications stationList = {} transportList = {} tmp = SupplyDrop() for _, obj in ipairs(tmp:getObjectsInRange(300000)) do if obj.typeName == "SpaceStation" then table.insert(stationList, obj) end end tmp:destroy() maxTransport = math.floor(#stationList * 1.5) transportPlot = transportSpawn plot1 = chasePlayer -- Start main plot line end function randomStation() idx = math.floor(random(1, #stationList + 0.99)) return stationList[idx] end function transportSpawn(delta) -- Remove any stations from the list if they have been destroyed if #stationList > 0 then for idx, obj in ipairs(stationList) do if not obj:isValid() then table.remove(stationList, idx) end end end cnt = 0 -- Initialize transport count -- Count transports, remove destroyed transports from list, send transport to random station if docked if #transportList > 0 then for idx, obj in ipairs(transportList) do if not obj:isValid() then --Transport destroyed, remove it from the list table.remove(transportList, idx) else if obj:isDocked(obj.target) then if obj.undock_delay > 0 then obj.undock_delay = obj.undock_delay - delta else obj.target = randomStation() obj.undock_delay = random(5, 30) obj:orderDock(obj.target) end end cnt = cnt + 1 end end end -- Create another transport if fewer than maximum present, send to random station if cnt < maxTransport then target = randomStation() if target:isValid() then rnd = irandom(1,5) if rnd == 1 then name = "Personnel" elseif rnd == 2 then name = "Goods" elseif rnd == 3 then name = "Garbage" elseif rnd == 4 then name = "Equipment" else name = "Fuel" end if irandom(1,100) < 15 then name = name .. " Jump Freighter " .. irandom(3, 5) else name = name .. " Freighter " .. irandom(1, 5) end obj = CpuShip():setTemplate(name):setFaction('Independent') obj.target = target obj.undock_delay = random(5, 30) obj:orderDock(obj.target) x, y = obj.target:getPosition() xd, yd = vectorFromAngle(random(0, 360), random(25000, 40000)) obj:setPosition(x + xd, y + yd) table.insert(transportList, obj) end end transportPlot = transportWait transportDelay = 0.0 end function transportWait(delta) transportDelay = transportDelay + delta if transportDelay > 8 then transportPlot = transportSpawn end end -- Chase player until enemies destroyed or player gets away function chasePlayer(delta) kraylorChaserCount = 0 nearestChaser = 0 askForOrders = "orders" -- Turn on order messages in station communications for _, enemy in ipairs(kraylorChaserList) do if enemy:isValid() then kraylorChaserCount = kraylorChaserCount + 1 if nearestChaser == 0 then nearestChaser = distance(player, enemy) else nearestChaser = math.min(nearestChaser, distance(player,enemy)) end end end if kraylorChaserCount == 0 then plot1 = getAmbassador elseif nearestChaser > 6000 then plot1 = getAmbassador end end -- Tell player to get the ambassador. Create the planet. Start the revolution delay timer function getAmbassador(delta) outpost41:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: CMDMICHL012") player:addToShipLog(string.format("[CMDMICHL012](Commander Michael) %s, avoid contact where possible. Get ambassador Gremus at Balindor Prime",playerCallSign),"Yellow") if playMsgMichaelButton == nil then playMsgMichaelButton = "play" player:addCustomButton("Relay",playMsgMichaelButton,"|> CMDMICHL012",playMsgMichael) end balindorPrime = Planet():setPosition(-50500,84000):setPlanetRadius(3000):setDistanceFromMovementPlane(-2000):setPlanetSurfaceTexture("planets/planet-1.png"):setPlanetCloudTexture("planets/clouds-1.png"):setPlanetAtmosphereTexture("planets/atmosphere.png"):setPlanetAtmosphereColor(0.2,0.2,1.0):setAxialRotationTime(400.0) plot1 = ambassadorAboard ambassadorEscapedBalindor = false fomentTimer = 0.0 plot2 = revolutionFomenting plot3 = balindorInterceptor askForBalindorLocation = "ready" end function playMsgMichael() playSoundFile("sa_51_Michael.wav") player:removeCustom(playMsgMichaelButton) end -- Update delay timer. Once timer expires, start revolution timer. Tell player about limited time for mission function revolutionFomenting(delta) fomentTimer = fomentTimer + delta if fomentTimer > 60 then bpcommnex:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: AMBGREMUS001") player:addToShipLog("[AMBGREMUS001](Ambassador Gremus) I am glad you are coming to get me. There is serious unrest here on Balindor Prime. I am not sure how long I am going to survive. Please hurry, I can hear a mob outside my compound.","Yellow") if playMsgGremus1Button == nil then playMsgGremus1Button = "play" player:addCustomButton("Relay",playMsgGremus1Button,"|> AMBGREMUS001",playMsgGremus1) end breakoutTimer = 0.0 plot2 = revolutionOccurs end end function playMsgGremus1() playSoundFile("sa_51_Gremus1.wav") player:removeCustom(playMsgGremus1Button) end -- Update revolution timer. If timer expires before ship arrives, Gremus dies and mission fails. function revolutionOccurs(delta) breakoutTimer = breakoutTimer + delta if breakoutTimer > 60 * 5 then if ambassadorEscapedBalindor then bpcommnex:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: GREMUSGRD003") player:addToShipLog("[GREMUSGRD003](Compound Sentry) You got ambassador Gremus just in time. We barely escaped the mob with our lives. I don't recommend bringing the ambassador back anytime soon.","Yellow") if playMsgSentry1Button == nil then playMsgSentry1Button = "play" player:addCustomButton("Relay",playMsgSentry1Button,"|> GREMUSGRD003",playMsgSentry1) end plot2 = nil else globalMessage([[Ambassador lost to hostile mob. The Kraylors are victorious]]) bpcommnex:sendCommsMessage(player, [[(Compound Sentry) I'm sad to report the loss of ambassador Gremus to a hostile mob.]]) playSoundFile("sa_51_Sentry2.wav") plot2 = defeat end end end function playMsgSentry1() playSoundFile("sa_51_Sentry1.wav") player:removeCustomer(playMsgSentry1Button) end function defeat(delta) victory("Kraylor") end -- Create and send mission prevention enemies function balindorInterceptor(delta) if distance(player,-50500,84000) < 35000 then local ao = 20000 -- ambush offset local fo = 1000 -- formation offset kraylorBalindorInterceptorList = {} local x, y = player:getPosition() kraylorBalindorInterceptor1 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x-ao,y+ao):setHeading(45) kraylorBalindorInterceptor1:orderAttack(player) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor1) kraylorBalindorInterceptor2 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x-(ao+fo),y+ao):setHeading(45) kraylorBalindorInterceptor2:orderFlyFormation(kraylorBalindorInterceptor1,fo,0) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor2) kraylorBalindorInterceptor3 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x+ao,y-ao):setHeading(225) kraylorBalindorInterceptor3:orderAttack(player) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor3) kraylorBalindorInterceptor4 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x+ao+fo,y-ao):setHeading(225) kraylorBalindorInterceptor4:orderFlyFormation(kraylorBalindorInterceptor3,-fo,0) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor4) if getScenarioVariation() ~= "Easy" then kraylorBalindorInterceptor5 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x-ao,y+ao+fo):setHeading(45) kraylorBalindorInterceptor5:orderFlyFormation(kraylorBalindorInterceptor1,0,fo) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor5) kraylorBalindorInterceptor6 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x-(ao+fo),y+ao+fo):setHeading(45) kraylorBalindorInterceptor6:orderFlyFormation(kraylorBalindorInterceptor1,fo,fo) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor6) kraylorBalindorInterceptor7 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x+ao,y-(ao+fo)):setHeading(225) kraylorBalindorInterceptor7:orderFlyFormation(kraylorBalindorInterceptor3,0,-fo) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor7) kraylorBalindorInterceptor8 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x+ao+fo,y-(ao+fo)):setHeading(225) kraylorBalindorInterceptor8:orderFlyFormation(kraylorBalindorInterceptor3,-fo,-fo) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor8) end if getScenarioVariation() == "Hard" then kraylorBalindorInterceptor9 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x-ao,y+ao+fo*2):setHeading(45) kraylorBalindorInterceptor9:orderFlyFormation(kraylorBalindorInterceptor1,0,fo*2) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor9) kraylorBalindorInterceptor10 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x-(ao+fo*2),y+ao):setHeading(45) kraylorBalindorInterceptor10:orderFlyFormation(kraylorBalindorInterceptor1,fo*2,0) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor10) kraylorBalindorInterceptor11 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x+ao,y-(ao+fo*2)):setHeading(225) kraylorBalindorInterceptor11:orderFlyFormation(kraylorBalindorInterceptor3,0,-fo*2) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor11) kraylorBalindorInterceptor12 = CpuShip():setTemplate("Piranha F8"):setFaction("Kraylor"):setPosition(x+ao+fo*2,y-ao):setHeading(225) kraylorBalindorInterceptor12:orderFlyFormation(kraylorBalindorInterceptor3,-fo*2,0) table.insert(kraylorBalindorInterceptorList,kraylorBalindorInterceptor12) end plot3 = nil end end -- Now that Gremus is aboard, transport to Ningling requested. Create Ningling station function ambassadorAboard(delta) if distance(player, balindorPrime) < 3300 then ambassadorEscapedBalindor = true bpcommnex:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: AMBGREMUS004") player:addToShipLog("[AMBGREMUS004](Ambassador Gremus) Thanks for bringing me aboard. Please transport me to Ningling.","Yellow") if playMsgGremus2Button == nil then playMsgGremus2Button = "play" player:addCustomButton("Relay",playMsgGremus2Button,"|> AMBGREMUS004",playMsgGremus2) end playSoundFile("sa_51_Gremus2.wav") ningling = SpaceStation():setTemplate("Large Station"):setFaction("Human Navy"):setCommsScript(""):setCommsFunction(commsStation) ningling:setPosition(12200,-62600):setCallSign("Ningling") stationFranklin:addReputationPoints(25.0) if getScenarioVariation() ~= "Hard" then stationFranklin:addReputationPoints(25.0) end plot1 = gotoNingling plot3 = ningAttack askForNingLocation = "ready" end end function playMsgGremus2() playSoundFile("sa_51_Gremus2.wav") player:removeCustom(playMsgGremus2Button) end -- Create and send more enemies to stop mission function ningAttack(delta) if distance(player, balindorPrime) > 30000 then local ao = 10000 -- ambush offset local fo = 500 -- formation offset kraylorNingList = {} local x, y = player:getPosition() kraylorNing1 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x,y-ao):setHeading(180) kraylorNing1:orderAttack(player) table.insert(kraylorNingList,kraylorNing1) -- kraylorNing2 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x-fo*2,y-ao):setHeading(180) -- kraylorNing2:orderFlyFormation(kraylorNing1,-fo*2,0) -- table.insert(kraylorNingList,kraylorNing2) -- kraylorNing3 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x+fo*2,y-ao):setHeading(180) -- kraylorNing3:orderFlyFormation(kraylorNing1,fo*2,0) -- table.insert(kraylorNingList,kraylorNing3) kraylorNing4 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x,y+ao):setHeading(0) kraylorNing4:orderAttack(player) table.insert(kraylorNingList,kraylorNing4) -- kraylorNing5 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x-fo*2,y+ao):setHeading(0) -- kraylorNing5:orderFlyFormation(kraylorNing4,-fo*2,0) -- table.insert(kraylorNingList,kraylorNing5) -- kraylorNing6 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x+fo*2,y+ao):setHeading(0) -- kraylorNing6:orderFlyFormation(kraylorNing4,fo*2,0) -- table.insert(kraylorNingList,kraylorNing6) if getScenarioVariation() ~= "Easy" then kraylorNing7 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x-fo,y-ao-fo*2):setHeading(180) kraylorNing7:orderFlyFormation(kraylorNing1,-fo,-fo*2) table.insert(kraylorNingList,kraylorNing7) -- kraylorNing8 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x+fo,y-ao-fo*2):setHeading(180) -- kraylorNing8:orderFlyFormation(kraylorNing1,fo,-fo*2) -- table.insert(kraylorNingList,kraylorNing8) kraylorNing9 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x-fo,y+ao+fo*2):setHeading(0) kraylorNing9:orderFlyFormation(kraylorNing4,-fo,fo*2) table.insert(kraylorNingList,kraylorNing9) -- kraylorNing10 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x+fo,y+ao+fo*2):setHeading(0) -- kraylorNing10:orderFlyFormation(kraylorNing4,fo,fo*2) -- table.insert(kraylorNingList,kraylorNing10) end if getScenarioVariation() == "Hard" then kraylorNing11 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x-fo,y-ao+fo*2):setHeading(180) kraylorNing11:orderFlyFormation(kraylorNing1,-fo,fo*2) table.insert(kraylorNingList,kraylorNing11) -- kraylorNing12 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x+fo,y-ao+fo*2):setHeading(180) -- kraylorNing12:orderFlyFormation(kraylorNing1,fo,fo*2) -- table.insert(kraylorNingList,kraylorNing12) kraylorNing13 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x-fo,y+ao-fo*2):setHeading(0) kraylorNing13:orderFlyFormation(kraylorNing4,-fo,-fo*2) table.insert(kraylorNingList,kraylorNing13) -- kraylorNing14 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x+fo,y+ao-fo*2):setHeading(0) -- kraylorNing14:orderFlyFormation(kraylorNing4,fo,-fo*2) -- table.insert(kraylorNingList,kraylorNing14) end plot3 = nil end end -- Tell player to wait for Gremus to finish before next mission goal. Set meeting timer function gotoNingling(delta) if not ningling:isValid() then victory("Kraylor") end if player:isDocked(ningling) then ningling:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: NINGPCLO002") player:addToShipLog("[NINGPCLO002](Ningling Protocol Officer) Ambassador Gremus arrived. The ambassador is scheduled for a brief meeting with liaison Fordina. After that meeting, you will be asked to transport the ambassador to Goltin 7. We will contact you after the meeting.","Yellow") if playMsgProtocolButton == nil then playMsgProtocolButton = "play" player:addCustomButton("Relay",playMsgProtocolButton,"|> NINGPCLO002",playMsgProtocol) end playSoundFile("sa_51_Protocol.wav") plot1 = waitForAmbassador meetingTimer = 0.0 plot3 = ningWait end end function playMsgProtocol() playSoundFile("sa_51_Protocol.wav") player:removeCustom(playMsgProtocolButton) end -- While waiting, spawn more enemies to stop mission function ningWait(delta) local x, y = ningling:getPosition() local ao = 25000 local fo = 1200 waitNingList = {} waitNing1 = CpuShip():setTemplate("MT52 Hornet"):setFaction("Kraylor"):setPosition(x+ao,y+ao):setHeading(315) waitNing1:orderAttack(player) table.insert(waitNingList,waitNing1) if getScenarioVariation() ~= "Easy" then waitNing2 = CpuShip():setTemplate("MU52 Hornet"):setFaction("Kraylor"):setPosition(x+ao+fo,y+ao):setHeading(315) waitNing2:orderFlyFormation(waitNing1,fo,0) table.insert(waitNingList,waitNing2) waitNing3 = CpuShip():setTemplate("Adder MK4"):setFaction("Kraylor"):setPosition(x+ao,y+ao+fo):setHeading(315) waitNing3:orderFlyFormation(waitNing1,0,fo) table.insert(waitNingList,waitNing3) end if getScenarioVariation() == "Hard" then waitNing4 = CpuShip():setTemplate("Adder MK5"):setFaction("Kraylor"):setPosition(x+ao+fo*2,y+ao):setHeading(315) waitNing4:orderFlyFormation(waitNing1,fo*2,0) table.insert(waitNingList,waitNing4) waitNing5 = CpuShip():setTemplate("Adder MK5"):setFaction("Kraylor"):setPosition(x+ao,y+ao+fo*2):setHeading(315) waitNing5:orderFlyFormation(waitNing1,0,fo*2) table.insert(waitNingList,waitNing5) end plot3 = nil end -- When meeting completes, request dock for next mission goal function waitForAmbassador(delta) if not ningling:isValid() then victory("Kraylor") end meetingTimer = meetingTimer + delta if meetingTimer > 60 * 5 and not player:isDocked(ningling) then ningling:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: AMBGREMUS007") player:addToShipLog(string.format("[AMBGREMUS007](Ambassador Gremus) %s, I am ready to be transported to Goltin 7. Please dock with Ningling",playerCallSign),"Yellow") if playMsgGremus3Button == nil then playMsgGremus3Button = "play" player:addCustomButton("Relay",playMsgGremus3Button,"|> AMBGREMUS007",playMsgGremus3) end plot1 = getFromNingling end end function playMsgGremus3() playSoundFile("sa_51_Gremus3.wav") player:removeCustom(playMsgGremus3Button) end -- Set next goal: Goltin 7. Inform player. Create planet. Start sub-plots function getFromNingling(delta) if not ningling:isValid() then victory("Kraylor") end if player:isDocked(ningling) then ningling:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: AMBGREMUS021") player:addToShipLog("[AMBGREMUS021](Ambassador Gremus) Thank you for waiting and then for coming back and getting me. I needed the information provided by liaison Fordina to facilitate negotiations at Goltin 7. Let us away!","Yellow") player:addToShipLog("Reconfigured beam weapons: pointed one forward, increased range and narrowed focus of rearward","Magenta") if playMsgGremus4Button == nil then playMsgGremus4Button = "play" player:addCustomButton("Relay",playMsgGremus4Button,"|> AMBGREMUS021",playMsgGremus4) end player:setTypeName("Flavia P. Falcon MK2") player:setBeamWeapon(0, 40, 180, 1200.0, 6.0, 6) player:setBeamWeapon(1, 20, 0, 1600.0, 6.0, 6) goltin = Planet():setPosition(93150,21387):setPlanetRadius(3000):setDistanceFromMovementPlane(-2000):setPlanetSurfaceTexture("planets/gas-1.png"):setAxialRotationTime(80.0) artifactResearchCount = 0 plot1 = travelGoltin plot2 = lastSabotage plot3 = artifactResearch askForGoltinLocation = "ready" end end function playMsgGremus4() playSoundFile("sa_51_Gremus4.wav") player:removeCustom(playMsgGremus4Button) end -- Expand artifact sub-plot after player leaves Ningling function artifactResearch(delta) if distance(player, ningling) > 10000 then ningling:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: LSNFRDNA009") player:addToShipLog("[LSNFRDNA009](Liaison Fordina) Ambassador Gremus, we just received that follow-up information from Goltin 7 we spoke of. It seems they want additional information about several artifacts. Some of these have been reported by stations in the area: Pangora, Nakor and Science-37.","Yellow") if playMsgFordinaButton == nil then playMsgFordinaButton = "play" player:addCustomButton("Relay",playMsgFordinaButton,"|> LSNFRDNA009",playMsgFordina) end playSoundFile("sa_51_Fordina.wav") askForPangoraLocation = "ready" askForNakorLocation = "ready" askForScience37Location = "ready" plot3 = artifactByStation nearPangora = "ready" nearNakor = "ready" nearScience37 = "ready" end end function playMsgFordina() playSoundFile("sa_51_Fordina.wav") player:removeCustom(playMsgFordinaButton) end -- When the player docks, create the artifact nearby. Enable message additions to station relay messages function artifactByStation(delta) if player:isDocked(stationPangora) then if nearPangora == "ready" then x, y = stationPangora:getPosition() nPangora = Artifact():setPosition(x+35000,y+38000):setScanningParameters(3,2):setRadarSignatureInfo(random(2,8),random(2,8),random(2,8)) nPangora:setModel("artifact3"):allowPickup(false) nPangora.beta_radiation = irandom(3,15) nPangora.gravity_disruption = irandom(1,21) nPangora.ionic_phase_shift = irandom(5,32) nPangora.doppler_instability = irandom(1,9) nPangora:setDescriptions("Unusual object floating in space", string.format([[Object gives off unusual readings: Beta radiation: %i Gravity disruption: %i Ionic phase shift: %i Doppler instability: %i]],nPangora.beta_radiation, nPangora.gravity_disruption, nPangora.ionic_phase_shift, nPangora.doppler_instability)) nearPangora = "created" end askForPangoraArtifactLocation = "ready" end if player:isDocked(stationNakor) then if nearNakor == "ready" then x, y = stationNakor:getPosition() nNakor = Artifact():setPosition(x-35000,y-36000):setScanningParameters(2,3):setRadarSignatureInfo(random(2,5),random(2,5),random(2,8)) nNakor:setModel("artifact5"):allowPickup(false) nNakor.gamma_radiation = irandom(1,9) nNakor.organic_decay = irandom(3,43) nNakor.gravity_disruption = irandom(2,13) nNakor:setDescription("Object with unusual visual properties", string.format([[Sensor readings of interest: Gamma radiation: %i Organic decay: %i Gravity disruption: %i]],nNakor.gamma_radiation, nNakor.organic_decay, nNakor.gravity_disruption)) nearNakor = "created" end askForNakorArtifactLocation = "ready" end if player:isDocked(science37) then if nearScience37 == "ready" then x, y = science37:getPosition() nScience37 = Artifact():setPosition(x+1000,y-40000):setScanningParameters(4,1):setRadarSignatureInfo(random(3,9),random(1,5),random(2,4)) nScience37:setModel("artifact6"):allowPickup(true) nScience37.ionic_phase_shift = irandom(1,9) nScience37.organic_decay = irandom(3,13) nScience37.theta_particle_emission = irandom(1,15) nScience37:setDescription("Small object floating in space", string.format([[Sensors show: Ionic pase shift: %i Organic decay: %i Theta particle emission: %i]],nScience37.ionic_phase_shift, nScience37.organic_decay, nScience37.theta_particle_emission)) nearScience37 = "created" end askForScience37ArtifactLocation = "ready" end if nPangora:isValid() then if nPangora:isScannedBy(player) then artifactResearchCount = artifactResearchCount + 1 end if distance(player,nPangora) < 5000 then pangoraExplodeCountdown = 0.0 nPangora.gravity_disruption = nPangora.gravity_disruption + 1 nPangora:setDescriptions("Unusual object floating in space", string.format([[Object gives off unusual readings: Beta radiation: %i Gravity disruption: %i Ionic phase shift: %i Doppler instability: %i]],nPangora.beta_radiation, nPangora.gravity_disruption, nPangora.ionic_phase_shift, nPangora.doppler_instability)) plot4 = pangoraArtifactChange end end if nNakor:isValid() then if nNakor:isScannedBy(player) then artifactResearchCount = artifactResearchCount + 1 end end if nScience37:isValid() then if nScience37:isScannedBy(player) then artifactResearchCount = artifactResearchCount + 1 end end end function pangoraArtifactChange(delta) player:addCustomMessage("Science", "Warning", "The readings on the Pangora artifact have changed") --not working plot4 = pangoraArtifactExplode end function pangoraArtifactExplode(delta) pangoraExplodeCountdown = pangoraExplodeCountdown + delta if pangoraExplodeCountdown > 15 then if distance(player,nPangora) < 6000 then player:setSystemHealth("reactor", player:getSystemHealth("reactor") - random(0.0, 0.5)) player:setSystemHealth("beamweapons", player:getSystemHealth("beamweapons") - random(0.0, 0.5)) player:setSystemHealth("maneuver", player:getSystemHealth("maneuver") - random(0.0, 0.5)) player:setSystemHealth("missilesystem", player:getSystemHealth("missilesystem") - random(0.0, 0.5)) player:setSystemHealth("impulse", player:getSystemHealth("impulse") - random(1.3, 1.5)) player:setSystemHealth("warp", player:getSystemHealth("warp") - random(1.3, 1.5)) player:setSystemHealth("jumpdrive", player:getSystemHealth("jumpdrive") - random(1.3, 1.5)) player:setSystemHealth("frontshield", player:getSystemHealth("frontshield") - random(0.0, 0.5)) player:setSystemHealth("rearshield", player:getSystemHealth("rearshield") - random(0.0, 0.5)) end nPangora:explode() player:removeCustom("Warning") plot4 = nil end end -- Last ditch attempt to sabotage mission - the big guns function lastSabotage(delta) if distance(player, ningling) > 40000 then local ao = 30000 local fo = 2500 local x, y = player:getPosition() goltinList = {} goltin1 = CpuShip():setTemplate("Atlantis X23"):setFaction("Kraylor"):setPosition(x+ao,y+ao):setHeading(315) goltin1:orderAttack(player) table.insert(goltinList,goltin1) goltin2 = CpuShip():setTemplate("Starhammer II"):setFaction("Kraylor"):setPosition(x,y+ao):setHeading(0) goltin2:orderAttack(player) table.insert(goltinList,goltin2) goltin3 = CpuShip():setTemplate("Stalker Q7"):setFaction("Kraylor"):setPosition(x+ao,y):setHeading(270) goltin3:orderAttack(player) table.insert(goltinList,goltin3) if getScenarioVariation() ~= "Easy" then goltin4 = CpuShip():setTemplate("Stalker R7"):setFaction("Kraylor"):setPosition(x+ao+fo,y+ao-fo):setHeading(315) goltin4:orderAttack(player) table.insert(goltinList,goltin4) goltin5 = CpuShip():setTemplate("Ranus U"):setFaction("Kraylor"):setPosition(x+fo,y+ao):setHeading(0) goltin5:orderAttack(player) table.insert(goltinList,goltin5) goltin6 = CpuShip():setTemplate("Phobos T3"):setFaction("Kraylor"):setPosition(x+ao,y-fo):setHeading(270) goltin6:orderAttack(player) table.insert(goltinList,goltin6) end if getScenarioVariation() == "Hard" then goltin7 = CpuShip():setTemplate("Nirvana R5"):setFaction("Kraylor"):setPosition(x+ao-fo,y+ao+fo):setHeading(315) goltin7:orderAttack(player) table.insert(goltinList,goltin7) goltin8 = CpuShip():setTemplate("Piranha F12"):setFaction("Kraylor"):setPosition(x-fo,y+ao):setHeading(0) goltin8:orderAttack(player) table.insert(goltinList,goltin8) goltin9 = CpuShip():setTemplate("Nirvana R5A"):setFaction("Kraylor"):setPosition(x+ao,y+fo):setHeading(270) goltin9:orderAttack(player) table.insert(goltinList,goltin9) end plot2 = nil end end -- Arrive at Goltin 7: win if research done or identify artifact research as required for mission completion. function travelGoltin(delta) if artifactResearchCount > 0 then if distance(player,goltin) < 3300 then globalMessage([[Goltin 7 welcomes ambassador Gremus]]) goltincomms:sendCommsMessage(player, "(Ambassador Gremus) Thanks for transporting me, "..playerCallSign..[[. Tensions are high, but I think negotiations will succeed. In the meantime, be careful of hostile ships.]]) playSoundFile("sa_51_Gremus5.wav") lastMessage = 0.0 plot1 = finalMessage end else if distance(player, goltin) < 3300 then goltincomms:sendCommsMessage(player, "Audio message received. Auto-transcribed into log. Stored for playback: AMBGREMUS032") player:addToShipLog(string.format("[AMBGREMUS032](Ambassador Gremus) Thanks for transporting me, %s. I will need artifact research for successful negotiation. Please return with that research when you can.",playerCallSign),"Yellow") if playMsgGremus6Button == nil then playMsgGremus6Button = "play" player:addCustomButton("Relay",playMsgGremus6Button,"|> AMBGREMUS021",playMsgGremus6) end plot1 = departForResearch end end end function playMsgGremus6() playSoundFile("sa_51_Gremus6.wav") player:removeCustom(playMsgGremus6Button) end function departForResearch(delta) if distance(player,goltin) > 30000 then plot1 = goltinAndResearch end end -- Win upon return with research function goltinAndResearch(delta) if artifactResearchCount > 0 then if distance(player,goltin) < 3300 then globalMessage([[Goltin 7 welcomes ambassador Gremus]]) goltincomms:sendCommsMessage(player, "(Ambassador Gremus) Thanks for researching the artifacts, "..playerCallSign..[[. Tensions are high, but I think negotiations will succeed. In the meantime, be careful of hostile ships.]]) playSoundFile("sa_51_Gremus7.wav") lastMessage = 0.0 plot1 = finalMessage end end end function finalMessage(delta) lastMessage = lastMessage + delta if lastMessage > 20 then plot1 = nil end end -- Incorporated stations communications script so that I can add messages as needed function commsStation() if comms_target.comms_data == nil then comms_target.comms_data = {} end mergeTables(comms_target.comms_data, { friendlyness = random(0.0, 100.0), weapons = { Homing = "neutral", HVLI = "neutral", Mine = "neutral", Nuke = "friend", EMP = "friend" }, weapon_cost = { Homing = 2, HVLI = 2, Mine = 2, Nuke = 15, EMP = 10 }, services = { supplydrop = "friend", reinforcements = "friend", }, service_cost = { supplydrop = 100, reinforcements = 150, }, reputation_cost_multipliers = { friend = 1.0, neutral = 2.5 }, max_weapon_refill_amount = { friend = 1.0, neutral = 0.5 } }) comms_data = comms_target.comms_data if player:isEnemy(comms_target) then return false end if comms_target:areEnemiesInRange(5000) then setCommsMessage("We are under attack! No time for chatting!"); return true end if not player:isDocked(comms_target) then handleUndockedState() else handleDockedState() end return true end function handleDockedState() -- Handle communications while docked with this station. if player:isFriendly(comms_target) then setCommsMessage("Good day, officer!\nWhat can we do for you today?") else setCommsMessage("Welcome to our lovely station.") end if player:getWeaponStorageMax("Homing") > 0 then addCommsReply("Do you have spare homing missiles for us? ("..getWeaponCost("Homing").."rep each)", function() handleWeaponRestock("Homing") end) end if player:getWeaponStorageMax("HVLI") > 0 then addCommsReply("Can you restock us with HVLI? ("..getWeaponCost("HVLI").."rep each)", function() handleWeaponRestock("HVLI") end) end if player:getWeaponStorageMax("Mine") > 0 then addCommsReply("Please re-stock our mines. ("..getWeaponCost("Mine").."rep each)", function() handleWeaponRestock("Mine") end) end if player:getWeaponStorageMax("Nuke") > 0 then addCommsReply("Can you supply us with some nukes? ("..getWeaponCost("Nuke").."rep each)", function() handleWeaponRestock("Nuke") end) end if player:getWeaponStorageMax("EMP") > 0 then addCommsReply("Please re-stock our EMP missiles. ("..getWeaponCost("EMP").."rep each)", function() handleWeaponRestock("EMP") end) end -- Include helpful location waypoint providers for handling large map if isAllowedTo(askForBalindorLocation) then addCommsReply("Where is Balindor Prime?", function() player:commandAddWaypoint(-50500,84000) setCommsMessage(string.format("Added waypoint %i to your navigation system for Balindor Prime",player:getWaypointCount())) askForBalindorLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForNingLocation) then addCommsReply("Where is Ningling?", function() player:commandAddWaypoint(12200,-62600) setCommsMessage(string.format("Added waypoint %i for Ningling station",player:getWaypointCount())) askForNingLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForGoltinLocation) then addCommsReply("Where is Goltin 7?", function() player:commandAddWaypoint(93150,21387) setCommsMessage(string.format("Added waypoint %i for Goltin 7",player:getWaypointCount())) askForGoltinLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForPangoraLocation) then addCommsReply("Where is Pangora?", function() player:commandAddWaypoint(stationPangora:getPosition()) setCommsMessage(string.format("Added waypoint %i for Pangora station",player:getWaypointCount())) askForPangoraLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForNakorLocation) then addCommsReply("Where is Nakor?", function() player:commandAddWaypoint(stationNakor:getPosition()) setCommsMessage(string.format("Added waypoint %i for Nakor station",player:getWaypointCount())) askForNakorLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForScience37Location) then addCommsReply("Where is Science-37?", function() player:commandAddWaypoint(science37:getPosition()) setCommsMessage(string.format("Added a waypoint %i for station Science-37",player:getWaypointCount())) askForScience37Location = "complete" addCommsReply("Back", commsStation) end) end -- Include clue messages for artifacts near identified stations if isAllowedTo(askForPangoraArtifactLocation) then addCommsReply("Any reports of artifacts near Pangora?", function() setCommsMessage("Some freighters report seeing an artifact on approximate heading 135 from Pangora") askForPangoraArtifactLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForNakorArtifactLocation) then addCommsReply("Heard of any artifacts near Nakor?", function() setCommsMessage("Some have reported seeing object on approximate heading of 315 from Nakor station") askForNakorArtifactLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForScience37ArtifactLocation) then addCommsReply("Has anyone reported seeing artifacts near Science-37?", function() setCommsMessage("Freighters doing business here occasionally report an object on approximate heading zero from Science-37 station") askForScience37ArtifactLocation = "complete" addCommsReply("Back", commsStation) end) end -- Include orders upon request for when they are missed if isAllowedTo(askForOrders) then addCommsReply("What are my current orders?", function() oMessage = "" if plot1 == chasePlayer or plot1 == getAmbassador or plot1 == ambassadorAboard then oMessage = "Current Orders: Get ambassador Gremus from Balindor Prime. Avoid contact if possible. " elseif plot1 == gotoNingling then oMessage = "Current Orders: Transport ambassador Gremus to Ningling. " elseif plot1 == waitForAmbassador then oMessage = "Current Orders: Wait for ambassador Gremus to complete business at Ningling. " elseif plot1 == getFromNingling then oMessage = "Current Orders: Dock with Ningling to get ambassador Gremus. " elseif plot1 == travelGoltin then oMessage = "Current Orders: Transport ambassador Gremus to Goltin 7. " end if plot3 == artifactResearch or plot3 == artifactByStation then oMessage = oMessage.."Additional Orders: Research artifacts. Some artifacts reported near Pangora, Nakor and Science-37. " if plot1 == departForResearch or plot1 == goltinAndResearch then oMessage = oMessage.."Provide artifact research to ambassador Gremus on Goltin 7. " end end setCommsMessage(oMessage) addCommsReply("Back", commsStation) end) end end function handleWeaponRestock(weapon) if not player:isDocked(comms_target) then setCommsMessage("You need to stay docked for that action."); return end if not isAllowedTo(comms_data.weapons[weapon]) then if weapon == "Nuke" then setCommsMessage("We do not deal in weapons of mass destruction.") elseif weapon == "EMP" then setCommsMessage("We do not deal in weapons of mass disruption.") else setCommsMessage("We do not deal in those weapons.") end return end local points_per_item = getWeaponCost(weapon) local item_amount = math.floor(player:getWeaponStorageMax(weapon) * comms_data.max_weapon_refill_amount[getFriendStatus()]) - player:getWeaponStorage(weapon) if item_amount <= 0 then if weapon == "Nuke" then setCommsMessage("All nukes are charged and primed for destruction."); else setCommsMessage("Sorry, sir, but you are as fully stocked as I can allow."); end addCommsReply("Back", commsStation) else if not player:takeReputationPoints(points_per_item * item_amount) then setCommsMessage("Not enough reputation.") return end player:setWeaponStorage(weapon, player:getWeaponStorage(weapon) + item_amount) if player:getWeaponStorage(weapon) == player:getWeaponStorageMax(weapon) then setCommsMessage("You are fully loaded and ready to explode things.") else setCommsMessage("We generously resupplied you with some weapon charges.\nPut them to good use.") end addCommsReply("Back", commsStation) end end function handleUndockedState() --Handle communications when we are not docked with the station. if player:isFriendly(comms_target) then setCommsMessage("Good day, officer.\nIf you need supplies, please dock with us first.") else setCommsMessage("Greetings.\nIf you want to do business, please dock with us first.") end if isAllowedTo(comms_target.comms_data.services.supplydrop) then addCommsReply("Can you send a supply drop? ("..getServiceCost("supplydrop").."rep)", function() if player:getWaypointCount() < 1 then setCommsMessage("You need to set a waypoint before you can request backup."); else setCommsMessage("To which waypoint should we deliver your supplies?"); for n=1,player:getWaypointCount() do addCommsReply("WP" .. n, function() if player:takeReputationPoints(getServiceCost("supplydrop")) then local position_x, position_y = comms_target:getPosition() local target_x, target_y = player:getWaypoint(n) local script = Script() script:setVariable("position_x", position_x):setVariable("position_y", position_y) script:setVariable("target_x", target_x):setVariable("target_y", target_y) script:setVariable("faction_id", comms_target:getFactionId()):run("supply_drop.lua") setCommsMessage("We have dispatched a supply ship toward WP" .. n); else setCommsMessage("Not enough reputation!"); end addCommsReply("Back", commsStation) end) end end addCommsReply("Back", commsStation) end) end if isAllowedTo(comms_target.comms_data.services.reinforcements) then addCommsReply("Please send reinforcements! ("..getServiceCost("reinforcements").."rep)", function() if player:getWaypointCount() < 1 then setCommsMessage("You need to set a waypoint before you can request reinforcements."); else setCommsMessage("To which waypoint should we dispatch the reinforcements?"); for n=1,player:getWaypointCount() do addCommsReply("WP" .. n, function() if player:takeReputationPoints(getServiceCost("reinforcements")) then ship = CpuShip():setFactionId(comms_target:getFactionId()):setPosition(comms_target:getPosition()):setTemplate("Adder MK5"):setScanned(true):orderDefendLocation(player:getWaypoint(n)) setCommsMessage("We have dispatched " .. ship:getCallSign() .. " to assist at WP" .. n); else setCommsMessage("Not enough reputation!"); end addCommsReply("Back", commsStation) end) end end addCommsReply("Back", commsStation) end) end -- Add helpful waypoint creation messages if isAllowedTo(askForBalindorLocation) then addCommsReply("Where is Balindor Prime?", function() player:commandAddWaypoint(-50500,84000) setCommsMessage("Added a waypoint to your navigation system for Balindor Prime") askForBalindorLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForNingLocation) then addCommsReply("Where is Ningling?", function() player:commandAddWaypoint(12200,-62600) setCommsMessage("Added a waypoint for Ningling station") askForNingLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForGoltinLocation) then addCommsReply("Where is Goltin 7?", function() player:commandAddWaypoint(93150,21387) setCommsMessage("Added a waypoint for Goltin 7") askForGoltinLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForPangoraLocation) then addCommsReply("Where is Pangora?", function() player:commandAddWaypoint(stationPangora:getPosition()) setCommsMessage("Added a waypoint for Pangora station") askForPangoraLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForNakorLocation) then addCommsReply("Where is Nakor?", function() player:commandAddWaypoint(stationNakor:getPosition()) setCommsMessage("Added a waypoint for Nakor station") askForNakorLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForScience37Location) then addCommsReply("Where is Science-37?", function() player:commandAddWaypoint(science37:getPosition()) setCommsMessage("Added a waypoint for station Science-37") askForScience37Location = "complete" addCommsReply("Back", commsStation) end) end -- Add artifact location clues if isAllowedTo(askForPangoraArtifactLocation) then addCommsReply("Any reports of artifacts near Pangora?", function() setCommsMessage("Some freighters report seeing an artifact on approximate heading 135 from Pangora") askForPangoraArtifactLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForNakorArtifactLocation) then addCommsReply("Heard of any artifacts near Nakor?", function() setCommsMessage("Some have reported seeing object on approximate heading of 315 from Nakor station") askForNakorArtifactLocation = "complete" addCommsReply("Back", commsStation) end) end if isAllowedTo(askForScience37ArtifactLocation) then addCommsReply("Has anyone reported seeing artifacts near Science-37?", function() setCommsMessage("Freighters doing business here occasionally report an objecton approximate heading zero from Science-37 station") askForScience37ArtifactLocation = "complete" addCommsReply("Back", commsStation) end) end end function isAllowedTo(state) if state == "friend" and player:isFriendly(comms_target) then return true end if state == "neutral" and not player:isEnemy(comms_target) then return true end if state == "ready" then return true end if state == "orders" and comms_target:getFaction() == "Human Navy" then return true end return false end -- Return the number of reputation points that a specified weapon costs for the current player function getWeaponCost(weapon) return math.ceil(comms_data.weapon_cost[weapon] * comms_data.reputation_cost_multipliers[getFriendStatus()]) end -- Return the number of reputation points that a specified service costs for the current player function getServiceCost(service) return math.ceil(comms_data.service_cost[service]) end function getFriendStatus() if player:isFriendly(comms_target) then return "friend" else return "neutral" end end function update(delta) if not player:isValid() then victory("Kraylor") return end if plot1 == nil then victory("Human Navy") return end if plot2 == defeat then victory("Kraylor") end if plot1 ~= nil then plot1(delta) end if plot2 ~= nil then plot2(delta) end if plot3 ~= nil then plot3(delta) end if plot4 ~= nil then plot4(delta) end if transportPlot ~= nil then transportPlot(delta) end end -- Create amount of objects of type object_type along arc -- Center defined by x and y -- Radius defined by distance -- Start of arc between 0 and 360 (startArc), end arc: endArcClockwise -- Use randomize to vary the distance from the center point. Omit to keep distance constant -- Example: -- createRandomAlongArc(Asteroid, 100, 500, 3000, 65, 120, 450) function createRandomAlongArc(object_type, amount, x, y, distance, startArc, endArcClockwise, randomize) if randomize == nil then randomize = 0 end local sa = startArc local ea = endArcClockwise if sa > ea then ea = ea + 360 end for n=1,amount do local r = random(sa,ea) local dist = distance + random(-randomize,randomize) local xo = x + math.cos(r / 180 * math.pi) * dist local yo = y + math.sin(r / 180 * math.pi) * dist object_type():setPosition(xo, yo) end end
gpl-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/chats/last-hope-melinda-father.lua
1
9433
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local q = game.player:hasQuest("kryl-feijan-escape") local qs = game.player:hasQuest("shertul-fortress") local ql = game.player:hasQuest("love-melinda") if ql and ql:isStatus(q.COMPLETED, "death-beach") then newChat{ id="welcome", text = [[#LIGHT_GREEN#*A man talks to you from inside, the door half open. His voice is sad.*#WHITE# Sorry, the store is closed.]], answers = { {"[leave]"}, } } elseif not q or not q:isStatus(q.DONE) then newChat{ id="welcome", text = [[#LIGHT_GREEN#*A man talks to you from inside, the door half open. His voice is sad.*#WHITE# Sorry, the store is closed.]], answers = { {"[leave]"}, } } else ------------------------------------------------------------------ -- Saved ------------------------------------------------------------------ newChat{ id="welcome", text = [[@playername@! My daughter's savior!]], answers = { {"Hi, I was just checking in to see if Melinda is all right.", jump="reward", cond=function(npc, player) return not npc.rewarded_for_saving_melinda end, action=function(npc, player) npc.rewarded_for_saving_melinda = true end}, {"Hi, I would like to talk to Melinda please.", jump="rewelcome", switch_npc={name="Melinda"}, cond=function(npc, player) return ql and not ql:isCompleted("moved-in") and not ql.inlove end}, {"Hi, I would like to talk to Melinda please.", jump="rewelcome-love", switch_npc={name="Melinda"}, cond=function(npc, player) return ql and not ql:isCompleted("moved-in") and ql.inlove end}, {"Sorry, I have to go!"}, } } newChat{ id="reward", text = [[Please take this. It is nothing compared to the life of my child. Oh, and she wanted to thank you in person; I will call her.]], answers = { {"Thank you.", jump="melinda", switch_npc={name="Melinda"}, action=function(npc, player) local ro = game.zone:makeEntity(game.level, "object", {unique=true, not_properties={"lore"}}, nil, true) if ro then ro:identify(true) game.logPlayer(player, "Melinda's father gives you: %s", ro:getName{do_color=true}) game.zone:addEntity(game.level, ro, "object") player:addObject(player:getInven("INVEN"), ro) game._chronoworlds = nil end player:grantQuest("love-melinda") ql = player:hasQuest("love-melinda") end}, } } newChat{ id="melinda", text = [[@playername@! #LIGHT_GREEN#*She jumps for joy and hugs you while her father returns to his shop.*#WHITE#]], answers = { {"I am glad to see you are fine. It seems your scars are healing quite well.", jump="scars", cond=function(npc, player) if player:attr("undead") then return false end return true end,}, {"I am glad to see you well. Take care."}, } } ------------------------------------------------------------------ -- Flirting ------------------------------------------------------------------ newChat{ id="scars", text = [[Yes it has mostly healed, though I still do have nightmares. I feel like something is still lurking. Ah well, the bad dreams are still better than the fate you saved me from!]], answers = { {"Should I come across a way to help you during my travels, I will try to help.", quick_reply="Thank you, you are most welcome."}, {"Most certainly, so what are your plans now?", jump="plans"}, } } newChat{ id="rewelcome", text = [[Hi @playername@! I am feeling better now, even starting to grow restless...]], answers = { {"So what are your plans now?", jump="plans"}, {"About that, I was thinking that maybe you'd like to go out with me sometime ...", jump="hiton", cond=function() return not ql.inlove and not ql.nolove end}, } } newChat{ id="rewelcome-love", text = [[#LIGHT_GREEN#*Melinda appears at the door and kisses you*#WHITE# Hi my dear, I'm so happy to see you!]], answers = { {"I am still looking out for an explanation of what happened at the beach."}, {"About what happened on the beach, I think I have found something.", jump="home1", cond=function() return ql:isStatus(engine.Quest.COMPLETED, "can_come_fortress") end}, } } local p = game:getPlayer(true) local is_am = p:attr("forbid_arcane") local is_mage = (p.faction == "angolwen") or p:isQuestStatus("mage-apprentice", engine.Quest.DONE) newChat{ id="plans", text = [[I do not know yet, my father won't let me out until I'm fully healed. I've always wanted to do so many things. That is why I got stuck in that crypt, I want to see the world. My father gave me some funds so that I can take my future into my own hands. I have some friends in Derth, maybe I will open my own little shop there. ]]..( is_am and [[I have seen how you fought those corruptors, the way you destroyed their magic. I want to learn to do the same, so that such horrors never happen again. To anyone.]] or (is_mage and [[Or maybe, well I suppose I can trust you with this, I've always secretly dreamed of learning magic. Real magic I mean not alchemist tricks! I've learnt about a secret place, Angolwen, where I could learn it.]] or [[]])), answers = (not is_am and not is_mage) and { {"Derth has its up and downs but I think they could do with a smart girl yes.", action=function() ql.wants_to = "derth" end, quick_reply="Thanks!"}, } or { {"Derth has its up and downs but I think they could do with a smart girl yes.", action=function() ql.wants_to = "derth" end, quick_reply="Thanks!"}, {"You wish to join our noble crusade against magic? Wonderful! I will talk to them for you.", action=function() ql.wants_to = "antimagic" end, cond=function() return is_am end, quick_reply="That would be very nice!"}, {"I happen to be welcome among the people of Angolwen, I could say a word for you.", action=function() ql.wants_to = "magic" end, cond=function() return is_mage end, quick_reply="That would be very nice!"}, } } newChat{ id="hiton", text = [[What?!? Just because you rescued me from a moderately-to-extremely gruesome death, you think that entitles you to take liberties?!]], answers = { {"WHY AREN'T WOMEN ATTRACTED TO ME I'M A NICE "..(p.female and "GIRL" or "GUY")..".", quick_reply="Uhh, sorry I hear my father calling, see you.", action=function() ql.nolove = true end}, {"Just a minute, I was just ...", jump="reassurance"}, } } newChat{ id="reassurance", text = [[#LIGHT_GREEN#*She looks at you cheerfully.*#WHITE# Just kidding. I would love that!]], answers = { {"#LIGHT_GREEN#[walk away with her]#WHITE#What about a little trip to the south, from the coastline we can see the Charred Scar Volcano, it is a wonderous sight.", action=function() ql.inlove = true ql:toBeach() end}, {"Joke's on you really, goodbye!", quick_reply="But... ok goodbye.", action=function() ql.nolove = true end}, } } newChat{ id="hug", text = [[#LIGHT_GREEN#*You take Melinda in your arms and press her against you. The warmth of the contact lightens your heart.*#WHITE# I feel safe in your arms. Please, I know you must leave, but promise to come back soon and hold me again.]], answers = { {"I think I would enjoy that very much. #LIGHT_GREEN#[kiss her]#WHITE#", action=function(npc, player) end}, {"That thought will carry me in the dark places I shall walk. #LIGHT_GREEN#[kiss her]#WHITE#", action=function(npc, player) player:grantQuest("love-melinda") end}, {"Oh, I am sorry. I think you are mistaken. I was only trying to comfort you.", quick_reply="Oh, sorry, I was not myself. Goodbye, then. Farewell."}, } } ------------------------------------------------------------------ -- Moving in ------------------------------------------------------------------ newChat{ id="home1", text = [[#LIGHT_GREEN#*Melinda looks worried*#WHITE# Please tell me you can help!]], answers = { {"Yes, I think so. Some time ago I assumed ownership of a very special home... #LIGHT_GREEN#[tell her the Fortress story]#WHITE#", jump="home2"}, } } newChat{ id="home2", text = [[An ancient fortress of a mythical race?! How #{bold}#exciting#{normal}#! And you say it could cure me?]], answers = { {"The Fortress seems to think so. I know this might sound a bit .. inappropriate .. but you would need to come live there, at least for a while.", jump="home3"}, } } newChat{ id="home3", text = [[#LIGHT_GREEN#*She looks at you cheerfully*#WHITE# Ah the plan to sleep with me is finally revealed! Shhh you dummy, I thought we were past such silliness, I will come, both for my health and because I want to be with you. #LIGHT_GREEN#*She kisses you tenderly*#WHITE#]], answers = { {"Then my lady, if you will follow me. #LIGHT_GREEN#[take her to the Fortress]", action=function(npc, player) game:changeLevel(1, "shertul-fortress", {direct_switch=true}) player:hasQuest("love-melinda"):spawnFortress(player) end}, } } end return "welcome"
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/zones/lake-nur/npcs.lua
1
1361
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/npcs/aquatic_critter.lua", function(e) if e.rarity then e.water_rarity, e.rarity = e.rarity, nil end end) load("/data/general/npcs/aquatic_demon.lua", function(e) if e.rarity then e.water_rarity, e.rarity = e.rarity, nil end end) load("/data/general/npcs/horror_aquatic.lua", function(e) if e.rarity then e.horror_water_rarity, e.rarity = e.rarity, nil end end) load("/data/general/npcs/horror.lua", rarity(0)) load("/data/general/npcs/snake.lua", rarity(3)) load("/data/general/npcs/plant.lua", rarity(3)) local Talents = require("engine.interface.ActorTalents")
gpl-3.0
AmyBSOD/ToME-SX
lib/scpt/s_divin.lua
1
5389
-- Handles thhe divination school STARIDENTIFY = add_spell { ["name"] = "Greater Identify", ["school"] = {SCHOOL_DIVINATION}, ["level"] = 35, ["mana"] = 30, ["mana_max"] = 30, ["fail"] = 80, ["spell"] = function() if get_check("Cast on yourself?") == TRUE then self_knowledge() else identify_fully() end return TRUE end, ["info"] = function() return "" end, ["desc"] = { "Asks for an object and fully identify it, providing the full list of powers", "Cast at yourself it will reveal your powers" } } IDENTIFY = add_spell { ["name"] = "Identify", ["school"] = {SCHOOL_DIVINATION}, ["level"] = 8, ["mana"] = 10, ["mana_max"] = 50, ["fail"] = 40, ["stick"] = { ["charge"] = { 7, 10 }, [TV_STAFF] = { ["rarity"] = 45, ["base_level"] = { 1, 15 }, ["max_level"] = { 15, 40 }, }, }, ["spell"] = function() if get_level(IDENTIFY, 50) >= 27 then local obvious obvious = identify_pack() obvious = is_obvious(fire_ball(GF_IDENTIFY, 0, 1, get_level(IDENTIFY, 3)), obvious) if obvious == TRUE then player.notice = bor(player.notice, PN_COMBINE, PN_REORDER) end return obvious elseif get_level(IDENTIFY, 50) >= 17 then local obvious obvious = identify_pack() obvious = is_obvious(fire_ball(GF_IDENTIFY, 0, 1, 0), obvious) if obvious == TRUE then player.notice = bor(player.notice, PN_COMBINE, PN_REORDER) end return obvious else if ident_spell() == TRUE then return TRUE else return end end end, ["info"] = function() if get_level(IDENTIFY, 50) >= 27 then return "rad "..(get_level(IDENTIFY, 3)) else return "" end end, ["desc"] = { "Asks for an object and identifies it", "At level 17 it identifies all objects in the inventory", "At level 27 it identifies all objects in the inventory and in a", "radius on the floor, as well as probing monsters in that radius" } } VISION = add_spell { ["name"] = "Vision", ["school"] = {SCHOOL_DIVINATION}, ["level"] = 15, ["mana"] = 7, ["mana_max"] = 55, ["fail"] = 45, ["stick"] = { ["charge"] = { 4, 6 }, [TV_STAFF] = { ["rarity"] = 60, ["base_level"] = { 1, 5 }, ["max_level"] = { 10, 30 }, }, }, ["inertia"] = { 2, 200 }, ["spell"] = function() if get_level(VISION, 50) >= 25 then wiz_lite_extra() else map_area() end return TRUE end, ["info"] = function() return "" end, ["desc"] = { "Detects the layout of the surrounding area", "At level 25 it maps and lights the whole level", } } SENSEHIDDEN = add_spell { ["name"] = "Sense Hidden", ["school"] = {SCHOOL_DIVINATION}, ["level"] = 5, ["mana"] = 2, ["mana_max"] = 10, ["fail"] = 25, ["stick"] = { ["charge"] = { 1, 15 }, [TV_STAFF] = { ["rarity"] = 20, ["base_level"] = { 1, 15 }, ["max_level"] = { 10, 50 }, }, }, ["inertia"] = { 1, 10 }, ["spell"] = function() local obvious = nil obvious = detect_traps(15 + get_level(SENSEHIDDEN, 40, 0)) if get_level(SENSEHIDDEN, 50) >= 15 then obvious = is_obvious(set_tim_invis(10 + randint(20) + get_level(SENSEHIDDEN, 40)), obvious) end return obvious end, ["info"] = function() if get_level(SENSEHIDDEN, 50) >= 15 then return "rad "..(15 + get_level(SENSEHIDDEN, 40)).." dur "..(10 + get_level(SENSEHIDDEN, 40)).."+d20" else return "rad "..(15 + get_level(SENSEHIDDEN, 40)) end end, ["desc"] = { "Detects the traps in a certain radius around you", "At level 15 it allows you to sense invisible for a while" } } REVEALWAYS = add_spell { ["name"] = "Reveal Ways", ["school"] = {SCHOOL_DIVINATION}, ["level"] = 9, ["mana"] = 3, ["mana_max"] = 15, ["fail"] = 20, ["stick"] = { ["charge"] = { 6, 6 }, [TV_STAFF] = { ["rarity"] = 35, ["base_level"] = { 1, 15 }, ["max_level"] = { 25, 50 }, }, }, ["inertia"] = { 1, 10 }, ["spell"] = function() local obvious obvious = detect_doors(10 + get_level(REVEALWAYS, 40, 0)) obvious = is_obvious(detect_stairs(10 + get_level(REVEALWAYS, 40, 0)), obvious) return obvious end, ["info"] = function() return "rad "..(10 + get_level(REVEALWAYS, 40)) end, ["desc"] = { "Detects the doors/stairs/ways in a certain radius around you", } } SENSEMONSTERS = add_spell { ["name"] = "Sense Monsters", ["school"] = {SCHOOL_DIVINATION}, ["level"] = 1, ["mana"] = 1, ["mana_max"] = 20, ["fail"] = 10, ["stick"] = { ["charge"] = { 5, 10 }, [TV_STAFF] = { ["rarity"] = 37, ["base_level"] = { 1, 10 }, ["max_level"] = { 15, 40 }, }, }, ["inertia"] = { 1, 10 }, ["spell"] = function() local obvious obvious = detect_monsters_normal(10 + get_level(SENSEMONSTERS, 40, 0)) if get_level(SENSEMONSTERS, 50) >= 30 then obvious = is_obvious(set_tim_esp(10 + randint(10) + get_level(SENSEMONSTERS, 20)), obvious) end return obvious end, ["info"] = function() if get_level(SENSEMONSTERS, 50) >= 30 then return "rad "..(10 + get_level(SENSEMONSTERS, 40)).." dur "..(10 + get_level(SENSEMONSTERS, 20)).."+d10" else return "rad "..(10 + get_level(SENSEMONSTERS, 40)) end end, ["desc"] = { "Detects all monsters near you", "At level 30 it allows you to sense monster minds for a while" } }
gpl-2.0
mahdibagheri/aqa-mp3
plugins/meme.lua
637
5791
local helpers = require "OAuth.helpers" local _file_memes = './data/memes.lua' local _cache = {} local function post_petition(url, arguments) local response_body = {} local request_constructor = { url = url, method = "POST", sink = ltn12.sink.table(response_body), headers = {}, redirect = false } local source = arguments if type(arguments) == "table" then local source = helpers.url_encode_arguments(arguments) end request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded" request_constructor.headers["Content-Length"] = tostring(#source) request_constructor.source = ltn12.source.string(source) local ok, response_code, response_headers, response_status_line = http.request(request_constructor) if not ok then return nil end response_body = json:decode(table.concat(response_body)) return response_body end local function upload_memes(memes) local base = "http://hastebin.com/" local pet = post_petition(base .. "documents", memes) if pet == nil then return '', '' end local key = pet.key return base .. key, base .. 'raw/' .. key end local function analyze_meme_list() local function get_m(res, n) local r = "<option.*>(.*)</option>.*" local start = string.find(res, "<option.*>", n) if start == nil then return nil, nil end local final = string.find(res, "</option>", n) + #"</option>" local sub = string.sub(res, start, final) local f = string.match(sub, r) return f, final end local res, code = http.request('http://apimeme.com/') local r = "<option.*>(.*)</option>.*" local n = 0 local f, n = get_m(res, n) local ult = {} while f ~= nil do print(f) table.insert(ult, f) f, n = get_m(res, n) end return ult end local function get_memes() local memes = analyze_meme_list() return { last_time = os.time(), memes = memes } end local function load_data() local data = load_from_file(_file_memes) if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then data = get_memes() -- Upload only if changed? link, rawlink = upload_memes(table.concat(data.memes, '\n')) data.link = link data.rawlink = rawlink serialize_to_file(data, _file_memes) end return data end local function match_n_word(list1, list2) local n = 0 for k,v in pairs(list1) do for k2, v2 in pairs(list2) do if v2:find(v) then n = n + 1 end end end return n end local function match_meme(name) local _memes = load_data() local name = name:lower():split(' ') local max = 0 local id = nil for k,v in pairs(_memes.memes) do local n = match_n_word(name, v:lower():split(' ')) if n > 0 and n > max then max = n id = v end end return id end local function generate_meme(id, textup, textdown) local base = "http://apimeme.com/meme" local arguments = { meme=id, top=textup, bottom=textdown } return base .. "?" .. helpers.url_encode_arguments(arguments) end local function get_all_memes_names() local _memes = load_data() local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n' for k, v in pairs(_memes.memes) do text = text .. '- ' .. v .. '\n' end text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/' return text end local function callback_send(cb_extra, success, data) if success == 0 then send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'list' then local _memes = load_data() return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link elseif matches[1] == 'listall' then if not is_sudo(msg) then return "You can't list this way, use \"!meme list\"" else return get_all_memes_names() end elseif matches[1] == "search" then local meme_id = match_meme(matches[2]) if meme_id == nil then return "I can't match that search with any meme." end return "With that search your meme is " .. meme_id end local searchterm = string.gsub(matches[1]:lower(), ' ', '') local meme_id = _cache[searchterm] or match_meme(matches[1]) if not meme_id then return 'I don\'t understand the meme name "' .. matches[1] .. '"' end _cache[searchterm] = meme_id print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3]) local url_gen = generate_meme(meme_id, matches[2], matches[3]) send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen}) return nil end return { description = "Generate a meme image with up and bottom texts.", usage = { "!meme search (name): Return the name of the meme that match.", "!meme list: Return the link where you can see the memes.", "!meme listall: Return the list of all memes. Only admin can call it.", '!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.', '!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.', }, patterns = { "^!meme (search) (.+)$", '^!meme (list)$', '^!meme (listall)$', '^!meme (.+) "(.*)" "(.*)"$', '^!meme "(.+)" "(.*)" "(.*)"$', "^!meme (.+) %- (.*) %- (.*)$" }, run = run }
gpl-2.0
saraedum/luci-packages-old
protocols/6x4/luasrc/model/network/proto_6x4.lua
78
1602
--[[ LuCI - Network model - 6to4, 6in4 & 6rd protocol extensions Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"6in4", "6to4", "6rd"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "6in4" then return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)") elseif p == "6to4" then return luci.i18n.translate("IPv6-over-IPv4 (6to4)") elseif p == "6rd" then return luci.i18n.translate("IPv6-over-IPv4 (6rd)") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) return p end function proto.is_installed(self) return nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interfaces(self) return nil end function proto.contains_interface(self, ifname) return (netmod:ifnameof(ifc) == self:ifname()) end netmod:register_pattern_virtual("^%s-%%w" % p) end
apache-2.0
froggatt/openwrt-luci
protocols/ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua
59
3798
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local username, password, ac, service local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true ac = section:taboption("general", Value, "ac", translate("Access Concentrator"), translate("Leave empty to autodetect")) ac.placeholder = translate("auto") service = section:taboption("general", Value, "service", translate("Service Name"), translate("Leave empty to autodetect")) service.placeholder = translate("auto") if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", Flag, "ipv6", translate("Enable IPv6 negotiation on the PPP link")) ipv6.default = ipv6.disabled end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/chats/shertul-fortress-butler.lua
1
11366
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local has_rod = function(npc, player) return player:findInAllInventoriesBy("define_as", "ROD_OF_RECALL") end local q = game.player:hasQuest("shertul-fortress") local ql = game.player:hasQuest("love-melinda") local set = function(what) return function(npc, player) q:setStatus(q.COMPLETED, "chat-"..what) end end local isNotSet = function(what) return function(npc, player) return not q:isCompleted("chat-"..what) end end newChat{ id="welcome", text = [[*#LIGHT_GREEN#The creature slowly turns to you. You hear its terrible voice directly in your head.#WHITE#* Welcome, master.]], answers = { {"What are you, and what is this place?", jump="what", cond=isNotSet"what", action=set"what"}, {"Master? I am not your mas...", jump="master", cond=isNotSet"master", action=set"master"}, {"Why do I understand you? The texts are unreadable to me.", jump="understand", cond=isNotSet"understand", action=set"understand"}, {"What can I do here?", jump="storage", cond=isNotSet"storage", action=set"storage"}, {"What else can this place do?", jump="energy", cond=isNotSet"energy", action=set"energy"}, {"Would it be possible to improve my Cloak of Deception so I do not need to wear it to pass as a living being?", jump="permanent-cloak", cond=function(npc, player) local cloak = player:findInAllInventoriesBy("define_as", "CLOAK_DECEPTION") return not q:isCompleted("permanent-cloak") and q:isCompleted("transmo-chest") and cloak end}, {"You asked me to come, about a farportal?", jump="farportal", cond=function() return q:isCompleted("farportal") and not q:isCompleted("farportal-spawn") end}, {"You asked me to come, about the rod of recall?", jump="recall", cond=function() return q:isCompleted("recall") and not q:isCompleted("recall-done") end}, {"Would it be possible for my Transmogrification Chest to automatically extract gems?", jump="transmo-gems", cond=function(npc, player) return not q:isCompleted("transmo-chest-extract-gems") and q:isCompleted("transmo-chest") and player:knowTalent(player.T_EXTRACT_GEMS) end}, {"Are there any training facilities?", jump="training", cond=function() return not q:isCompleted("training") end}, {"I find your appearance unsettling. Any way you can change it?", jump="changetile", cond=function() return q:isCompleted("recall-done") end}, {"I have come upon a strange thing indeed. #LIGHT_GREEN#[tell him about Melinda]", jump="cure-melinda", cond=function() return ql and ql:isStatus(engine.Quest.COMPLETED, "saved-beach") and not ql:isStatus(engine.Quest.FAILED) and not ql:isStatus(engine.Quest.COMPLETED, "can_come_fortress") end}, {"[leave]"}, } } newChat{ id="master", text = [[*#LIGHT_GREEN#The creature glares at you.#WHITE#* You possess a control rod. You are the master.]], answers = { {"Err... ok.", jump="welcome"}, } } newChat{ id="understand", text = [[*#LIGHT_GREEN#The creature glares at you.#WHITE#* You are the master; you have the rod. I am created to speak to the master.]], answers = { {"Err... ok.", jump="welcome"}, } } newChat{ id="what", text = [[*#LIGHT_GREEN#The creature glares at you with intensity. You 'see' images in your head. You see titanic wars in an age now forgotten. You see armies of what you suppose are Sher'Tuls since they look like the shadow. They fight with weapons, magic and other things. They fight gods. They hunt them down, killing or banishing them. You see great fortresses like this one, flying all over the skies of Eyal - shining bastions of power glittering in the young sun. You see the gods beaten, defeated and dead. All but one. Then you see darkness; it seems like the shadow does not know what followed those events. You shake your head as the vision dissipates, and your normal sight comes back slowly. #WHITE#* ]], answers = { {"Those are Sher'Tuls? They fought the gods?!", jump="godslayers"}, } } newChat{ id="godslayers", text = [[They had to. They forged terrible weapons of war. They won.]], answers = { {"But then where are they now if they won?", jump="where"}, } } newChat{ id="where", text = [[They are gone now. I cannot tell you more.]], answers = { {"But I am the master!", jump="where"}, {"Fine.", jump="welcome"}, } } newChat{ id="storage", text = [[*#LIGHT_GREEN#The creature glares at you.#WHITE#* You are the master. You can use this place as you desire. However, most of the energies are depleted and only some rooms are usable. To the south you will find the storage room.]], answers = { {"Thanks.", jump="welcome"}, } } newChat{ id="energy", text = [[This Fortress is designed as a mobile base for the Godslayers - it can fly. It is also equiped with various facilities: exploratory farportal, emergency containment field, remote storage, ... However, the Fortress is badly damaged and has lain dormant for too long. Its energies are nearly depleted. Take this Transmogrification Chest. It is linked by a permanent farportal to the Fortress. Any item you put inside will be sent to the power core and dismantled for energy. There are, however, unwanted byproducts to this operation: the generation of a metal known as gold. It is of no use to the Fortress and thus will be sent back to you.]], answers = { {"I will, thanks.", jump="welcome", action=function() q:spawn_transmo_chest() end, cond=function(npc, player) return not player:attr("has_transmo") end}, {"I have already found such a chest in my travel. Will it work?", jump="alreadychest", action=function() q:setStatus(q.COMPLETED, "transmo-chest") end, cond=function(npc, player) return player:attr("has_transmo") end}, } } newChat{ id="alreadychest", text = [[Yes, it will. I will attune it to this fortress. Done.]], answers = { {"Thanks.", jump="welcome"}, } } newChat{ id="farportal", text = [[Long ago the Sher'tuls used farportals not only for transportation to known locations, but also to explore new parts of the world, or even other worlds. This Fortress is equipped with an exploratory farportal, and now has enough energy to allow one teleportation. Each teleportation will take you to a random part of the universe and use 45 energy. Beware that the return portal may not be nearby your arrival point; you will need to find it. You can use the rod of recall to try to force an emergency recall, but it has high chances of breaking the exploratory farportal forever. You may use the farportal; however, beware - I sense a strange presence in the farportal room.]], answers = { {"I will check it out, thanks.", action=function() q:spawn_farportal_guardian() end}, } } newChat{ id="recall", text = [[The rod of recall you possess is not a Sher'tul artifact, but it is based on Sher'tul design. The Fortress now has enough energy to upgrade it. It can be changed to recall you to the Fortress.]], answers = { {"I like it the way it is now. Thanks anyway."}, {"That could be quite useful. Yes, please do it.", action=function() q:upgrade_rod() end}, } } newChat{ id="training", text = [[Yes master, a training facility is available to the north, but it is not yet powered on. I will need to use 50 energy to do this.]], answers = { {"Maybe later."}, {"That could be quite useful. Yes, please do it.", cond=function() return q.shertul_energy >= 50 end, action=function() q:open_training() end}, } } newChat{ id="transmo-gems", text = [[Ah yes, you seem to master the simple art of alchemy. I can change the chest to automatically use your power to extract a gem if the transmogrification of the gem would reward more energy. However, I will need to use 25 energy to do this.]], answers = { {"Maybe sometime later."}, {"That could be quite useful. Yes, please do it.", cond=function() return q.shertul_energy >= 25 end, action=function() q:upgrade_transmo_gems() end}, } } newChat{ id="changetile", text = [[I can alter the Fortress holographic projection matrix to accomodate your racial tastes. This will require 60 energy, however.]], answers = { {"Can you try for a human female appearance please?", cond=function() return q.shertul_energy >= 60 end, action=function(npc, player) q.shertul_energy = q.shertul_energy - 60 npc.replace_display = mod.class.Actor.new{ add_mos={{image = "npc/humanoid_female_sluttymaid.png", display_y=-1, display_h=2}}, -- shader = "shadow_simulacrum", -- shader_args = { color = {0.2, 0.1, 0.8}, base = 0.5, time_factor = 500 }, } npc:removeAllMOs() game.level.map:updateMap(npc.x, npc.y) game.level.map:particleEmitter(npc.x, npc.y, 1, "demon_teleport") end}, {"Can you try for a human male appearance please?", cond=function() return q.shertul_energy >= 60 end, action=function(npc, player) q.shertul_energy = q.shertul_energy - 60 npc.replace_display = mod.class.Actor.new{ image = "invis.png", add_mos={{image = "npc/humanoid_male_sluttymaid.png", display_y=-1, display_h=2}}, -- shader = "shadow_simulacrum", -- shader_args = { color = {0.2, 0.1, 0.8}, base = 0.5, time_factor = 500 }, } npc:removeAllMOs() game.level.map:updateMap(npc.x, npc.y) game.level.map:particleEmitter(npc.x, npc.y, 1, "demon_teleport") end}, {"Please revert to your default appearance.", cond=function() return q.shertul_energy >= 60 end, action=function(npc, player) q.shertul_energy = q.shertul_energy - 60 npc.replace_display = nil npc:removeAllMOs() game.level.map:updateMap(npc.x, npc.y) game.level.map:particleEmitter(npc.x, npc.y, 1, "demon_teleport") end}, {"Well, you do not look so bad actually. Let it be for now."}, } } newChat{ id="permanent-cloak", text = [[Yes Master. I can use 10 energy to infuse your cloak. When you take it off the effect should still persist. However, I suggest you still carry it with you in case something manages to remove it from you.]], answers = { {"Not now."}, {"That could be quite useful. Yes, please do it.", action=function(npc, player) local cloak = player:findInAllInventoriesBy("define_as", "CLOAK_DECEPTION") cloak.upgraded_cloak = true q.shertul_energy = q.shertul_energy - 10 q:setStatus(engine.Quest.COMPLETED, "permanent-cloak") end}, } } newChat{ id="cure-melinda", text = [[Demonic taint. Yes I have a way to help in the archives. However this is a long process, the subject will need to live here for a while. She will have to spend 8 hours per day in the regeneration tank.]], answers = { {"This is great news! I will tell her at once.", action=function(npc, player) player:setQuestStatus("love-melinda", engine.Quest.COMPLETED, "can_come_fortress") end}, } } return "welcome"
gpl-3.0
xAleXXX007x/Witcher-RolePlay
nutscript/gamemode/core/derma/cl_dev_icon.lua
4
9508
ICON_INFO = ICON_INFO or {} ICON_INFO.camPos = ICON_INFO.camPos or Vector() ICON_INFO.camAng = ICON_INFO.camAng or Angle() ICON_INFO.FOV = ICON_INFO.FOV or 50 ICON_INFO.w = ICON_INFO.w or 1 ICON_INFO.h = ICON_INFO.h or 1 ICON_INFO.modelAng = ICON_INFO.modelAng or Angle() ICON_INFO.modelName = ICON_INFO.modelName or "models/Items/grenadeAmmo.mdl" local vTxt = "xyz" local aTxt = "pyr" local bTxt = { "best", "full", "above", "right", "origin", } local PANEL = {} local iconSize = 64 /* 3D ICON PREVIEW WINDOW */ function PANEL:Init() self:SetPos(50, 50) self:ShowCloseButton(false) self:SetTitle("PREVIEW") self.model = self:Add("DModelPanel") self.model:SetPos(5, 22) function self.model:PaintOver(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end function self.model:LayoutEntity() end self:AdjustSize(ICON_INFO.w, ICON_INFO.h) end function PANEL:Paint(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end function PANEL:AdjustSize(x, y) self:SetSize(10 + (x or 1)*64, 27 + (y or 1)*64) self.model:SetSize((x or 1)*64, (y or 1)*64) end vgui.Register("iconPreview", PANEL, "DFrame") /* RENDER ICON PREVIEW */ PANEL = {} AccessorFunc( PANEL, "m_strModel", "Model" ) AccessorFunc( PANEL, "m_pOrigin", "Origin" ) AccessorFunc( PANEL, "m_bCustomIcon", "CustomIcon" ) function PANEL:Init() self:SetPos(50, 300) self:ShowCloseButton(false) self:SetTitle("PREVIEW") self.model = self:Add("SpawnIcon") self.model:InvalidateLayout(true) self.model:SetPos(5, 22) function self.model:PaintOver(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end self:AdjustSize(ICON_INFO.w, ICON_INFO.h) end function PANEL:Paint(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end function PANEL:AdjustSize(x, y) self:SetSize(10 + (x or 1)*64, 27 + (y or 1)*64) self.model:SetSize((x or 1)*64, (y or 1)*64) end vgui.Register("iconRenderPreview", PANEL, "DFrame") /* EDITOR FUNCTION */ local function action() end local function renderAction(self) local p1 = self.prev local p = self.prev2 local icon = p.model local iconModel = p1.model if (icon and iconModel) then local ent = iconModel:GetEntity() local tab = {} tab.ent = ent tab.cam_pos = iconModel:GetCamPos() tab.cam_ang = iconModel:GetLookAng() tab.cam_fov = iconModel:GetFOV() icon:SetModel(ent:GetModel()) icon:RebuildSpawnIconEx( tab ) print("ITEM.model = \""..ICON_INFO.modelName:gsub("\\", "/"):lower().."\"") print("ITEM.width = "..ICON_INFO.w) print("ITEM.height = "..ICON_INFO.h) print("ITEM.iconCam = {") print("\tpos = Vector("..tab.cam_pos.x..", "..tab.cam_pos.y..", "..tab.cam_pos.z.."),") print("\tang = Angle("..tab.cam_ang.p..", "..tab.cam_ang.y..", "..tab.cam_ang.r.."),") print("\tfov = "..tab.cam_fov) print("}") end end PANEL = {} function PANEL:Init() if (editorPanel and editorPanel:IsVisible()) then editorPanel:Close() end editorPanel = self self:SetTitle("MODEL ADJUST") self:MakePopup() self:SetSize(400, ScrH()*.8) self:Center() self.prev = vgui.Create("iconPreview") self.prev2 = vgui.Create("iconRenderPreview") self.list = self:Add("DScrollPanel") self.list:Dock(FILL) self:AddText("Actions") self.render = self.list:Add("DButton") self.render:Dock(TOP) self.render:SetFont("ChatFont") self.render:SetText("RENDER") self.render:SetTall(30) self.render:DockMargin(5, 5, 5, 0) self.render.DoClick = function() renderAction(self) end self.copy = self.list:Add("DButton") self.copy:Dock(TOP) self.copy:SetFont("ChatFont") self.copy:SetText("COPY") self.copy:SetTall(30) self.copy:DockMargin(5, 5, 5, 0) self.copy.DoClick = action self:AddText("Presets") for i = 1, 5 do local btn = self.list:Add("DButton") btn:Dock(TOP) btn:SetFont("ChatFont") btn:SetText(bTxt[i]) btn:SetTall(30) btn:DockMargin(5, 5, 5, 0) btn.DoClick = function() self:SetupEditor(true, i) self:UpdateShits() end end self:AddText("Model Name") self.mdl = self.list:Add("DTextEntry") self.mdl:Dock(TOP) self.mdl:SetFont("Default") self.mdl:SetText("Copy that :)") self.mdl:SetTall(25) self.mdl:DockMargin(5, 5, 5, 0) self.mdl.OnEnter = function() ICON_INFO.modelName = self.mdl:GetValue() self:SetupEditor(true) self:UpdateShits() end self:AddText("Icon Size") local cfg = self.list:Add("DNumSlider") cfg:Dock(TOP) cfg:SetText("W") cfg:SetMin(0) cfg:SetMax(10) cfg:SetDecimals(0) cfg:SetValue(ICON_INFO.w) cfg:DockMargin(10, 0, 0, 5) cfg.OnValueChanged = function(cfg, value) ICON_INFO.w = value self.prev:AdjustSize(ICON_INFO.w, ICON_INFO.h) self.prev2:AdjustSize(ICON_INFO.w, ICON_INFO.h) end local cfg = self.list:Add("DNumSlider") cfg:Dock(TOP) cfg:SetText("H") cfg:SetMin(0) cfg:SetMax(10) cfg:SetDecimals(0) cfg:SetValue(ICON_INFO.h) cfg:DockMargin(10, 0, 0, 5) cfg.OnValueChanged = function(cfg, value) print(self) ICON_INFO.h = value self.prev:AdjustSize(ICON_INFO.w, ICON_INFO.h) self.prev2:AdjustSize(ICON_INFO.w, ICON_INFO.h) end self:AddText("Camera FOV") self.camFOV = self.list:Add("DNumSlider") self.camFOV:Dock(TOP) self.camFOV:SetText("CAMFOV") self.camFOV:SetMin(0) self.camFOV:SetMax(180) self.camFOV:SetDecimals(3) self.camFOV:SetValue(ICON_INFO.FOV) self.camFOV:DockMargin(10, 0, 0, 5) self.camFOV.OnValueChanged = function(cfg, value) if (!fagLord) then ICON_INFO.FOV = value local p = self.prev if (p and p:IsVisible()) then p.model:SetFOV(ICON_INFO.FOV) end end end self:AddText("Camera Position") self.camPos = {} for i = 1, 3 do self.camPos[i] = self.list:Add("DNumSlider") self.camPos[i]:Dock(TOP) self.camPos[i]:SetText("CAMPOS_" .. vTxt[i]) self.camPos[i]:SetMin(-500) self.camPos[i]:SetMax(500) self.camPos[i]:SetDecimals(3) self.camPos[i]:SetValue(ICON_INFO.camPos[i]) self.camPos[i]:DockMargin(10, 0, 0, 5) self.camPos[i].OnValueChanged = function(cfg, value) if (!fagLord) then ICON_INFO.camPos[i] = value end end end self:AddText("Camera Angle") self.camAng = {} for i = 1, 3 do self.camAng[i] = self.list:Add("DNumSlider") self.camAng[i]:Dock(TOP) self.camAng[i]:SetText("CAMANG_" .. aTxt[i]) self.camAng[i]:SetMin(-180) self.camAng[i]:SetMax(180) self.camAng[i]:SetDecimals(3) self.camAng[i]:SetValue(ICON_INFO.camAng[i]) self.camAng[i]:DockMargin(10, 0, 0, 5) self.camAng[i].OnValueChanged = function(cfg, value) if (!fagLord) then ICON_INFO.camAng[i] = value end end end self:SetupEditor() self:UpdateShits(true) end function PANEL:UpdateShits() fagLord = true self.camFOV:SetValue(ICON_INFO.FOV) for i = 1, 3 do self.camPos[i]:SetValue(ICON_INFO.camPos[i]) self.camAng[i]:SetValue(ICON_INFO.camAng[i]) end fagLord = false end function PANEL:SetupEditor(update, mode) local p = self.prev local p2 = self.prev2 if (p and p:IsVisible() and p2 and p2:IsVisible()) then p.model:SetModel(ICON_INFO.modelName) p2.model:SetModel(ICON_INFO.modelName) if (!update) then self.mdl:SetText(ICON_INFO.modelName) end if (mode) then if (mode == 1) then self:BestGuessLayout() elseif (mode == 2) then self:FullFrontalLayout() elseif (mode == 3) then self:AboveLayout() elseif (mode == 4) then self:RightLayout() elseif (mode == 5) then self:OriginLayout() end else self:BestGuessLayout() end p.model:SetCamPos(ICON_INFO.camPos) p.model:SetFOV(ICON_INFO.FOV) p.model:SetLookAng(ICON_INFO.camAng) end end function PANEL:BestGuessLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local tab = PositionSpawnIcon(ent, pos) if ( tab ) then ICON_INFO.camPos = tab.origin ICON_INFO.FOV = tab.fov ICON_INFO.camAng = tab.angles end end function PANEL:FullFrontalLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( -200, 0, 0 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = (campos * -1):Angle() end function PANEL:AboveLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( 0, 0, 200 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = (campos * -1):Angle() end function PANEL:RightLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( 0, 200, 0 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = (campos * -1):Angle() end function PANEL:OriginLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( 0, 0, 0 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = Angle( 0, -180, 0 ) end function PANEL:AddText(str) local label = self.list:Add("DLabel") label:SetFont("ChatFont") label:SetTextColor(color_white) label:Dock(TOP) label:DockMargin(5, 5, 5, 0) label:SetContentAlignment(5) label:SetText(str) end function PANEL:OnRemove() if (self.prev and self.prev:IsVisible()) then self.prev:Close() end if (self.prev2 and self.prev2:IsVisible()) then self.prev2:Close() end end vgui.Register("iconEditor", PANEL, "DFrame") concommand.Add("nut_dev_icon", function() if (LocalPlayer():IsAdmin()) then vgui.Create("iconEditor") end end)
mit
protomech/epgp-dkp-reloaded
libs/AceComm-3.0/ChatThrottleLib.lua
22
15434
-- -- ChatThrottleLib by Mikk -- -- Manages AddOn chat output to keep player from getting kicked off. -- -- ChatThrottleLib:SendChatMessage/:SendAddonMessage functions that accept -- a Priority ("BULK", "NORMAL", "ALERT") as well as prefix for SendChatMessage. -- -- Priorities get an equal share of available bandwidth when fully loaded. -- Communication channels are separated on extension+chattype+destination and -- get round-robinned. (Destination only matters for whispers and channels, -- obviously) -- -- Will install hooks for SendChatMessage and SendAddonMessage to measure -- bandwidth bypassing the library and use less bandwidth itself. -- -- -- Fully embeddable library. Just copy this file into your addon directory, -- add it to the .toc, and it's done. -- -- Can run as a standalone addon also, but, really, just embed it! :-) -- -- LICENSE: ChatThrottleLib is released into the Public Domain -- local CTL_VERSION = 23 local _G = _G if _G.ChatThrottleLib then if _G.ChatThrottleLib.version >= CTL_VERSION then -- There's already a newer (or same) version loaded. Buh-bye. return elseif not _G.ChatThrottleLib.securelyHooked then print("ChatThrottleLib: Warning: There's an ANCIENT ChatThrottleLib.lua (pre-wow 2.0, <v16) in an addon somewhere. Get the addon updated or copy in a newer ChatThrottleLib.lua (>=v16) in it!") -- ATTEMPT to unhook; this'll behave badly if someone else has hooked... -- ... and if someone has securehooked, they can kiss that goodbye too... >.< _G.SendChatMessage = _G.ChatThrottleLib.ORIG_SendChatMessage if _G.ChatThrottleLib.ORIG_SendAddonMessage then _G.SendAddonMessage = _G.ChatThrottleLib.ORIG_SendAddonMessage end end _G.ChatThrottleLib.ORIG_SendChatMessage = nil _G.ChatThrottleLib.ORIG_SendAddonMessage = nil end if not _G.ChatThrottleLib then _G.ChatThrottleLib = {} end ChatThrottleLib = _G.ChatThrottleLib -- in case some addon does "local ChatThrottleLib" above us and we're copypasted (AceComm-2, sigh) local ChatThrottleLib = _G.ChatThrottleLib ChatThrottleLib.version = CTL_VERSION ------------------ TWEAKABLES ----------------- ChatThrottleLib.MAX_CPS = 800 -- 2000 seems to be safe if NOTHING ELSE is happening. let's call it 800. ChatThrottleLib.MSG_OVERHEAD = 40 -- Guesstimate overhead for sending a message; source+dest+chattype+protocolstuff ChatThrottleLib.BURST = 4000 -- WoW's server buffer seems to be about 32KB. 8KB should be safe, but seen disconnects on _some_ servers. Using 4KB now. ChatThrottleLib.MIN_FPS = 20 -- Reduce output CPS to half (and don't burst) if FPS drops below this value local setmetatable = setmetatable local table_remove = table.remove local tostring = tostring local GetTime = GetTime local math_min = math.min local math_max = math.max local next = next local strlen = string.len local GetFramerate = GetFramerate local strlower = string.lower local unpack,type,pairs,wipe = unpack,type,pairs,wipe local UnitInRaid,UnitInParty = UnitInRaid,UnitInParty ----------------------------------------------------------------------- -- Double-linked ring implementation local Ring = {} local RingMeta = { __index = Ring } function Ring:New() local ret = {} setmetatable(ret, RingMeta) return ret end function Ring:Add(obj) -- Append at the "far end" of the ring (aka just before the current position) if self.pos then obj.prev = self.pos.prev obj.prev.next = obj obj.next = self.pos obj.next.prev = obj else obj.next = obj obj.prev = obj self.pos = obj end end function Ring:Remove(obj) obj.next.prev = obj.prev obj.prev.next = obj.next if self.pos == obj then self.pos = obj.next if self.pos == obj then self.pos = nil end end end ----------------------------------------------------------------------- -- Recycling bin for pipes -- A pipe is a plain integer-indexed queue of messages -- Pipes normally live in Rings of pipes (3 rings total, one per priority) ChatThrottleLib.PipeBin = nil -- pre-v19, drastically different local PipeBin = setmetatable({}, {__mode="k"}) local function DelPipe(pipe) PipeBin[pipe] = true end local function NewPipe() local pipe = next(PipeBin) if pipe then wipe(pipe) PipeBin[pipe] = nil return pipe end return {} end ----------------------------------------------------------------------- -- Recycling bin for messages ChatThrottleLib.MsgBin = nil -- pre-v19, drastically different local MsgBin = setmetatable({}, {__mode="k"}) local function DelMsg(msg) msg[1] = nil -- there's more parameters, but they're very repetetive so the string pool doesn't suffer really, and it's faster to just not delete them. MsgBin[msg] = true end local function NewMsg() local msg = next(MsgBin) if msg then MsgBin[msg] = nil return msg end return {} end ----------------------------------------------------------------------- -- ChatThrottleLib:Init -- Initialize queues, set up frame for OnUpdate, etc function ChatThrottleLib:Init() -- Set up queues if not self.Prio then self.Prio = {} self.Prio["ALERT"] = { ByName = {}, Ring = Ring:New(), avail = 0 } self.Prio["NORMAL"] = { ByName = {}, Ring = Ring:New(), avail = 0 } self.Prio["BULK"] = { ByName = {}, Ring = Ring:New(), avail = 0 } end -- v4: total send counters per priority for _, Prio in pairs(self.Prio) do Prio.nTotalSent = Prio.nTotalSent or 0 end if not self.avail then self.avail = 0 -- v5 end if not self.nTotalSent then self.nTotalSent = 0 -- v5 end -- Set up a frame to get OnUpdate events if not self.Frame then self.Frame = CreateFrame("Frame") self.Frame:Hide() end self.Frame:SetScript("OnUpdate", self.OnUpdate) self.Frame:SetScript("OnEvent", self.OnEvent) -- v11: Monitor P_E_W so we can throttle hard for a few seconds self.Frame:RegisterEvent("PLAYER_ENTERING_WORLD") self.OnUpdateDelay = 0 self.LastAvailUpdate = GetTime() self.HardThrottlingBeginTime = GetTime() -- v11: Throttle hard for a few seconds after startup -- Hook SendChatMessage and SendAddonMessage so we can measure unpiped traffic and avoid overloads (v7) if not self.securelyHooked then -- Use secure hooks as of v16. Old regular hook support yanked out in v21. self.securelyHooked = true --SendChatMessage hooksecurefunc("SendChatMessage", function(...) return ChatThrottleLib.Hook_SendChatMessage(...) end) --SendAddonMessage hooksecurefunc("SendAddonMessage", function(...) return ChatThrottleLib.Hook_SendAddonMessage(...) end) end self.nBypass = 0 end ----------------------------------------------------------------------- -- ChatThrottleLib.Hook_SendChatMessage / .Hook_SendAddonMessage local bMyTraffic = false function ChatThrottleLib.Hook_SendChatMessage(text, chattype, language, destination, ...) if bMyTraffic then return end local self = ChatThrottleLib local size = strlen(tostring(text or "")) + strlen(tostring(destination or "")) + self.MSG_OVERHEAD self.avail = self.avail - size self.nBypass = self.nBypass + size -- just a statistic end function ChatThrottleLib.Hook_SendAddonMessage(prefix, text, chattype, destination, ...) if bMyTraffic then return end local self = ChatThrottleLib local size = tostring(text or ""):len() + tostring(prefix or ""):len(); size = size + tostring(destination or ""):len() + self.MSG_OVERHEAD self.avail = self.avail - size self.nBypass = self.nBypass + size -- just a statistic end ----------------------------------------------------------------------- -- ChatThrottleLib:UpdateAvail -- Update self.avail with how much bandwidth is currently available function ChatThrottleLib:UpdateAvail() local now = GetTime() local MAX_CPS = self.MAX_CPS; local newavail = MAX_CPS * (now - self.LastAvailUpdate) local avail = self.avail if now - self.HardThrottlingBeginTime < 5 then -- First 5 seconds after startup/zoning: VERY hard clamping to avoid irritating the server rate limiter, it seems very cranky then avail = math_min(avail + (newavail*0.1), MAX_CPS*0.5) self.bChoking = true elseif GetFramerate() < self.MIN_FPS then -- GetFrameRate call takes ~0.002 secs avail = math_min(MAX_CPS, avail + newavail*0.5) self.bChoking = true -- just a statistic else avail = math_min(self.BURST, avail + newavail) self.bChoking = false end avail = math_max(avail, 0-(MAX_CPS*2)) -- Can go negative when someone is eating bandwidth past the lib. but we refuse to stay silent for more than 2 seconds; if they can do it, we can. self.avail = avail self.LastAvailUpdate = now return avail end ----------------------------------------------------------------------- -- Despooling logic -- Reminder: -- - We have 3 Priorities, each containing a "Ring" construct ... -- - ... made up of N "Pipe"s (1 for each destination/pipename) -- - and each pipe contains messages function ChatThrottleLib:Despool(Prio) local ring = Prio.Ring while ring.pos and Prio.avail > ring.pos[1].nSize do local msg = table_remove(ring.pos, 1) if not ring.pos[1] then -- did we remove last msg in this pipe? local pipe = Prio.Ring.pos Prio.Ring:Remove(pipe) Prio.ByName[pipe.name] = nil DelPipe(pipe) else Prio.Ring.pos = Prio.Ring.pos.next end local didSend=false local lowerDest = strlower(msg[3] or "") if lowerDest == "raid" and not UnitInRaid("player") then -- do nothing elseif lowerDest == "party" and not UnitInParty("player") then -- do nothing else Prio.avail = Prio.avail - msg.nSize bMyTraffic = true msg.f(unpack(msg, 1, msg.n)) bMyTraffic = false Prio.nTotalSent = Prio.nTotalSent + msg.nSize DelMsg(msg) didSend = true end -- notify caller of delivery (even if we didn't send it) if msg.callbackFn then msg.callbackFn (msg.callbackArg, didSend) end -- USER CALLBACK MAY ERROR end end function ChatThrottleLib.OnEvent(this,event) -- v11: We know that the rate limiter is touchy after login. Assume that it's touchy after zoning, too. local self = ChatThrottleLib if event == "PLAYER_ENTERING_WORLD" then self.HardThrottlingBeginTime = GetTime() -- Throttle hard for a few seconds after zoning self.avail = 0 end end function ChatThrottleLib.OnUpdate(this,delay) local self = ChatThrottleLib self.OnUpdateDelay = self.OnUpdateDelay + delay if self.OnUpdateDelay < 0.08 then return end self.OnUpdateDelay = 0 self:UpdateAvail() if self.avail < 0 then return -- argh. some bastard is spewing stuff past the lib. just bail early to save cpu. end -- See how many of our priorities have queued messages (we only have 3, don't worry about the loop) local n = 0 for prioname,Prio in pairs(self.Prio) do if Prio.Ring.pos or Prio.avail < 0 then n = n + 1 end end -- Anything queued still? if n<1 then -- Nope. Move spillover bandwidth to global availability gauge and clear self.bQueueing for prioname, Prio in pairs(self.Prio) do self.avail = self.avail + Prio.avail Prio.avail = 0 end self.bQueueing = false self.Frame:Hide() return end -- There's stuff queued. Hand out available bandwidth to priorities as needed and despool their queues local avail = self.avail/n self.avail = 0 for prioname, Prio in pairs(self.Prio) do if Prio.Ring.pos or Prio.avail < 0 then Prio.avail = Prio.avail + avail if Prio.Ring.pos and Prio.avail > Prio.Ring.pos[1].nSize then self:Despool(Prio) -- Note: We might not get here if the user-supplied callback function errors out! Take care! end end end end ----------------------------------------------------------------------- -- Spooling logic function ChatThrottleLib:Enqueue(prioname, pipename, msg) local Prio = self.Prio[prioname] local pipe = Prio.ByName[pipename] if not pipe then self.Frame:Show() pipe = NewPipe() pipe.name = pipename Prio.ByName[pipename] = pipe Prio.Ring:Add(pipe) end pipe[#pipe + 1] = msg self.bQueueing = true end function ChatThrottleLib:SendChatMessage(prio, prefix, text, chattype, language, destination, queueName, callbackFn, callbackArg) if not self or not prio or not prefix or not text or not self.Prio[prio] then error('Usage: ChatThrottleLib:SendChatMessage("{BULK||NORMAL||ALERT}", "prefix", "text"[, "chattype"[, "language"[, "destination"]]]', 2) end if callbackFn and type(callbackFn)~="function" then error('ChatThrottleLib:ChatMessage(): callbackFn: expected function, got '..type(callbackFn), 2) end local nSize = text:len() if nSize>255 then error("ChatThrottleLib:SendChatMessage(): message length cannot exceed 255 bytes", 2) end nSize = nSize + self.MSG_OVERHEAD -- Check if there's room in the global available bandwidth gauge to send directly if not self.bQueueing and nSize < self:UpdateAvail() then self.avail = self.avail - nSize bMyTraffic = true _G.SendChatMessage(text, chattype, language, destination) bMyTraffic = false self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize if callbackFn then callbackFn (callbackArg, true) end -- USER CALLBACK MAY ERROR return end -- Message needs to be queued local msg = NewMsg() msg.f = _G.SendChatMessage msg[1] = text msg[2] = chattype or "SAY" msg[3] = language msg[4] = destination msg.n = 4 msg.nSize = nSize msg.callbackFn = callbackFn msg.callbackArg = callbackArg self:Enqueue(prio, queueName or (prefix..(chattype or "SAY")..(destination or "")), msg) end function ChatThrottleLib:SendAddonMessage(prio, prefix, text, chattype, target, queueName, callbackFn, callbackArg) if not self or not prio or not prefix or not text or not chattype or not self.Prio[prio] then error('Usage: ChatThrottleLib:SendAddonMessage("{BULK||NORMAL||ALERT}", "prefix", "text", "chattype"[, "target"])', 2) end if callbackFn and type(callbackFn)~="function" then error('ChatThrottleLib:SendAddonMessage(): callbackFn: expected function, got '..type(callbackFn), 2) end local nSize = text:len(); if RegisterAddonMessagePrefix then if nSize>255 then error("ChatThrottleLib:SendAddonMessage(): message length cannot exceed 255 bytes", 2) end else nSize = nSize + prefix:len() + 1 if nSize>255 then error("ChatThrottleLib:SendAddonMessage(): prefix + message length cannot exceed 254 bytes", 2) end end nSize = nSize + self.MSG_OVERHEAD; -- Check if there's room in the global available bandwidth gauge to send directly if not self.bQueueing and nSize < self:UpdateAvail() then self.avail = self.avail - nSize bMyTraffic = true _G.SendAddonMessage(prefix, text, chattype, target) bMyTraffic = false self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize if callbackFn then callbackFn (callbackArg, true) end -- USER CALLBACK MAY ERROR return end -- Message needs to be queued local msg = NewMsg() msg.f = _G.SendAddonMessage msg[1] = prefix msg[2] = text msg[3] = chattype msg[4] = target msg.n = (target~=nil) and 4 or 3; msg.nSize = nSize msg.callbackFn = callbackFn msg.callbackArg = callbackArg self:Enqueue(prio, queueName or (prefix..chattype..(target or "")), msg) end ----------------------------------------------------------------------- -- Get the ball rolling! ChatThrottleLib:Init() --[[ WoWBench debugging snippet if(WOWB_VER) then local function SayTimer() print("SAY: "..GetTime().." "..arg1) end ChatThrottleLib.Frame:SetScript("OnEvent", SayTimer) ChatThrottleLib.Frame:RegisterEvent("CHAT_MSG_SAY") end ]]
bsd-3-clause
HandsomeCharming/RPG
Cocos2dx/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ArmatureAnimation.lua
7
3037
-------------------------------- -- @module ArmatureAnimation -- @extend ProcessBase -- @parent_module ccs -------------------------------- -- @function [parent=#ArmatureAnimation] getSpeedScale -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ArmatureAnimation] pause -- @param self -------------------------------- -- @function [parent=#ArmatureAnimation] setSpeedScale -- @param self -- @param #float float -------------------------------- -- @function [parent=#ArmatureAnimation] init -- @param self -- @param #ccs.Armature armature -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ArmatureAnimation] playWithIndexes -- @param self -- @param #array_table array -- @param #int int -- @param #bool bool -------------------------------- -- @function [parent=#ArmatureAnimation] play -- @param self -- @param #string str -- @param #int int -- @param #int int -------------------------------- -- @function [parent=#ArmatureAnimation] gotoAndPause -- @param self -- @param #int int -------------------------------- -- @function [parent=#ArmatureAnimation] resume -- @param self -------------------------------- -- @function [parent=#ArmatureAnimation] stop -- @param self -------------------------------- -- @function [parent=#ArmatureAnimation] update -- @param self -- @param #float float -------------------------------- -- @function [parent=#ArmatureAnimation] getAnimationData -- @param self -- @return AnimationData#AnimationData ret (return value: ccs.AnimationData) -------------------------------- -- @function [parent=#ArmatureAnimation] playWithIndex -- @param self -- @param #int int -- @param #int int -- @param #int int -------------------------------- -- @function [parent=#ArmatureAnimation] getCurrentMovementID -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#ArmatureAnimation] setAnimationData -- @param self -- @param #ccs.AnimationData animationdata -------------------------------- -- @function [parent=#ArmatureAnimation] gotoAndPlay -- @param self -- @param #int int -------------------------------- -- @function [parent=#ArmatureAnimation] playWithNames -- @param self -- @param #array_table array -- @param #int int -- @param #bool bool -------------------------------- -- @function [parent=#ArmatureAnimation] getMovementCount -- @param self -- @return long#long ret (return value: long) -------------------------------- -- @function [parent=#ArmatureAnimation] create -- @param self -- @param #ccs.Armature armature -- @return ArmatureAnimation#ArmatureAnimation ret (return value: ccs.ArmatureAnimation) -------------------------------- -- @function [parent=#ArmatureAnimation] ArmatureAnimation -- @param self return nil
gpl-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/texts/tutorial/stats/stats3.lua
1
1161
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org return [[ The final three important #GOLD#combat stats#WHITE# of your character are these: #LIGHT_GREEN#Physical power: #WHITE#Your ability to inflict damage and effects with weapons (including fists). #LIGHT_GREEN#Spellpower: #WHITE#Your ability to inflict damage and effects with spells. #LIGHT_GREEN#Mindpower: #WHITE#Your ability to inflict damage and effects with your mind. ]]
gpl-3.0
MOHAMMAD-MOSAVI/Security
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
behrouz-mansoori/faranesh
libs/dateparser.lua
1
6216
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-3.0
froggatt/openwrt-luci
applications/luci-diag-devinfo/luasrc/controller/luci_diag/luci_diag_devinfo.lua
76
2144
--[[ Luci diag - Diagnostics controller module (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.controller.luci_diag.luci_diag_devinfo", package.seeall) function index() local e e = entry({"admin", "voice", "diag", "phones"}, arcombine(cbi("luci_diag/smap_devinfo"), cbi("luci_diag/smap_devinfo_config")), _("Phones"), 10) e.leaf = true e.subindex = true e.dependent = true e = entry({"admin", "voice", "diag", "phones", "config"}, cbi("luci_diag/smap_devinfo_config"), _("Configure"), 10) e = entry({"admin", "status", "smap_devinfo"}, cbi("luci_diag/smap_devinfo"), _("SIP Devices on Network"), 120) e.leaf = true e.dependent = true e = entry({"admin", "network", "diag_config", "netdiscover_devinfo_config"}, cbi("luci_diag/netdiscover_devinfo_config"), _("Network Device Scan"), 100) e.leaf = true e.dependent = true e = entry({"admin", "network", "diag_config", "smap_devinfo_config"}, cbi("luci_diag/smap_devinfo_config"), _("SIP Device Scan")) e.leaf = true e.dependent = true e = entry({"admin", "status", "netdiscover_devinfo"}, cbi("luci_diag/netdiscover_devinfo"), _("Devices on Network"), 90) e.dependent = true e = entry({"admin", "network", "mactodevinfo"}, cbi("luci_diag/mactodevinfo"), _("MAC Device Info Overrides"), 190) e.dependent = true e = entry({"mini", "diag", "phone_scan"}, cbi("luci_diag/smap_devinfo_mini"), _("Phone Scan"), 100) e.dependent = true e = entry({"mini", "voice", "phones", "phone_scan_config"}, cbi("luci_diag/smap_devinfo_config_mini"), _("Config Phone Scan"), 90) e.dependent = true e = entry({"mini", "diag", "netdiscover_devinfo"}, cbi("luci_diag/netdiscover_devinfo_mini"), _("Network Device Scan"), 10) e.dependent = true e = entry({"mini", "network", "netdiscover_devinfo_config"}, cbi("luci_diag/netdiscover_devinfo_config_mini"), _("Device Scan Config")) e.dependent = true end
apache-2.0
nonchip/moon-mission
locco/markdown.lua
2
44764
#!/usr/bin/env lua --[[ # markdown.lua -- version 0.40 **Author:** Niklas Frykholm, <niklas@frykholm.se> **Date:** 31 May 2008 See the following page for changes to the original file https://github.com/speedata/luamarkdown This is an implementation of the popular text markup language Markdown in pure Lua. Markdown can convert documents written in a simple and easy to read text format to well-formatted HTML. For a more thourough description of Markdown and the Markdown syntax, see <http://daringfireball.net/projects/markdown>. The original Markdown source is written in Perl and makes heavy use of advanced regular expression techniques (such as negative look-ahead, etc) which are not available in Lua's simple regex engine. Therefore this Lua port has been rewritten from the ground up. It is probably not completely bug free. If you notice any bugs, please report them to me. A unit test that exposes the error is helpful. ## Usage local markdown = require "markdown" markdown.markdown(source) ``markdown.lua`` returns a table with a single function named ``markdown(s)`` which applies the Markdown transformation to the specified string. ``markdown.lua`` can also be used directly from the command line: lua markdown.lua test.md Creates a file ``test.html`` with the converted content of ``test.md``. Run: lua markdown.lua -h For a description of the command-line options. ``markdown.lua`` uses the same license as Lua, the MIT license. ## License Copyright &copy; 2008 Niklas Frykholm. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Version history - **0.40** -- 17 Apr 2014 - Compatibility for Lua 5.1 and 5.2 - **0.32** -- 31 May 2008 - Fix for links containing brackets - **0.31** -- 1 Mar 2008 - Fix for link definitions followed by spaces - **0.30** -- 25 Feb 2008 - Consistent behavior with Markdown when the same link reference is reused - **0.29** -- 24 Feb 2008 - Fix for <pre> blocks with spaces in them - **0.28** -- 18 Feb 2008 - Fix for link encoding - **0.27** -- 14 Feb 2008 - Fix for link database links with () - **0.26** -- 06 Feb 2008 - Fix for nested italic and bold markers - **0.25** -- 24 Jan 2008 - Fix for encoding of naked < - **0.24** -- 21 Jan 2008 - Fix for link behavior. - **0.23** -- 10 Jan 2008 - Fix for a regression bug in longer expressions in italic or bold. - **0.22** -- 27 Dec 2007 - Fix for crash when processing blocks with a percent sign in them. - **0.21** -- 27 Dec 2007 - Fix for combined strong and emphasis tags - **0.20** -- 13 Oct 2007 - Fix for < as well in image titles, now matches Dingus behavior - **0.19** -- 28 Sep 2007 - Fix for quotation marks " and ampersands & in link and image titles. - **0.18** -- 28 Jul 2007 - Does not crash on unmatched tags (behaves like standard markdown) - **0.17** -- 12 Apr 2007 - Fix for links with %20 in them. - **0.16** -- 12 Apr 2007 - Do not require arg global to exist. - **0.15** -- 28 Aug 2006 - Better handling of links with underscores in them. - **0.14** -- 22 Aug 2006 - Bug for *`foo()`* - **0.13** -- 12 Aug 2006 - Added -l option for including stylesheet inline in document. - Fixed bug in -s flag. - Fixed emphasis bug. - **0.12** -- 15 May 2006 - Fixed several bugs to comply with MarkdownTest 1.0 <http://six.pairlist.net/pipermail/markdown-discuss/2004-December/000909.html> - **0.11** -- 12 May 2006 - Fixed bug for escaping `*` and `_` inside code spans. - Added license terms. - Changed join() to table.concat(). - **0.10** -- 3 May 2006 - Initial public release. // Niklas ]] local unpack = unpack or table.unpack local span_transform, encode_backslash_escapes, block_transform, blocks_to_html, blocks_to_html ---------------------------------------------------------------------- -- Utility functions ---------------------------------------------------------------------- -- Returns the result of mapping the values in table t through the function f local function map(t, f) local out = {} for k,v in pairs(t) do out[k] = f(v,k) end return out end -- The identity function, useful as a placeholder. local function identity(text) return text end -- Functional style if statement. (NOTE: no short circuit evaluation) local function iff(t, a, b) if t then return a else return b end end -- Splits the text into an array of separate lines. local function split(text, sep) sep = sep or "\n" local lines = {} local pos = 1 while true do local b,e = text:find(sep, pos) if not b then table.insert(lines, text:sub(pos)) break end table.insert(lines, text:sub(pos, b-1)) pos = e + 1 end return lines end -- Converts tabs to spaces local function detab(text) local tab_width = 4 local function rep(match) local spaces = -match:len() while spaces<1 do spaces = spaces + tab_width end return match .. string.rep(" ", spaces) end text = text:gsub("([^\n]-)\t", rep) return text end -- Applies string.find for every pattern in the list and returns the first match local function find_first(s, patterns, index) local res = {} for _,p in ipairs(patterns) do local match = {s:find(p, index)} if #match>0 and (#res==0 or match[1] < res[1]) then res = match end end return unpack(res) end -- If a replacement array is specified, the range [start, stop] in the array is replaced -- with the replacement array and the resulting array is returned. Without a replacement -- array the section of the array between start and stop is returned. local function splice(array, start, stop, replacement) if replacement then local n = stop - start + 1 while n > 0 do table.remove(array, start) n = n - 1 end for i,v in ipairs(replacement) do table.insert(array, start, v) end return array else local res = {} for i = start,stop do table.insert(res, array[i]) end return res end end -- Outdents the text one step. local function outdent(text) text = "\n" .. text text = text:gsub("\n ? ? ?", "\n") text = text:sub(2) return text end -- Indents the text one step. local function indent(text) text = text:gsub("\n", "\n ") return text end -- Does a simple tokenization of html data. Returns the data as a list of tokens. -- Each token is a table with a type field (which is either "tag" or "text") and -- a text field (which contains the original token data). local function tokenize_html(html) local tokens = {} local pos = 1 while true do local start = find_first(html, {"<!%-%-", "<[a-z/!$]", "<%?"}, pos) if not start then table.insert(tokens, {type="text", text=html:sub(pos)}) break end if start ~= pos then table.insert(tokens, {type="text", text = html:sub(pos, start-1)}) end local _, stop if html:match("^<!%-%-", start) then _,stop = html:find("%-%->", start) elseif html:match("^<%?", start) then _,stop = html:find("?>", start) else _,stop = html:find("%b<>", start) end if not stop then -- error("Could not match html tag " .. html:sub(start,start+30)) table.insert(tokens, {type="text", text=html:sub(start, start)}) pos = start + 1 else table.insert(tokens, {type="tag", text=html:sub(start, stop)}) pos = stop + 1 end end return tokens end ---------------------------------------------------------------------- -- Hash ---------------------------------------------------------------------- -- This is used to "hash" data into alphanumeric strings that are unique -- in the document. (Note that this is not cryptographic hash, the hash -- function is not one-way.) The hash procedure is used to protect parts -- of the document from further processing. local HASH = { -- Has the hash been inited. inited = false, -- The unique string prepended to all hash values. This is to ensure -- that hash values do not accidently coincide with an actual existing -- string in the document. identifier = "", -- Counter that counts up for each new hash instance. counter = 0, -- Hash table. table = {} } -- Inits hashing. Creates a hash_identifier that doesn't occur anywhere -- in the text. local function init_hash(text) HASH.inited = true HASH.identifier = "" HASH.counter = 0 HASH.table = {} local s = "HASH" local counter = 0 local id while true do id = s .. counter if not text:find(id, 1, true) then break end counter = counter + 1 end HASH.identifier = id end -- Returns the hashed value for s. local function hash(s) assert(HASH.inited) if not HASH.table[s] then HASH.counter = HASH.counter + 1 local id = HASH.identifier .. HASH.counter .. "X" HASH.table[s] = id end return HASH.table[s] end ---------------------------------------------------------------------- -- Protection ---------------------------------------------------------------------- -- The protection module is used to "protect" parts of a document -- so that they are not modified by subsequent processing steps. -- Protected parts are saved in a table for later unprotection -- Protection data local PD = { -- Saved blocks that have been converted blocks = {}, -- Block level tags that will be protected tags = {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre", "table", "dl", "ol", "ul", "script", "noscript", "form", "fieldset", "iframe", "math", "ins", "del"} } -- Pattern for matching a block tag that begins and ends in the leftmost -- column and may contain indented subtags, i.e. -- <div> -- A nested block. -- <div> -- Nested data. -- </div> -- </div> local function block_pattern(tag) return "\n<" .. tag .. ".-\n</" .. tag .. ">[ \t]*\n" end -- Pattern for matching a block tag that begins and ends with a newline local function line_pattern(tag) return "\n<" .. tag .. ".-</" .. tag .. ">[ \t]*\n" end -- Protects the range of characters from start to stop in the text and -- returns the protected string. local function protect_range(text, start, stop) local s = text:sub(start, stop) local h = hash(s) PD.blocks[h] = s text = text:sub(1,start) .. h .. text:sub(stop) return text end -- Protect every part of the text that matches any of the patterns. The first -- matching pattern is protected first, etc. local function protect_matches(text, patterns) while true do local start, stop = find_first(text, patterns) if not start then break end text = protect_range(text, start, stop) end return text end -- Protects blocklevel tags in the specified text local function protect(text) -- First protect potentially nested block tags text = protect_matches(text, map(PD.tags, block_pattern)) -- Then protect block tags at the line level. text = protect_matches(text, map(PD.tags, line_pattern)) -- Protect <hr> and comment tags text = protect_matches(text, {"\n<hr[^>]->[ \t]*\n"}) text = protect_matches(text, {"\n<!%-%-.-%-%->[ \t]*\n"}) return text end -- Returns true if the string s is a hash resulting from protection local function is_protected(s) return PD.blocks[s] end -- Unprotects the specified text by expanding all the nonces local function unprotect(text) for k,v in pairs(PD.blocks) do v = v:gsub("%%", "%%%%") text = text:gsub(k, v) end return text end ---------------------------------------------------------------------- -- Block transform ---------------------------------------------------------------------- -- The block transform functions transform the text on the block level. -- They work with the text as an array of lines rather than as individual -- characters. -- Returns true if the line is a ruler of (char) characters. -- The line must contain at least three char characters and contain only spaces and -- char characters. local function is_ruler_of(line, char) if not line:match("^[ %" .. char .. "]*$") then return false end if not line:match("%" .. char .. ".*%" .. char .. ".*%" .. char) then return false end return true end -- Identifies the block level formatting present in the line local function classify(line) local info = {line = line, text = line} if line:match("^ ") then info.type = "indented" info.outdented = line:sub(5) return info end for _,c in ipairs({'*', '-', '_', '='}) do if is_ruler_of(line, c) then info.type = "ruler" info.ruler_char = c return info end end if line == "" then info.type = "blank" return info end if line:match("^(#+)[ \t]*(.-)[ \t]*#*[ \t]*$") then local m1, m2 = line:match("^(#+)[ \t]*(.-)[ \t]*#*[ \t]*$") info.type = "header" info.level = m1:len() info.text = m2 return info end if line:match("^ ? ? ?(%d+)%.[ \t]+(.+)") then local number, text = line:match("^ ? ? ?(%d+)%.[ \t]+(.+)") info.type = "list_item" info.list_type = "numeric" info.number = 0 + number info.text = text return info end if line:match("^ ? ? ?([%*%+%-])[ \t]+(.+)") then local bullet, text = line:match("^ ? ? ?([%*%+%-])[ \t]+(.+)") info.type = "list_item" info.list_type = "bullet" info.bullet = bullet info.text= text return info end if line:match("^>[ \t]?(.*)") then info.type = "blockquote" info.text = line:match("^>[ \t]?(.*)") return info end if is_protected(line) then info.type = "raw" info.html = unprotect(line) return info end info.type = "normal" return info end -- Find headers constisting of a normal line followed by a ruler and converts them to -- header entries. local function headers(array) local i = 1 while i <= #array - 1 do if array[i].type == "normal" and array[i+1].type == "ruler" and (array[i+1].ruler_char == "-" or array[i+1].ruler_char == "=") then local info = {line = array[i].line} info.text = info.line info.type = "header" info.level = iff(array[i+1].ruler_char == "=", 1, 2) table.remove(array, i+1) array[i] = info end i = i + 1 end return array end -- Find list blocks and convert them to protected data blocks local function lists(array, sublist) local function process_list(arr) local function any_blanks(arr) for i = 1, #arr do if arr[i].type == "blank" then return true end end return false end local function split_list_items(arr) local acc = {arr[1]} local res = {} for i=2,#arr do if arr[i].type == "list_item" then table.insert(res, acc) acc = {arr[i]} else table.insert(acc, arr[i]) end end table.insert(res, acc) return res end local function process_list_item(lines, block) while lines[#lines].type == "blank" do table.remove(lines) end local itemtext = lines[1].text for i=2,#lines do itemtext = itemtext .. "\n" .. outdent(lines[i].line) end if block then itemtext = block_transform(itemtext, true) if not itemtext:find("<pre>") then itemtext = indent(itemtext) end return " <li>" .. itemtext .. "</li>" else local lines = split(itemtext) lines = map(lines, classify) lines = lists(lines, true) lines = blocks_to_html(lines, true) itemtext = table.concat(lines, "\n") if not itemtext:find("<pre>") then itemtext = indent(itemtext) end return " <li>" .. itemtext .. "</li>" end end local block_list = any_blanks(arr) local items = split_list_items(arr) local out = "" for _, item in ipairs(items) do out = out .. process_list_item(item, block_list) .. "\n" end if arr[1].list_type == "numeric" then return "<ol>\n" .. out .. "</ol>" else return "<ul>\n" .. out .. "</ul>" end end -- Finds the range of lines composing the first list in the array. A list -- starts with (^ list_item) or (blank list_item) and ends with -- (blank* $) or (blank normal). -- -- A sublist can start with just (list_item) does not need a blank... local function find_list(array, sublist) local function find_list_start(array, sublist) if array[1].type == "list_item" then return 1 end if sublist then for i = 1,#array do if array[i].type == "list_item" then return i end end else for i = 1, #array-1 do if array[i].type == "blank" and array[i+1].type == "list_item" then return i+1 end end end return nil end local function find_list_end(array, start) local pos = #array for i = start, #array-1 do if array[i].type == "blank" and array[i+1].type ~= "list_item" and array[i+1].type ~= "indented" and array[i+1].type ~= "blank" then pos = i-1 break end end while pos > start and array[pos].type == "blank" do pos = pos - 1 end return pos end local start = find_list_start(array, sublist) if not start then return nil end return start, find_list_end(array, start) end while true do local start, stop = find_list(array, sublist) if not start then break end local text = process_list(splice(array, start, stop)) local info = { line = text, type = "raw", html = text } array = splice(array, start, stop, {info}) end -- Convert any remaining list items to normal for _,line in ipairs(array) do if line.type == "list_item" then line.type = "normal" end end return array end -- Find and convert blockquote markers. local function blockquotes(lines) local function find_blockquote(lines) local start for i,line in ipairs(lines) do if line.type == "blockquote" then start = i break end end if not start then return nil end local stop = #lines for i = start+1, #lines do if lines[i].type == "blank" or lines[i].type == "blockquote" then elseif lines[i].type == "normal" then if lines[i-1].type == "blank" then stop = i-1 break end else stop = i-1 break end end while lines[stop].type == "blank" do stop = stop - 1 end return start, stop end local function process_blockquote(lines) local raw = lines[1].text for i = 2,#lines do raw = raw .. "\n" .. lines[i].text end local bt = block_transform(raw) if not bt:find("<pre>") then bt = indent(bt) end return "<blockquote>\n " .. bt .. "\n</blockquote>" end while true do local start, stop = find_blockquote(lines) if not start then break end local text = process_blockquote(splice(lines, start, stop)) local info = { line = text, type = "raw", html = text } lines = splice(lines, start, stop, {info}) end return lines end -- Find and convert codeblocks. local function codeblocks(lines) local function find_codeblock(lines) local start for i,line in ipairs(lines) do if line.type == "indented" then start = i break end end if not start then return nil end local stop = #lines for i = start+1, #lines do if lines[i].type ~= "indented" and lines[i].type ~= "blank" then stop = i-1 break end end while lines[stop].type == "blank" do stop = stop - 1 end return start, stop end local function process_codeblock(lines) local raw = detab(encode_code(outdent(lines[1].line))) for i = 2,#lines do raw = raw .. "\n" .. detab(encode_code(outdent(lines[i].line))) end return "<pre><code>" .. raw .. "\n</code></pre>" end while true do local start, stop = find_codeblock(lines) if not start then break end local text = process_codeblock(splice(lines, start, stop)) local info = { line = text, type = "raw", html = text } lines = splice(lines, start, stop, {info}) end return lines end -- Convert lines to html code function blocks_to_html(lines, no_paragraphs) local out = {} local i = 1 while i <= #lines do local line = lines[i] if line.type == "ruler" then table.insert(out, "<hr/>") elseif line.type == "raw" then table.insert(out, line.html) elseif line.type == "normal" then local s = line.line while i+1 <= #lines and lines[i+1].type == "normal" do i = i + 1 s = s .. "\n" .. lines[i].line end if no_paragraphs then table.insert(out, span_transform(s)) else table.insert(out, "<p>" .. span_transform(s) .. "</p>") end elseif line.type == "header" then local s = "<h" .. line.level .. ">" .. span_transform(line.text) .. "</h" .. line.level .. ">" table.insert(out, s) else table.insert(out, line.line) end i = i + 1 end return out end -- Perform all the block level transforms function block_transform(text, sublist) local lines = split(text) lines = map(lines, classify) lines = headers(lines) lines = lists(lines, sublist) lines = codeblocks(lines) lines = blockquotes(lines) lines = blocks_to_html(lines) local text = table.concat(lines, "\n") return text end -- Debug function for printing a line array to see the result -- of partial transforms. local function print_lines(lines) for i, line in ipairs(lines) do print(i, line.type, line.text or line.line) end end ---------------------------------------------------------------------- -- Span transform ---------------------------------------------------------------------- -- Functions for transforming the text at the span level. -- These characters may need to be escaped because they have a special -- meaning in markdown. escape_chars = "'\\`*_{}[]()>#+-.!'" escape_table = {} local function init_escape_table() escape_table = {} for i = 1,#escape_chars do local c = escape_chars:sub(i,i) escape_table[c] = hash(c) end end -- Adds a new escape to the escape table. local function add_escape(text) if not escape_table[text] then escape_table[text] = hash(text) end return escape_table[text] end -- Escape characters that should not be disturbed by markdown. local function escape_special_chars(text) local tokens = tokenize_html(text) local out = "" for _, token in ipairs(tokens) do local t = token.text if token.type == "tag" then -- In tags, encode * and _ so they don't conflict with their use in markdown. t = t:gsub("%*", escape_table["*"]) t = t:gsub("%_", escape_table["_"]) else t = encode_backslash_escapes(t) end out = out .. t end return out end -- Encode backspace-escaped characters in the markdown source. function encode_backslash_escapes(t) for i=1,escape_chars:len() do local c = escape_chars:sub(i,i) t = t:gsub("\\%" .. c, escape_table[c]) end return t end -- Unescape characters that have been encoded. local function unescape_special_chars(t) local tin = t for k,v in pairs(escape_table) do k = k:gsub("%%", "%%%%") t = t:gsub(v,k) end if t ~= tin then t = unescape_special_chars(t) end return t end -- Encode/escape certain characters inside Markdown code runs. -- The point is that in code, these characters are literals, -- and lose their special Markdown meanings. function encode_code(s) s = s:gsub("%&", "&amp;") s = s:gsub("<", "&lt;") s = s:gsub(">", "&gt;") for k,v in pairs(escape_table) do s = s:gsub("%"..k, v) end return s end -- Handle backtick blocks. local function code_spans(s) s = s:gsub("\\\\", escape_table["\\"]) s = s:gsub("\\`", escape_table["`"]) local pos = 1 while true do local start, stop = s:find("`+", pos) if not start then return s end local count = stop - start + 1 -- Find a matching numbert of backticks local estart, estop = s:find(string.rep("`", count), stop+1) local brstart = s:find("\n", stop+1) if estart and (not brstart or estart < brstart) then local code = s:sub(stop+1, estart-1) code = code:gsub("^[ \t]+", "") code = code:gsub("[ \t]+$", "") code = code:gsub(escape_table["\\"], escape_table["\\"] .. escape_table["\\"]) code = code:gsub(escape_table["`"], escape_table["\\"] .. escape_table["`"]) code = "<code>" .. encode_code(code) .. "</code>" code = add_escape(code) s = s:sub(1, start-1) .. code .. s:sub(estop+1) pos = start + code:len() else pos = stop + 1 end end return s end -- Encode alt text... enodes &, and ". local function encode_alt(s) if not s then return s end s = s:gsub('&', '&amp;') s = s:gsub('"', '&quot;') s = s:gsub('<', '&lt;') return s end -- Handle image references local function images(text) local function reference_link(alt, id) alt = encode_alt(alt:match("%b[]"):sub(2,-2)) id = id:match("%[(.*)%]"):lower() if id == "" then id = text:lower() end link_database[id] = link_database[id] or {} if not link_database[id].url then return nil end local url = link_database[id].url or id url = encode_alt(url) local title = encode_alt(link_database[id].title) if title then title = " title=\"" .. title .. "\"" else title = "" end return add_escape ('<img src="' .. url .. '" alt="' .. alt .. '"' .. title .. "/>") end local function inline_link(alt, link) alt = encode_alt(alt:match("%b[]"):sub(2,-2)) local url, title = link:match("%(<?(.-)>?[ \t]*['\"](.+)['\"]") url = url or link:match("%(<?(.-)>?%)") url = encode_alt(url) title = encode_alt(title) if title then return add_escape('<img src="' .. url .. '" alt="' .. alt .. '" title="' .. title .. '"/>') else return add_escape('<img src="' .. url .. '" alt="' .. alt .. '"/>') end end text = text:gsub("!(%b[])[ \t]*\n?[ \t]*(%b[])", reference_link) text = text:gsub("!(%b[])(%b())", inline_link) return text end -- Handle anchor references local function anchors(text) local function reference_link(text, id) text = text:match("%b[]"):sub(2,-2) id = id:match("%b[]"):sub(2,-2):lower() if id == "" then id = text:lower() end link_database[id] = link_database[id] or {} if not link_database[id].url then return nil end local url = link_database[id].url or id url = encode_alt(url) local title = encode_alt(link_database[id].title) if title then title = " title=\"" .. title .. "\"" else title = "" end return add_escape("<a href=\"" .. url .. "\"" .. title .. ">") .. text .. add_escape("</a>") end local function inline_link(text, link) text = text:match("%b[]"):sub(2,-2) local url, title = link:match("%(<?(.-)>?[ \t]*['\"](.+)['\"]") title = encode_alt(title) url = url or link:match("%(<?(.-)>?%)") or "" url = encode_alt(url) if title then return add_escape("<a href=\"" .. url .. "\" title=\"" .. title .. "\">") .. text .. "</a>" else return add_escape("<a href=\"" .. url .. "\">") .. text .. add_escape("</a>") end end text = text:gsub("(%b[])[ \t]*\n?[ \t]*(%b[])", reference_link) text = text:gsub("(%b[])(%b())", inline_link) return text end -- Handle auto links, i.e. <http://www.google.com/>. local function auto_links(text) local function link(s) return add_escape("<a href=\"" .. s .. "\">") .. s .. "</a>" end -- Encode chars as a mix of dec and hex entitites to (perhaps) fool -- spambots. local function encode_email_address(s) -- Use a deterministic encoding to make unit testing possible. -- Code 45% hex, 45% dec, 10% plain. local hex = {code = function(c) return "&#x" .. string.format("%x", c:byte()) .. ";" end, count = 1, rate = 0.45} local dec = {code = function(c) return "&#" .. c:byte() .. ";" end, count = 0, rate = 0.45} local plain = {code = function(c) return c end, count = 0, rate = 0.1} local codes = {hex, dec, plain} local function swap(t,k1,k2) local temp = t[k2] t[k2] = t[k1] t[k1] = temp end local out = "" for i = 1,s:len() do for _,code in ipairs(codes) do code.count = code.count + code.rate end if codes[1].count < codes[2].count then swap(codes,1,2) end if codes[2].count < codes[3].count then swap(codes,2,3) end if codes[1].count < codes[2].count then swap(codes,1,2) end local code = codes[1] local c = s:sub(i,i) -- Force encoding of "@" to make email address more invisible. if c == "@" and code == plain then code = codes[2] end out = out .. code.code(c) code.count = code.count - 1 end return out end local function mail(s) s = unescape_special_chars(s) local address = encode_email_address("mailto:" .. s) local text = encode_email_address(s) return add_escape("<a href=\"" .. address .. "\">") .. text .. "</a>" end -- links text = text:gsub("<(https?:[^'\">%s]+)>", link) text = text:gsub("<(ftp:[^'\">%s]+)>", link) -- mail text = text:gsub("<mailto:([^'\">%s]+)>", mail) text = text:gsub("<([-.%w]+%@[-.%w]+)>", mail) return text end -- Encode free standing amps (&) and angles (<)... note that this does not -- encode free >. local function amps_and_angles(s) -- encode amps not part of &..; expression local pos = 1 while true do local amp = s:find("&", pos) if not amp then break end local semi = s:find(";", amp+1) local stop = s:find("[ \t\n&]", amp+1) if not semi or (stop and stop < semi) or (semi - amp) > 15 then s = s:sub(1,amp-1) .. "&amp;" .. s:sub(amp+1) pos = amp+1 else pos = amp+1 end end -- encode naked <'s s = s:gsub("<([^a-zA-Z/?$!])", "&lt;%1") s = s:gsub("<$", "&lt;") -- what about >, nothing done in the original markdown source to handle them return s end -- Handles emphasis markers (* and _) in the text. local function emphasis(text) for _, s in ipairs {"%*%*", "%_%_"} do text = text:gsub(s .. "([^%s][%*%_]?)" .. s, "<strong>%1</strong>") text = text:gsub(s .. "([^%s][^<>]-[^%s][%*%_]?)" .. s, "<strong>%1</strong>") end for _, s in ipairs {"%*", "%_"} do text = text:gsub(s .. "([^%s_])" .. s, "<em>%1</em>") text = text:gsub(s .. "(<strong>[^%s_]</strong>)" .. s, "<em>%1</em>") text = text:gsub(s .. "([^%s_][^<>_]-[^%s_])" .. s, "<em>%1</em>") text = text:gsub(s .. "([^<>_]-<strong>[^<>_]-</strong>[^<>_]-)" .. s, "<em>%1</em>") end return text end -- Handles line break markers in the text. local function line_breaks(text) return text:gsub(" +\n", " <br/>\n") end -- Perform all span level transforms. function span_transform(text) text = code_spans(text) text = escape_special_chars(text) text = images(text) text = anchors(text) text = auto_links(text) text = amps_and_angles(text) text = emphasis(text) text = line_breaks(text) return text end ---------------------------------------------------------------------- -- Markdown ---------------------------------------------------------------------- -- Cleanup the text by normalizing some possible variations to make further -- processing easier. local function cleanup(text) -- Standardize line endings text = text:gsub("\r\n", "\n") -- DOS to UNIX text = text:gsub("\r", "\n") -- Mac to UNIX -- Convert all tabs to spaces text = detab(text) -- Strip lines with only spaces and tabs while true do local subs text, subs = text:gsub("\n[ \t]+\n", "\n\n") if subs == 0 then break end end return "\n" .. text .. "\n" end -- Strips link definitions from the text and stores the data in a lookup table. local function strip_link_definitions(text) local linkdb = {} local function link_def(id, url, title) id = id:match("%[(.+)%]"):lower() linkdb[id] = linkdb[id] or {} linkdb[id].url = url or linkdb[id].url linkdb[id].title = title or linkdb[id].title return "" end local def_no_title = "\n ? ? ?(%b[]):[ \t]*\n?[ \t]*<?([^%s>]+)>?[ \t]*" local def_title1 = def_no_title .. "[ \t]+\n?[ \t]*[\"'(]([^\n]+)[\"')][ \t]*" local def_title2 = def_no_title .. "[ \t]*\n[ \t]*[\"'(]([^\n]+)[\"')][ \t]*" local def_title3 = def_no_title .. "[ \t]*\n?[ \t]+[\"'(]([^\n]+)[\"')][ \t]*" text = text:gsub(def_title1, link_def) text = text:gsub(def_title2, link_def) text = text:gsub(def_title3, link_def) text = text:gsub(def_no_title, link_def) return text, linkdb end link_database = {} -- Main markdown processing function local function markdown(text) init_hash(text) init_escape_table() text = cleanup(text) text = protect(text) text, link_database = strip_link_definitions(text) text = block_transform(text) text = unescape_special_chars(text) return text end ---------------------------------------------------------------------- -- End of module ---------------------------------------------------------------------- -- Expose markdown function to the world md = { markdown = markdown } -- Class for parsing command-line options local OptionParser = {} OptionParser.__index = OptionParser -- Creates a new option parser function OptionParser:new() local o = {short = {}, long = {}} setmetatable(o, self) return o end -- Calls f() whenever a flag with specified short and long name is encountered function OptionParser:flag(short, long, f) local info = {type = "flag", f = f} if short then self.short[short] = info end if long then self.long[long] = info end end -- Calls f(param) whenever a parameter flag with specified short and long name is encountered function OptionParser:param(short, long, f) local info = {type = "param", f = f} if short then self.short[short] = info end if long then self.long[long] = info end end -- Calls f(v) for each non-flag argument function OptionParser:arg(f) self.arg = f end -- Runs the option parser for the specified set of arguments. Returns true if all arguments -- where successfully parsed and false otherwise. function OptionParser:run(args) local pos = 1 while pos <= #args do local arg = args[pos] if arg == "--" then for i=pos+1,#args do if self.arg then self.arg(args[i]) end return true end end if arg:match("^%-%-") then local info = self.long[arg:sub(3)] if not info then print("Unknown flag: " .. arg) return false end if info.type == "flag" then info.f() pos = pos + 1 else param = args[pos+1] if not param then print("No parameter for flag: " .. arg) return false end info.f(param) pos = pos+2 end elseif arg:match("^%-") then for i=2,arg:len() do local c = arg:sub(i,i) local info = self.short[c] if not info then print("Unknown flag: -" .. c) return false end if info.type == "flag" then info.f() else if i == arg:len() then param = args[pos+1] if not param then print("No parameter for flag: -" .. c) return false end info.f(param) pos = pos + 1 else param = arg:sub(i+1) info.f(param) end break end end pos = pos + 1 else if self.arg then self.arg(arg) end pos = pos + 1 end end return true end -- Handles the case when markdown is run from the command line local function run_command_line(arg) -- Generate output for input s given options local function run(s, options) s = markdown(s) if not options.wrap_header then return s end local header = "" if options.header then local f = io.open(options.header) or error("Could not open file: " .. options.header) header = f:read("*a") f:close() else header = [[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=CHARSET" /> <title>TITLE</title> <link rel="stylesheet" type="text/css" href="STYLESHEET" /> </head> <body> ]] local title = options.title or s:match("<h1>(.-)</h1>") or s:match("<h2>(.-)</h2>") or s:match("<h3>(.-)</h3>") or "Untitled" header = header:gsub("TITLE", title) if options.inline_style then local style = "" local f = io.open(options.stylesheet) if f then style = f:read("*a") f:close() else error("Could not include style sheet " .. options.stylesheet .. ": File not found") end header = header:gsub('<link rel="stylesheet" type="text/css" href="STYLESHEET" />', "<style type=\"text/css\"><!--\n" .. style .. "\n--></style>") else header = header:gsub("STYLESHEET", options.stylesheet) end header = header:gsub("CHARSET", options.charset) end local footer = "</body></html>" if options.footer then local f = io.open(options.footer) or error("Could not open file: " .. options.footer) footer = f:read("*a") f:close() end return header .. s .. footer end -- Generate output path name from input path name given options. local function outpath(path, options) if options.append then return path .. ".html" end local m = path:match("^(.+%.html)[^/\\]+$") if m then return m end m = path:match("^(.+%.)[^/\\]*$") if m and path ~= m .. "html" then return m .. "html" end return path .. ".html" end -- Default commandline options local options = { wrap_header = true, header = nil, footer = nil, charset = "utf-8", title = nil, stylesheet = "default.css", inline_style = false } local help = [[ Usage: markdown.lua [OPTION] [FILE] Runs the markdown text markup to HTML converter on each file specified on the command line. If no files are specified, runs on standard input. No header: -n, --no-wrap Don't wrap the output in <html>... tags. Custom header: -e, --header FILE Use content of FILE for header. -f, --footer FILE Use content of FILE for footer. Generated header: -c, --charset SET Specifies charset (default utf-8). -i, --title TITLE Specifies title (default from first <h1> tag). -s, --style STYLE Specifies style sheet file (default default.css). -l, --inline-style Include the style sheet file inline in the header. Generated files: -a, --append Append .html extension (instead of replacing). Other options: -h, --help Print this help text. -t, --test Run the unit tests. ]] local run_stdin = true local op = OptionParser:new() op:flag("n", "no-wrap", function () options.wrap_header = false end) op:param("e", "header", function (x) options.header = x end) op:param("f", "footer", function (x) options.footer = x end) op:param("c", "charset", function (x) options.charset = x end) op:param("i", "title", function(x) options.title = x end) op:param("s", "style", function(x) options.stylesheet = x end) op:flag("l", "inline-style", function(x) options.inline_style = true end) op:flag("a", "append", function() options.append = true end) op:flag("t", "test", function() local n = arg[0]:gsub("markdown.lua", "markdown-tests.lua") local f = io.open(n) if f then f:close() dofile(n) else error("Cannot find markdown-tests.lua") end run_stdin = false end) op:flag("h", "help", function() print(help) run_stdin = false end) op:arg(function(path) local file = io.open(path) or error("Could not open file: " .. path) local s = file:read("*a") file:close() s = run(s, options) file = io.open(outpath(path, options), "w") or error("Could not open output file: " .. outpath(path, options)) file:write(s) file:close() run_stdin = false end ) if not op:run(arg) then print(help) run_stdin = false end if run_stdin then local s = io.read("*a") s = run(s, options) io.write(s) end end -- If we are being run from the command-line, act accordingly if arg and arg[0]:find("markdown%.lua$") then run_command_line(arg) else return md end
mit
g10101k/GEDKeeper
scripts/sofonov_import.lua
3
4330
-- выбрать внешний файл csv_name = gk_select_file(); if (csv_name == "") then gk_print("Файл не выбран"); return end -- загрузка файла данных csv_load(csv_name, true); cols = csv_get_cols(); rows = csv_get_rows(); gk_print("Файл: "..csv_name..", столбцов: "..cols..", строк: "..rows); prev_vid = ""; prev_person = 0; marr_date = ""; birth_family = null; key_person = null; for r = 0, rows-1 do -- получение содержимого ячеек page = csv_get_cell(0, r); vid = csv_get_cell(1, r); link = csv_get_cell(2, r); date = csv_get_cell(3, r); name = csv_get_cell(4, r); patr_name = csv_get_cell(5, r); family = csv_get_cell(6, r); town = csv_get_cell(7, r); source = csv_get_cell(8, r); comment = csv_get_cell(10, r); -- вывод для отладки line = name.." "..patr_name.." "..family..", "..town..", "..source.." + "..page; gk_print(line); -- т.к. определение полного отчества требует пола, который сам требует отчества - необходимо выбрать -- ту операцию первой, которая меньше зависит от другой - это определение пола sex = gt_define_sex(name, patr_name); -- определение отчества, третий параметр - разрешение спрашивать пользователя, -- если у программы нет вариантов patronymic = gt_define_patronymic(patr_name, sex, true); -- создать персону p = gt_create_person(name, patronymic, family, sex); if (vid == "Брак") then marr_date = date; birth_family = null; else if (vid == "Рождение") then evt = gt_create_event(p, "BIRT"); gt_set_event_date(evt, date); marr_date = ""; birth_family = gt_create_family(); gt_bind_family_child(birth_family, p); end if (vid == "Смерть") then evt = gt_create_event(p, "DEAT"); gt_set_event_date(evt, date); marr_date = ""; birth_family = null; end end -- создать факт места проживания evt = gt_create_event(p, "RESI"); gt_set_event_place(evt, town); -- найти, не создан ли уже такой источник src = gt_find_source(source); if (src == 0) then -- создать отсутствующий src = gt_create_source(source); end -- присоединить источник к персоне (3 - высокое качество источника) gt_bind_record_source(p, src, page, 3); -- проверить, задан ли комментарий, если да - присоединить к персоне if not(comment == "") then n = gt_create_note(); gt_bind_record_note(p, n); gt_add_note_text(n, comment); end -- обработка семейных связей if (link == "Лицо") then key_person = p; end if (link == "Жена") then f = gt_create_family(); gt_bind_family_spouse(f, prev_person); -- предполагаем, что предыдущая персона - муж gt_bind_family_spouse(f, p); -- присоедниям к семье жену if not(marr_date == "") then evt = gt_create_event(f, "MARR"); gt_set_event_date(evt, date); end end if (link == "Отец") and not(birth_family == null) then gt_bind_family_spouse(birth_family, p); -- присоединяем к семье ребенка отца end if (link == "Мать") and not(birth_family == null) then gt_bind_family_spouse(birth_family, p); -- присоединяем к семье ребенка мать end if (link == "Кресный") then gt_add_person_association(key_person, link, p); end -- запоминаем состояние текущей строки if not(vid == "") then prev_vid = vid; end prev_person = p; end -- закрыли файл данных csv_close(); -- обновили списки базы данных gk_update_view();
gpl-3.0
UPTOSKYPROJECT/UPTOSKY
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
HandsomeCharming/RPG
Cocos2dx/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Sprite.lua
5
7894
-------------------------------- -- @module Sprite -- @extend Node,TextureProtocol -- @parent_module cc -------------------------------- -- @overload self, cc.SpriteFrame -- @overload self, string -- @function [parent=#Sprite] setSpriteFrame -- @param self -- @param #string str -------------------------------- -- @overload self, cc.Texture2D -- @overload self, string -- @function [parent=#Sprite] setTexture -- @param self -- @param #string str -------------------------------- -- @function [parent=#Sprite] getTexture -- @param self -- @return Texture2D#Texture2D ret (return value: cc.Texture2D) -------------------------------- -- @function [parent=#Sprite] setFlippedY -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Sprite] setFlippedX -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Sprite] getBatchNode -- @param self -- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode) -------------------------------- -- @function [parent=#Sprite] getOffsetPosition -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- @function [parent=#Sprite] removeAllChildrenWithCleanup -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Sprite] updateTransform -- @param self -------------------------------- -- @overload self, rect_table, bool, size_table -- @overload self, rect_table -- @function [parent=#Sprite] setTextureRect -- @param self -- @param #rect_table rect -- @param #bool bool -- @param #size_table size -------------------------------- -- @function [parent=#Sprite] isFrameDisplayed -- @param self -- @param #cc.SpriteFrame spriteframe -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Sprite] getAtlasIndex -- @param self -- @return long#long ret (return value: long) -------------------------------- -- @function [parent=#Sprite] setBatchNode -- @param self -- @param #cc.SpriteBatchNode spritebatchnode -------------------------------- -- @function [parent=#Sprite] setDisplayFrameWithAnimationName -- @param self -- @param #string str -- @param #long long -------------------------------- -- @function [parent=#Sprite] setTextureAtlas -- @param self -- @param #cc.TextureAtlas textureatlas -------------------------------- -- @function [parent=#Sprite] getSpriteFrame -- @param self -- @return SpriteFrame#SpriteFrame ret (return value: cc.SpriteFrame) -------------------------------- -- @function [parent=#Sprite] isDirty -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Sprite] setAtlasIndex -- @param self -- @param #long long -------------------------------- -- @function [parent=#Sprite] setDirty -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Sprite] isTextureRectRotated -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Sprite] getTextureRect -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- @function [parent=#Sprite] getTextureAtlas -- @param self -- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas) -------------------------------- -- @function [parent=#Sprite] isFlippedX -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Sprite] isFlippedY -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Sprite] setVertexRect -- @param self -- @param #rect_table rect -------------------------------- -- @overload self, string -- @overload self -- @overload self, string, rect_table -- @function [parent=#Sprite] create -- @param self -- @param #string str -- @param #rect_table rect -- @return Sprite#Sprite ret (retunr value: cc.Sprite) -------------------------------- -- @overload self, cc.Texture2D, rect_table, bool -- @overload self, cc.Texture2D -- @function [parent=#Sprite] createWithTexture -- @param self -- @param #cc.Texture2D texture2d -- @param #rect_table rect -- @param #bool bool -- @return Sprite#Sprite ret (retunr value: cc.Sprite) -------------------------------- -- @function [parent=#Sprite] createWithSpriteFrameName -- @param self -- @param #string str -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @function [parent=#Sprite] createWithSpriteFrame -- @param self -- @param #cc.SpriteFrame spriteframe -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @function [parent=#Sprite] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table mat4 -- @param #unsigned int int -------------------------------- -- @overload self, cc.Node, int, string -- @overload self, cc.Node, int, int -- @function [parent=#Sprite] addChild -- @param self -- @param #cc.Node node -- @param #int int -- @param #int int -------------------------------- -- @function [parent=#Sprite] setScaleY -- @param self -- @param #float float -------------------------------- -- @function [parent=#Sprite] setScaleX -- @param self -- @param #float float -------------------------------- -- @function [parent=#Sprite] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Sprite] setPositionZ -- @param self -- @param #float float -------------------------------- -- @function [parent=#Sprite] setAnchorPoint -- @param self -- @param #vec2_table vec2 -------------------------------- -- @function [parent=#Sprite] setRotationSkewX -- @param self -- @param #float float -------------------------------- -- @function [parent=#Sprite] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Sprite] setRotationSkewY -- @param self -- @param #float float -------------------------------- -- @overload self, float -- @overload self, float, float -- @function [parent=#Sprite] setScale -- @param self -- @param #float float -- @param #float float -------------------------------- -- @function [parent=#Sprite] reorderChild -- @param self -- @param #cc.Node node -- @param #int int -------------------------------- -- @function [parent=#Sprite] removeChild -- @param self -- @param #cc.Node node -- @param #bool bool -------------------------------- -- @function [parent=#Sprite] sortAllChildren -- @param self -------------------------------- -- @function [parent=#Sprite] setOpacityModifyRGB -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Sprite] setRotation -- @param self -- @param #float float -------------------------------- -- @function [parent=#Sprite] setSkewY -- @param self -- @param #float float -------------------------------- -- @function [parent=#Sprite] setVisible -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Sprite] setSkewX -- @param self -- @param #float float -------------------------------- -- @function [parent=#Sprite] ignoreAnchorPointForPosition -- @param self -- @param #bool bool return nil
gpl-2.0
dongguangming/sipml5
asterisk/etc/extensions.lua
317
5827
CONSOLE = "Console/dsp" -- Console interface for demo --CONSOLE = "DAHDI/1" --CONSOLE = "Phone/phone0" IAXINFO = "guest" -- IAXtel username/password --IAXINFO = "myuser:mypass" TRUNK = "DAHDI/G2" TRUNKMSD = 1 -- TRUNK = "IAX2/user:pass@provider" -- -- Extensions are expected to be defined in a global table named 'extensions'. -- The 'extensions' table should have a group of tables in it, each -- representing a context. Extensions are defined in each context. See below -- for examples. -- -- Extension names may be numbers, letters, or combinations thereof. If -- an extension name is prefixed by a '_' character, it is interpreted as -- a pattern rather than a literal. In patterns, some characters have -- special meanings: -- -- X - any digit from 0-9 -- Z - any digit from 1-9 -- N - any digit from 2-9 -- [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9) -- . - wildcard, matches anything remaining (e.g. _9011. matches -- anything starting with 9011 excluding 9011 itself) -- ! - wildcard, causes the matching process to complete as soon as -- it can unambiguously determine that no other matches are possible -- -- For example the extension _NXXXXXX would match normal 7 digit -- dialings, while _1NXXNXXXXXX would represent an area code plus phone -- number preceded by a one. -- -- If your extension has special characters in it such as '.' and '!' you must -- explicitly make it a string in the tabale definition: -- -- ["_special."] = function; -- ["_special!"] = function; -- -- There are no priorities. All extensions to asterisk appear to have a single -- priority as if they consist of a single priority. -- -- Each context is defined as a table in the extensions table. The -- context names should be strings. -- -- One context may be included in another context using the 'includes' -- extension. This extension should be set to a table containing a list -- of context names. Do not put references to tables in the includes -- table. -- -- include = {"a", "b", "c"}; -- -- Channel variables can be accessed thorugh the global 'channel' table. -- -- v = channel.var_name -- v = channel["var_name"] -- v.value -- v:get() -- -- channel.var_name = "value" -- channel["var_name"] = "value" -- v:set("value") -- -- channel.func_name(1,2,3):set("value") -- value = channel.func_name(1,2,3):get() -- -- channel["func_name(1,2,3)"]:set("value") -- channel["func_name(1,2,3)"] = "value" -- value = channel["func_name(1,2,3)"]:get() -- -- Note the use of the ':' operator to access the get() and set() -- methods. -- -- Also notice the absence of the following constructs from the examples above: -- channel.func_name(1,2,3) = "value" -- this will NOT work -- value = channel.func_name(1,2,3) -- this will NOT work as expected -- -- -- Dialplan applications can be accessed through the global 'app' table. -- -- app.Dial("DAHDI/1") -- app.dial("DAHDI/1") -- -- More examples can be found below. -- -- An autoservice is automatically run while lua code is executing. The -- autoservice can be stopped and restarted using the autoservice_stop() and -- autoservice_start() functions. The autservice should be running before -- starting long running operations. The autoservice will automatically be -- stopped before executing applications and dialplan functions and will be -- restarted afterwards. The autoservice_status() function can be used to -- check the current status of the autoservice and will return true if an -- autoservice is currently running. -- function outgoing_local(c, e) app.dial("DAHDI/1/" .. e, "", "") end function demo_instruct() app.background("demo-instruct") app.waitexten() end function demo_congrats() app.background("demo-congrats") demo_instruct() end -- Answer the chanel and play the demo sound files function demo_start(context, exten) app.wait(1) app.answer() channel.TIMEOUT("digit"):set(5) channel.TIMEOUT("response"):set(10) -- app.set("TIMEOUT(digit)=5") -- app.set("TIMEOUT(response)=10") demo_congrats(context, exten) end function demo_hangup() app.playback("demo-thanks") app.hangup() end extensions = { demo = { s = demo_start; ["2"] = function() app.background("demo-moreinfo") demo_instruct() end; ["3"] = function () channel.LANGUAGE():set("fr") -- set the language to french demo_congrats() end; ["1000"] = function() app.goto("demo", "s", 1) end; ["1234"] = function() app.playback("transfer", "skip") -- do a dial here end; ["1235"] = function() app.voicemail("1234", "u") end; ["1236"] = function() app.dial("Console/dsp") app.voicemail(1234, "b") end; ["#"] = demo_hangup; t = demo_hangup; i = function() app.playback("invalid") demo_instruct() end; ["500"] = function() app.playback("demo-abouttotry") app.dial("IAX2/guest@misery.digium.com/s@default") app.playback("demo-nogo") demo_instruct() end; ["600"] = function() app.playback("demo-echotest") app.echo() app.playback("demo-echodone") demo_instruct() end; ["8500"] = function() app.voicemailmain() demo_instruct() end; }; default = { -- by default, do the demo include = {"demo"}; }; public = { -- ATTENTION: If your Asterisk is connected to the internet and you do -- not have allowguest=no in sip.conf, everybody out there may use your -- public context without authentication. In that case you want to -- double check which services you offer to the world. -- include = {"demo"}; }; ["local"] = { ["_NXXXXXX"] = outgoing_local; }; } hints = { demo = { [1000] = "SIP/1000"; [1001] = "SIP/1001"; }; default = { ["1234"] = "SIP/1234"; }; }
bsd-3-clause
enricozhang/sipml5
asterisk/etc/extensions.lua
317
5827
CONSOLE = "Console/dsp" -- Console interface for demo --CONSOLE = "DAHDI/1" --CONSOLE = "Phone/phone0" IAXINFO = "guest" -- IAXtel username/password --IAXINFO = "myuser:mypass" TRUNK = "DAHDI/G2" TRUNKMSD = 1 -- TRUNK = "IAX2/user:pass@provider" -- -- Extensions are expected to be defined in a global table named 'extensions'. -- The 'extensions' table should have a group of tables in it, each -- representing a context. Extensions are defined in each context. See below -- for examples. -- -- Extension names may be numbers, letters, or combinations thereof. If -- an extension name is prefixed by a '_' character, it is interpreted as -- a pattern rather than a literal. In patterns, some characters have -- special meanings: -- -- X - any digit from 0-9 -- Z - any digit from 1-9 -- N - any digit from 2-9 -- [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9) -- . - wildcard, matches anything remaining (e.g. _9011. matches -- anything starting with 9011 excluding 9011 itself) -- ! - wildcard, causes the matching process to complete as soon as -- it can unambiguously determine that no other matches are possible -- -- For example the extension _NXXXXXX would match normal 7 digit -- dialings, while _1NXXNXXXXXX would represent an area code plus phone -- number preceded by a one. -- -- If your extension has special characters in it such as '.' and '!' you must -- explicitly make it a string in the tabale definition: -- -- ["_special."] = function; -- ["_special!"] = function; -- -- There are no priorities. All extensions to asterisk appear to have a single -- priority as if they consist of a single priority. -- -- Each context is defined as a table in the extensions table. The -- context names should be strings. -- -- One context may be included in another context using the 'includes' -- extension. This extension should be set to a table containing a list -- of context names. Do not put references to tables in the includes -- table. -- -- include = {"a", "b", "c"}; -- -- Channel variables can be accessed thorugh the global 'channel' table. -- -- v = channel.var_name -- v = channel["var_name"] -- v.value -- v:get() -- -- channel.var_name = "value" -- channel["var_name"] = "value" -- v:set("value") -- -- channel.func_name(1,2,3):set("value") -- value = channel.func_name(1,2,3):get() -- -- channel["func_name(1,2,3)"]:set("value") -- channel["func_name(1,2,3)"] = "value" -- value = channel["func_name(1,2,3)"]:get() -- -- Note the use of the ':' operator to access the get() and set() -- methods. -- -- Also notice the absence of the following constructs from the examples above: -- channel.func_name(1,2,3) = "value" -- this will NOT work -- value = channel.func_name(1,2,3) -- this will NOT work as expected -- -- -- Dialplan applications can be accessed through the global 'app' table. -- -- app.Dial("DAHDI/1") -- app.dial("DAHDI/1") -- -- More examples can be found below. -- -- An autoservice is automatically run while lua code is executing. The -- autoservice can be stopped and restarted using the autoservice_stop() and -- autoservice_start() functions. The autservice should be running before -- starting long running operations. The autoservice will automatically be -- stopped before executing applications and dialplan functions and will be -- restarted afterwards. The autoservice_status() function can be used to -- check the current status of the autoservice and will return true if an -- autoservice is currently running. -- function outgoing_local(c, e) app.dial("DAHDI/1/" .. e, "", "") end function demo_instruct() app.background("demo-instruct") app.waitexten() end function demo_congrats() app.background("demo-congrats") demo_instruct() end -- Answer the chanel and play the demo sound files function demo_start(context, exten) app.wait(1) app.answer() channel.TIMEOUT("digit"):set(5) channel.TIMEOUT("response"):set(10) -- app.set("TIMEOUT(digit)=5") -- app.set("TIMEOUT(response)=10") demo_congrats(context, exten) end function demo_hangup() app.playback("demo-thanks") app.hangup() end extensions = { demo = { s = demo_start; ["2"] = function() app.background("demo-moreinfo") demo_instruct() end; ["3"] = function () channel.LANGUAGE():set("fr") -- set the language to french demo_congrats() end; ["1000"] = function() app.goto("demo", "s", 1) end; ["1234"] = function() app.playback("transfer", "skip") -- do a dial here end; ["1235"] = function() app.voicemail("1234", "u") end; ["1236"] = function() app.dial("Console/dsp") app.voicemail(1234, "b") end; ["#"] = demo_hangup; t = demo_hangup; i = function() app.playback("invalid") demo_instruct() end; ["500"] = function() app.playback("demo-abouttotry") app.dial("IAX2/guest@misery.digium.com/s@default") app.playback("demo-nogo") demo_instruct() end; ["600"] = function() app.playback("demo-echotest") app.echo() app.playback("demo-echodone") demo_instruct() end; ["8500"] = function() app.voicemailmain() demo_instruct() end; }; default = { -- by default, do the demo include = {"demo"}; }; public = { -- ATTENTION: If your Asterisk is connected to the internet and you do -- not have allowguest=no in sip.conf, everybody out there may use your -- public context without authentication. In that case you want to -- double check which services you offer to the world. -- include = {"demo"}; }; ["local"] = { ["_NXXXXXX"] = outgoing_local; }; } hints = { demo = { [1000] = "SIP/1000"; [1001] = "SIP/1001"; }; default = { ["1234"] = "SIP/1234"; }; }
bsd-3-clause
mrichards42/xword
scripts/libs/pl/app.lua
8
5787
--- Application support functions. -- See @{01-introduction.md.Application_Support|the Guide} -- -- Dependencies: `pl.utils`, `pl.path` -- @module pl.app local io,package,require = _G.io, _G.package, _G.require local utils = require 'pl.utils' local path = require 'pl.path' local app = {} local function check_script_name () if _G.arg == nil then error('no command line args available\nWas this run from a main script?') end return _G.arg[0] end --- add the current script's path to the Lua module path. -- Applies to both the source and the binary module paths. It makes it easy for -- the main file of a multi-file program to access its modules in the same directory. -- `base` allows these modules to be put in a specified subdirectory, to allow for -- cleaner deployment and resolve potential conflicts between a script name and its -- library directory. -- @param base optional base directory. -- @return the current script's path with a trailing slash function app.require_here (base) local p = path.dirname(check_script_name()) if not path.isabs(p) then p = path.join(path.currentdir(),p) end if p:sub(-1,-1) ~= path.sep then p = p..path.sep end if base then p = p..base..path.sep end local so_ext = path.is_windows and 'dll' or 'so' local lsep = package.path:find '^;' and '' or ';' local csep = package.cpath:find '^;' and '' or ';' package.path = ('%s?.lua;%s?%sinit.lua%s%s'):format(p,p,path.sep,lsep,package.path) package.cpath = ('%s?.%s%s%s'):format(p,so_ext,csep,package.cpath) return p end --- return a suitable path for files private to this application. -- These will look like '~/.SNAME/file', with '~' as with expanduser and -- SNAME is the name of the script without .lua extension. -- @param file a filename (w/out path) -- @return a full pathname, or nil -- @return 'cannot create' error function app.appfile (file) local sname = path.basename(check_script_name()) local name,ext = path.splitext(sname) local dir = path.join(path.expanduser('~'),'.'..name) if not path.isdir(dir) then local ret = path.mkdir(dir) if not ret then return utils.raise ('cannot create '..dir) end end return path.join(dir,file) end --- return string indicating operating system. -- @return 'Windows','OSX' or whatever uname returns (e.g. 'Linux') function app.platform() if path.is_windows then return 'Windows' else local f = io.popen('uname') local res = f:read() if res == 'Darwin' then res = 'OSX' end f:close() return res end end --- return the full command-line used to invoke this script. -- Any extra flags occupy slots, so that `lua -lpl` gives us `{[-2]='lua',[-1]='-lpl'}` -- @return command-line -- @return name of Lua program used function app.lua () local args = _G.arg or error "not in a main program" local imin = 0 for i in pairs(args) do if i < imin then imin = i end end local cmd, append = {}, table.insert for i = imin,-1 do local a = args[i] if a:match '%s' then a = '"'..a..'"' end append(cmd,a) end return table.concat(cmd,' '),args[imin] end --- parse command-line arguments into flags and parameters. -- Understands GNU-style command-line flags; short (`-f`) and long (`--flag`). -- These may be given a value with either '=' or ':' (`-k:2`,`--alpha=3.2`,`-n2`); -- note that a number value can be given without a space. -- Multiple short args can be combined like so: ( `-abcd`). -- @param args an array of strings (default is the global `arg`) -- @param flags_with_values any flags that take values, e.g. <code>{out=true}</code> -- @return a table of flags (flag=value pairs) -- @return an array of parameters -- @raise if args is nil, then the global `args` must be available! function app.parse_args (args,flags_with_values) if not args then args = _G.arg if not args then error "Not in a main program: 'arg' not found" end end flags_with_values = flags_with_values or {} local _args = {} local flags = {} local i = 1 while i <= #args do local a = args[i] local v = a:match('^-(.+)') local is_long if v then -- we have a flag if v:find '^-' then is_long = true v = v:sub(2) end if flags_with_values[v] then if i == #_args or args[i+1]:find '^-' then return utils.raise ("no value for '"..v.."'") end flags[v] = args[i+1] i = i + 1 else -- a value can also be indicated with = local var,val = utils.splitv (v,'=') var = var or v val = val or true if not is_long then if #var > 1 then if var:find '.%d+' then -- short flag, number value val = var:sub(2) var = var:sub(1,1) else -- multiple short flags for i = 1,#var do flags[var:sub(i,i)] = true end val = nil -- prevents use of var as a flag below end else -- single short flag (can have value, defaults to true) val = val or true end end if val then flags[var] = val end end else _args[#_args+1] = a end i = i + 1 end return flags,_args end return app
gpl-3.0
froggatt/openwrt-luci
applications/luci-asterisk/luasrc/asterisk/cc_idd.lua
92
7735
--[[ LuCI - Asterisk - International Direct Dialing Prefixes and Country Codes Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module "luci.asterisk.cc_idd" CC_IDD = { -- Country, CC, IDD { "Afghanistan", "93", "00" }, { "Albania", "355", "00" }, { "Algeria", "213", "00" }, { "American Samoa", "684", "00" }, { "Andorra", "376", "00" }, { "Angola", "244", "00" }, { "Anguilla", "264", "011" }, { "Antarctica", "672", "" }, { "Antigua", "268", "011" }, { "Argentina", "54", "00" }, { "Armenia", "374", "00" }, { "Aruba", "297", "00" }, { "Ascension Island", "247", "00" }, { "Australia", "61", "0011" }, { "Austria", "43", "00" }, { "Azberbaijan", "994", "00" }, { "Bahamas", "242", "011" }, { "Bahrain", "973", "00" }, { "Bangladesh", "880", "00" }, { "Barbados", "246", "011" }, { "Barbuda", "268", "011" }, { "Belarus", "375", "810" }, { "Belgium", "32", "00" }, { "Belize", "501", "00" }, { "Benin", "229", "00" }, { "Bermuda", "441", "011" }, { "Bhutan", "975", "00" }, { "Bolivia", "591", "00" }, { "Bosnia", "387", "00" }, { "Botswana", "267", "00" }, { "Brazil", "55", "00" }, { "British Virgin Islands", "284", "011" }, { "Brunei", "673", "00" }, { "Bulgaria", "359", "00" }, { "Burkina Faso", "226", "00" }, { "Burma (Myanmar)", "95", "00" }, { "Burundi", "257", "00" }, { "Cambodia", "855", "001" }, { "Cameroon", "237", "00" }, { "Canada", "1", "011" }, { "Cape Verde Islands", "238", "0" }, { "Cayman Islands", "345", "011" }, { "Central African Rep.", "236", "00" }, { "Chad", "235", "15" }, { "Chile", "56", "00" }, { "China", "86", "00" }, { "Christmas Island", "61", "0011" }, { "Cocos Islands", "61", "0011" }, { "Colombia", "57", "00" }, { "Comoros", "269", "00" }, { "Congo", "242", "00" }, { "Congo, Dem. Rep. of", "243", "00" }, { "Cook Islands", "682", "00" }, { "Costa Rica", "506", "00" }, { "Croatia", "385", "00" }, { "Cuba", "53", "119" }, { "Cyprus", "357", "00" }, { "Czech Republic", "420", "00" }, { "Denmark", "45", "00" }, { "Diego Garcia", "246", "00" }, { "Djibouti", "253", "00" }, { "Dominica", "767", "011" }, { "Dominican Rep.", "809", "011" }, { "Ecuador", "593", "00" }, { "Egypt", "20", "00" }, { "El Salvador", "503", "00" }, { "Equatorial Guinea", "240", "00" }, { "Eritrea", "291", "00" }, { "Estonia", "372", "00" }, { "Ethiopia", "251", "00" }, { "Faeroe Islands", "298", "00" }, { "Falkland Islands", "500", "00" }, { "Fiji Islands", "679", "00" }, { "Finland", "358", "00" }, { "France", "33", "00" }, { "French Antilles", "596", "00" }, { "French Guiana", "594", "00" }, { "French Polynesia", "689", "00" }, { "Gabon", "241", "00" }, { "Gambia", "220", "00" }, { "Georgia", "995", "810" }, { "Germany", "49", "00" }, { "Ghana", "233", "00" }, { "Gibraltar", "350", "00" }, { "Greece", "30", "00" }, { "Greenland", "299", "00" }, { "Grenada", "473", "011" }, { "Guadeloupe", "590", "00" }, { "Guam", "671", "011" }, { "Guantanamo Bay", "5399", "00" }, { "Guatemala", "502", "00" }, { "Guinea", "224", "00" }, { "Guinea Bissau", "245", "00" }, { "Guyana", "592", "001" }, { "Haiti", "509", "00" }, { "Honduras", "504", "00" }, { "Hong Kong", "852", "001" }, { "Hungary", "36", "00" }, { "Iceland", "354", "00" }, { "India", "91", "00" }, { "Indonesia", "62", { "001", "008" } }, { "Iran", "98", "00" }, { "Iraq", "964", "00" }, { "Ireland", "353", "00" }, { "Israel", "972", "00" }, { "Italy", "39", "00" }, { "Ivory Coast", "225", "00" }, { "Jamaica", "876", "011" }, { "Japan", "81", "001" }, { "Jordan", "962", "00" }, { "Kazakhstan", "7", "810" }, { "Kenya", "254", "000" }, { "Kiribati", "686", "00" }, { "Korea, North", "850", "00" }, { "Korea, South", "82", "001" }, { "Kuwait", "965", "00" }, { "Kyrgyzstan", "996", "00" }, { "Laos", "856", "00" }, { "Latvia", "371", "00" }, { "Lebanon", "961", "00" }, { "Lesotho", "266", "00" }, { "Liberia", "231", "00" }, { "Libya", "218", "00" }, { "Liechtenstein", "423", "00" }, { "Lithuania", "370", "00" }, { "Luxembourg", "352", "00" }, { "Macau", "853", "00" }, { "Macedonia", "389", "00" }, { "Madagascar", "261", "00" }, { "Malawi", "265", "00" }, { "Malaysia", "60", "00" }, { "Maldives", "960", "00" }, { "Mali", "223", "00" }, { "Malta", "356", "00" }, { "Mariana Islands", "670", "011" }, { "Marshall Islands", "692", "011" }, { "Martinique", "596", "00" }, { "Mauritania", "222", "00" }, { "Mauritius", "230", "00" }, { "Mayotte Islands", "269", "00" }, { "Mexico", "52", "00" }, { "Micronesia", "691", "011" }, { "Midway Island", "808", "011" }, { "Moldova", "373", "00" }, { "Monaco", "377", "00" }, { "Mongolia", "976", "001" }, { "Montserrat", "664", "011" }, { "Morocco", "212", "00" }, { "Mozambique", "258", "00" }, { "Myanmar (Burma)", "95", "00" }, { "Namibia", "264", "00" }, { "Nauru", "674", "00" }, { "Nepal", "977", "00" }, { "Netherlands", "31", "00" }, { "Netherlands Antilles", "599", "00" }, { "Nevis", "869", "011" }, { "New Caledonia", "687", "00" }, { "New Zealand", "64", "00" }, { "Nicaragua", "505", "00" }, { "Niger", "227", "00" }, { "Nigeria", "234", "009" }, { "Niue", "683", "00" }, { "Norfolk Island", "672", "00" }, { "Norway", "47", "00" }, { "Oman", "968", "00" }, { "Pakistan", "92", "00" }, { "Palau", "680", "011" }, { "Palestine", "970", "00" }, { "Panama", "507", "00" }, { "Papua New Guinea", "675", "05" }, { "Paraguay", "595", "002" }, { "Peru", "51", "00" }, { "Philippines", "63", "00" }, { "Poland", "48", "00" }, { "Portugal", "351", "00" }, { "Puerto Rico", { "787", "939" }, "011" }, { "Qatar", "974", "00" }, { "Reunion Island", "262", "00" }, { "Romania", "40", "00" }, { "Russia", "7", "810" }, { "Rwanda", "250", "00" }, { "St. Helena", "290", "00" }, { "St. Kitts", "869", "011" }, { "St. Lucia", "758", "011" }, { "St. Perre & Miquelon", "508", "00" }, { "St. Vincent", "784", "011" }, { "San Marino", "378", "00" }, { "Sao Tome & Principe", "239", "00" }, { "Saudi Arabia", "966", "00" }, { "Senegal", "221", "00" }, { "Serbia", "381", "99" }, { "Seychelles", "248", "00" }, { "Sierra Leone", "232", "00" }, { "Singapore", "65", "001" }, { "Slovakia", "421", "00" }, { "Slovenia", "386", "00" }, { "Solomon Islands", "677", "00" }, { "Somalia", "252", "00" }, { "South Africa", "27", "09" }, { "Spain", "34", "00" }, { "Sri Lanka", "94", "00" }, { "Sudan", "249", "00" }, { "Suriname", "597", "00" }, { "Swaziland", "268", "00" }, { "Sweden", "46", "00" }, { "Switzerland", "41", "00" }, { "Syria", "963", "00" }, { "Taiwan", "886", "002" }, { "Tajikistan", "992", "810" }, { "Tanzania", "255", "00" }, { "Thailand", "66", "001" }, { "Togo", "228", "00" }, { "Tonga", "676", "00" }, { "Trinidad & Tobago", "868", "011" }, { "Tunisia", "216", "00" }, { "Turkey", "90", "00" }, { "Turkmenistan", "993", "810" }, { "Turks & Caicos", "649", "011" }, { "Tuvalu", "688", "00" }, { "Uganda", "256", "000" }, { "Ukraine", "380", "810" }, { "United Arab Emirates", "971", "00" }, { "United Kingdom", "44", "00" }, { "Uruguay", "598", "00" }, { "USA", "1", "011" }, { "US Virgin Islands", "340", "011" }, { "Uzbekistan", "998", "810" }, { "Vanuatu", "678", "00" }, { "Vatican City", "39", "00" }, { "Venezuela", "58", "00" }, { "Vietnam", "84", "00" }, { "Wake Island", "808", "00" }, { "Wallis & Futuna", "681", "19" }, { "Western Samoa", "685", "00" }, { "Yemen", "967", "00" }, { "Yugoslavia", "381", "99" }, { "Zambia", "260", "00" }, { "Zimbabwe", "263", "00" } }
apache-2.0
rigeirani/emc1
plugins/admin.lua
60
6680
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 { usage = { "pm: Send Pm To Priavate Chat.", "block: Block User [id].", "unblock: Unblock User [id].", "markread on: Reads Messages agancy Bot.", "markread off: Don't Reads Messages agancy Bot.", "setbotphoto: Set New Photo For Bot Account.", "contactlist: Send A List Of Bot Contacts.", "dialoglist: Send A Dialog Of Chat.", "delcontact: Delete Contact.", "import: Added Bot In Group With Link.", }, patterns = { "^(pm) (%d+) (.*)$", "^(import) (.*)$", "^(unblock) (%d+)$", "^(block) (%d+)$", "^(markread) (on)$", "^(markread) (off)$", "^(setbotphoto)$", "%[(photo)%]", "^(contactlist)$", "^(dialoglist)$", "^(delcontact) (%d+)$", "^(whois) (%d+)$" }, run = run, }
gpl-2.0
sinavafa/test5
plugins/admin.lua
60
6680
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 { usage = { "pm: Send Pm To Priavate Chat.", "block: Block User [id].", "unblock: Unblock User [id].", "markread on: Reads Messages agancy Bot.", "markread off: Don't Reads Messages agancy Bot.", "setbotphoto: Set New Photo For Bot Account.", "contactlist: Send A List Of Bot Contacts.", "dialoglist: Send A Dialog Of Chat.", "delcontact: Delete Contact.", "import: Added Bot In Group With Link.", }, patterns = { "^(pm) (%d+) (.*)$", "^(import) (.*)$", "^(unblock) (%d+)$", "^(block) (%d+)$", "^(markread) (on)$", "^(markread) (off)$", "^(setbotphoto)$", "%[(photo)%]", "^(contactlist)$", "^(dialoglist)$", "^(delcontact) (%d+)$", "^(whois) (%d+)$" }, run = run, }
gpl-2.0
LuaDist2/lua-nucleo
test/cases/0330-tpretty.lua
2
9053
-------------------------------------------------------------------------------- -- 0330-tpretty.lua: tests for pretty-printer -- This file is a part of lua-nucleo library -- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license) -------------------------------------------------------------------------------- local pairs = pairs local make_suite = assert(loadfile('test/test-lib/init/strict.lua'))(...) declare 'jit' local jit = jit local ensure, ensure_equals, ensure_strequals, ensure_tequals, ensure_fails_with_substring = import 'lua-nucleo/ensure.lua' { 'ensure', 'ensure_equals', 'ensure_strequals', 'ensure_tequals', 'ensure_fails_with_substring' } local tpretty_ex, tpretty, tpretty_ordered, tpretty_exports = import 'lua-nucleo/tpretty.lua' { 'tpretty_ex', 'tpretty', 'tpretty_ordered' } -------------------------------------------------------------------------------- local test = make_suite("tpretty", tpretty_exports) -------------------------------------------------------------------------------- test:group "tpretty_ex" -------------------------------------------------------------------------------- test "tpretty_ex-not-a-table" (function() ensure_strequals( "t is not a table", tpretty_ex(pairs, 42), '42' ) end) test "tpretty_ex-simple-table" (function() ensure_strequals( "t is a simple table", tpretty_ex(pairs, {"DEPLOY_MACHINE"}), '{ "DEPLOY_MACHINE" }' ) end) test "tpretty_ex-without-optional-params" (function() local s1 = [[ { result = { stats = { { garden = { views_total = "INTEGER"; unique_visits_total = "INTEGER"; id = "GARDEN_ID"; views_yesterday = "INTEGER"; unique_visits_yesterday = "INTEGER"; }; }; }; }; events = { }; }]] ensure_strequals( [[default values for optional params is 80 and " "]], tpretty_ex(pairs, ensure("parse", (loadstring("return " .. s1))())), tpretty_ex( pairs, ensure("parse", loadstring("return " .. s1))(), " ", 80 ) ) end) -- Based on actual bug scenario test "tpretty_ex-bug-concat-nil-minimal" (function() local s1 = [[ { stats = { }; }]] local s2 = [[{ }]] ensure_strequals( "first result matches expected", ensure( "render first", tpretty_ex( pairs, ensure("parse", loadstring("return " .. s1))(), " ", 80 ) ), s1 ) -- [[ ensure_strequals( "second result matches expected", ensure( "render second", tpretty_ex( pairs, ensure("parse", loadstring("return " .. s2))(), " ", 80 ) ), s2 )--]] end) -- Based on actual bug scenario test "tpretty_ex-bug-concat-nil-full" (function() -- TODO: systematic solution required -- https://github.com/lua-nucleo/lua-nucleo/issues/18 local s1 if jit ~= nil then s1 = [[ { result = { stats = { garden = { views_total = "INTEGER"; unique_visits_yesterday = "INTEGER"; id = "GARDEN_ID"; views_yesterday = "INTEGER"; unique_visits_total = "INTEGER"; }; }; }; events = { }; }]] else s1 = [[ { result = { stats = { garden = { views_total = "INTEGER"; unique_visits_total = "INTEGER"; id = "GARDEN_ID"; views_yesterday = "INTEGER"; unique_visits_yesterday = "INTEGER"; }; }; }; events = { }; }]] end local s2 = [[ { result = { money_real = "MONEY_REAL"; money_referral = "MONEY_REFERRAL"; money_game = "MONEY_GAME"; }; events = { }; }]] ensure_strequals( "first result matches expected", ensure( "render first", tpretty_ex( pairs, ensure("parse", loadstring("return " .. s1))(), " ", 80 ) ), s1 ) ensure_strequals( "second result matches expected", ensure( "render second", tpretty_ex( pairs, ensure("parse", loadstring("return " .. s2))(), " ", 80 ) ), s2 ) end) -- Test based on real bug scenario -- #2304 and #2317 -- -- In case of failure. `this_field_was_empty' miss in output test "tpretty_ex-fieldname-bug" (function () local cache_file_contents = [[ { projects = { ["lua-nucleo"] = { clusters = { ["localhost-an"] = { machines = { localhost = { this_field_was_empty = true }; }; }; }; }; }; }]] ensure_strequals( "second result matches expected", ensure( "render second", tpretty_ex( pairs, ensure("parse error", loadstring("return " .. cache_file_contents))(), " ", 80 ) ), cache_file_contents ) end) -------------------------------------------------------------------------------- -- Test based on real bug scenario -- #3067 -- -- Extra = is rendered as a table separator instead of ; -- and after opening {. test "tpretty_ex-wrong-table-list-separator-bug" (function () local data = [[ { { { { }; }; { { }; }; }; }]] ensure_strequals( "second result matches expected", ensure( "render second", tpretty_ex( pairs, ensure("data string loads", loadstring("return " .. data))(), " ", 80 ) ), data ) end) test "tpretty_ex-wrong-key-indent-bug" (function () local data = [[ { { }; foo = { { }; }; }]] ensure_strequals( "second result matches expected", ensure( "render second", tpretty_ex( pairs, ensure("data string loads", loadstring("return " .. data))(), " ", 80 ) ), data ) end) -------------------------------------------------------------------------------- -- Test based on real bug scenario -- #3836 test "tpretty_ex-serialize-inf-bug" (function () local table_with_inf = "{ 1/0, -1/0, 0/0 }" ensure_strequals( "second result matches expected", ensure( "render second", tpretty_ex( pairs, ensure("parse error", loadstring("return " .. table_with_inf))(), " ", 80 ) ), table_with_inf ) end) -------------------------------------------------------------------------------- test "tpretty_ex-custom-iterator" (function() local t = { 1, 2, 3 } local iterator_invocations_counter = 0 local custom_iterator = function(table) local iterator_function = function(table, pos) iterator_invocations_counter = iterator_invocations_counter + 1 pos = pos or 0 if pos < #table then pos = pos + 1 return pos, table[pos] end end return iterator_function, table, nil end tpretty_ex(custom_iterator, t) ensure_equals( "iterator invocations counter must match expected", iterator_invocations_counter, 4 ) end) -------------------------------------------------------------------------------- test:group "tpretty" -------------------------------------------------------------------------------- test "tpretty-simple" (function() local input = [[ { 1; 2; 3; a = { b = { c = { }; }; }; }]] ensure_strequals( "result matches expected", ensure( "render is OK", tpretty(ensure("parse error", loadstring("return " .. input))()) ), input ) end) -------------------------------------------------------------------------------- test:group "tpretty_ordered" -------------------------------------------------------------------------------- test "tpretty-ordered" (function() local input = [[ { result = { stats2 = { a3333333333333 = "INTEGER"; a2222222222222 = "INTEGER"; a1111111111111 = "GARDEN_ID"; }; stats1 = { bbbbbbbbbbbbbb = "INTEGER"; cccccccccccccc = "INTEGER"; aaaaaaaaaaaaaa = "GARDEN_ID"; }; }; }]] local expected = [[ { result = { stats1 = { aaaaaaaaaaaaaa = "GARDEN_ID"; bbbbbbbbbbbbbb = "INTEGER"; cccccccccccccc = "INTEGER"; }; stats2 = { a1111111111111 = "GARDEN_ID"; a2222222222222 = "INTEGER"; a3333333333333 = "INTEGER"; }; }; }]] ensure_strequals( "first result matches expected", ensure( "render first", tpretty_ordered( ensure("parse", loadstring("return " .. input))(), " ", 80 ) ), expected ) end)
mit
froggatt/openwrt-luci
modules/niu/luasrc/controller/niu/traffic.lua
49
1218
--[[ LuCI - Lua Development Framework Copyright 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local require = require module "luci.controller.niu.traffic" function index() local toniu = {on_success_to={"niu"}} local e = entry({"niu", "traffic"}, alias("niu"), "Network Traffic", 30) e.niu_dbtemplate = "niu/traffic" e.niu_dbtasks = true e.niu_dbicon = "icons32/preferences-system-network.png" if fs.access("/etc/config/firewall") then entry({"niu", "traffic", "portfw"}, cbi("niu/traffic/portfw", toniu), "Manage Port Forwarding", 1) end if fs.access("/etc/config/qos") then entry({"niu", "traffic", "qos"}, cbi("niu/traffic/qos", toniu), "Manage Prioritization (QoS)", 2) end entry({"niu", "traffic", "routes"}, cbi("niu/traffic/routes", toniu), "Manage Traffic Routing", 30) entry({"niu", "traffic", "conntrack"}, call("cnntrck"), "Display Local Network Activity", 50) end function cnntrck() require "luci.template".render("niu/traffic/conntrack") end
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/general/events/damp-cave.lua
1
3489
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org -- Find a random spot local x, y = game.state:findEventGrid(level) if not x then return false end local id = "damp-cave-"..game.turn local changer = function(id) local npcs = mod.class.NPC:loadList{"/data/general/npcs/thieve.lua"} local objects = mod.class.Object:loadList("/data/general/objects/objects.lua") local terrains = mod.class.Grid:loadList("/data/general/grids/cave.lua") terrains.CAVE_LADDER_UP_WILDERNESS.change_level_shift_back = true terrains.CAVE_LADDER_UP_WILDERNESS.change_zone_auto_stairs = true local zone = mod.class.Zone.new(id, { name = "Damp Cave", level_range = {game.zone:level_adjust_level(game.level, game.zone, "actor"), game.zone:level_adjust_level(game.level, game.zone, "actor")}, level_scheme = "player", max_level = 1, actor_adjust_level = function(zone, level, e) return zone.base_level + e:getRankLevelAdjust() + level.level-1 + rng.range(-1,2) end, width = 20, height = 20, ambient_music = "Swashing the buck.ogg", reload_lists = false, persistent = "zone", min_material_level = game.zone.min_material_level, max_material_level = game.zone.max_material_level, generator = { map = { class = "engine.generator.map.Cavern", zoom = 4, min_floor = 120, floor = "CAVEFLOOR", wall = "CAVEWALL", up = "CAVE_LADDER_UP_WILDERNESS", door = "CAVEFLOOR", }, actor = { class = "mod.class.generator.actor.Random", nb_npc = {14, 14}, guardian = {random_elite={life_rating=function(v) return v * 1.5 + 4 end, nb_rares=3}}, }, object = { class = "engine.generator.object.Random", filters = {{type="gem"}}, nb_object = {6, 9}, }, trap = { class = "engine.generator.trap.Random", nb_trap = {6, 9}, }, }, -- levels = { [1] = { generator = { map = { up = "CAVEFLOOR", }, }, }, }, npc_list = npcs, grid_list = terrains, object_list = objects, trap_list = mod.class.Trap:loadList("/data/general/traps/natural_forest.lua"), }) return zone end local g = game.level.map(x, y, engine.Map.TERRAIN):cloneFull() g.name = "damp cave" g.display='>' g.color_r=0 g.color_g=0 g.color_b=255 g.notice = true g.change_level=1 g.change_zone=id g.glow=true g:removeAllMOs() if engine.Map.tiles.nicer_tiles then g.add_displays = g.add_displays or {} g.add_displays[#g.add_displays+1] = mod.class.Grid.new{image="terrain/crystal_ladder_down.png", z=5} end g:altered() g:initGlow() g.real_change = changer g.change_level_check = function(self) game:changeLevel(1, self.real_change(self.change_zone), {temporary_zone_shift=true, direct_switch=true}) self.change_level_check = nil self.real_change = nil return true end game.zone:addEntity(game.level, g, "terrain", x, y) return true
gpl-3.0
electricpandafishstudios/Spoon
game/modules/Spoon/data/general/npcs/Virus.lua
1
1319
-- ToME - Tales of Middle-Earth -- Copyright (C) 2009 - 2015 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Talents = require("engine.interface.ActorTalents") newEntity{ define_as = "BASE_NPC_Virus", type = "humanoid", subtype = "virus", display = "v", color=colors.WHITE, desc = [[Ugly and green!]], ai = "dumb_talented_simple", ai_state = { talent_in=3, }, stats = {}, drops = { amt = 1, U = 22.5, C = 7.5, A = 7.5, G= 7.5}, combat_armor = 0, } newEntity{ base = "BASE_NPC_Virus", name = "virus", color=colors.GREEN, level_range = {1, 4}, exp_worth = 0, rarity = 4, max_life = resolvers.rngavg(1,3), combat = { dam=1 }, }
gpl-3.0
BooM-amour/king
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
kobyov/dst_brook
scripts/prefabs/swordcane.lua
1
3826
local assets = { Asset("ANIM", "anim/swordcane.zip"), Asset("ANIM", "anim/swap_swordcane.zip"), Asset("ATLAS", "images/inventoryimages/swordcane.xml"), Asset("IMAGE", "images/inventoryimages/swordcane.tex"), } local function ontakefuel(inst) inst.SoundEmitter:PlaySound("dontstarve/common/nightmareAddFuel") end local function onequip(inst, owner) if owner:HasTag("deadbones") then owner.AnimState:OverrideSymbol("swap_object", "swap_swordcane", "swap_swordcane") owner.AnimState:Show("ARM_carry") owner.AnimState:Hide("ARM_normal") else inst:DoTaskInTime(0, function() if owner and owner.components and owner.components.inventory then owner.components.inventory:GiveItem(inst) if owner.components.talker then owner.components.talker:Say("Cold enough to sear flesh") end end end) end end local function onunequip(inst, owner) owner.AnimState:Hide("ARM_carry") owner.AnimState:Show("ARM_normal") end local function onattack_hum(inst, attacker, target, skipsanity) if inst.components.fueled:IsEmpty() then inst.components.weapon:SetDamage(TUNING.CANE_DAMAGE) else inst.components.weapon:SetDamage(TUNING.SPEAR_DAMAGE) if attacker and attacker.components.sanity and not skipsanity then attacker.components.sanity:DoDelta(-TUNING.SANITY_SUPERTINY) end if target.components.burnable then if target.components.burnable:IsBurning() then target.components.burnable:Extinguish() elseif target.components.burnable:IsSmoldering() then target.components.burnable:SmotherSmolder() end end if target.components.freezable then target.components.freezable:AddColdness(1) target.components.freezable:SpawnShatterFX() end inst.components.fueled:DoDelta(-1) end if target.components.sleeper and target.components.sleeper:IsAsleep() then target.components.sleeper:WakeUp() end if target.components.combat then target.components.combat:SuggestTarget(attacker) end if target.sg and not target.sg:HasStateTag("frozen") then target:PushEvent("attacked", {attacker = attacker, damage = 0}) end end local function fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.entity:AddNetwork() MakeInventoryPhysics(inst) inst.AnimState:SetBank("swordcane") inst.AnimState:SetBuild("swordcane") inst.AnimState:PlayAnimation("idle") inst:AddTag("sharp") inst.entity:SetPristine() if not TheWorld.ismastersim then return inst end inst:AddComponent("weapon") inst.components.weapon:SetDamage(TUNING.CANE_DAMAGE) inst.components.weapon:SetOnAttack(onattack_hum) inst:AddComponent("inspectable") inst:AddComponent("inventoryitem") inst.components.inventoryitem.imagename = "swordcane" inst.components.inventoryitem.atlasname = "images/inventoryimages/swordcane.xml" inst:AddComponent("equippable") inst.components.equippable:SetOnEquip(onequip) inst.components.equippable:SetOnUnequip(onunequip) inst.components.equippable.walkspeedmult = TUNING.CANE_SPEED_MULT inst:AddComponent("fueled") inst.components.fueled.fueltype = FUELTYPE.NIGHTMARE inst.components.fueled:InitializeFuelLevel(100) inst.components.fueled.accepting = true inst.components.fueled.ontakefuelfn = ontakefuel MakeHauntableLaunch(inst) return inst end return Prefab("common/inventory/swordcane", fn, assets)
unlicense
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/general/objects/egos/robe.lua
1
17375
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Stats = require "engine.interface.ActorStats" local Talents = require "engine.interface.ActorTalents" local DamageType = require "engine.DamageType" --load("/data/general/objects/egos/charged-defensive.lua") --load("/data/general/objects/egos/charged-utility.lua") -- Resists and saves newEntity{ power_source = {nature=true}, name = " of fire (#RESIST#)", suffix=true, instant_resolve="last", keywords = {fire=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.FIRE] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.FIRE] = math.floor(ego.wielder.inc_damage[engine.DamageType.FIRE]*1.5) end), } newEntity{ power_source = {nature=true}, name = " of frost (#RESIST#)", suffix=true, instant_resolve="last", keywords = {frost=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.COLD] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.COLD] = math.floor(ego.wielder.inc_damage[engine.DamageType.COLD]*1.5) end), } newEntity{ power_source = {nature=true}, name = " of nature (#RESIST#)", suffix=true, instant_resolve="last", keywords = {nature=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.NATURE] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.NATURE] = math.floor(ego.wielder.inc_damage[engine.DamageType.NATURE]*1.5) end), } newEntity{ power_source = {nature=true}, name = " of lightning (#RESIST#)", suffix=true, instant_resolve="last", keywords = {lightning=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.LIGHTNING] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.LIGHTNING] = math.floor(ego.wielder.inc_damage[engine.DamageType.LIGHTNING]*1.5) end), } newEntity{ power_source = {arcane=true}, name = " of light (#RESIST#)", suffix=true, instant_resolve="last", keywords = {light=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.LIGHT] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.LIGHT] = math.floor(ego.wielder.inc_damage[engine.DamageType.LIGHT]*1.5) end), } newEntity{ power_source = {arcane=true}, name = " of darkness (#RESIST#)", suffix=true, instant_resolve="last", keywords = {darkness=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.DARKNESS] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.DARKNESS] = math.floor(ego.wielder.inc_damage[engine.DamageType.DARKNESS]*1.5) end), } newEntity{ power_source = {nature=true}, name = " of corrosion (#RESIST#)", suffix=true, instant_resolve="last", keywords = {corrosion=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.ACID] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.ACID] = math.floor(ego.wielder.inc_damage[engine.DamageType.ACID]*1.5) end), } -- rare resists newEntity{ power_source = {arcane=true}, name = " of blight (#RESIST#)", suffix=true, instant_resolve="last", keywords = {blight=true}, level_range = {1, 50}, rarity = 9, cost = 2, wielder = { inc_damage = { [DamageType.BLIGHT] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.BLIGHT] = (ego.wielder.inc_damage[engine.DamageType.BLIGHT]) end), } newEntity{ power_source = {nature=true}, name = " of the mountain (#RESIST#)", suffix=true, instant_resolve="last", keywords = {mountain=true}, level_range = {1, 50}, rarity = 12, cost = 2, wielder = { inc_damage = { [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.PHYSICAL] = ego.wielder.inc_damage[engine.DamageType.PHYSICAL] end), } newEntity{ power_source = {psionic=true}, name = " of the mind (#RESIST#)", suffix=true, instant_resolve="last", keywords = {mind=true}, level_range = {1, 50}, rarity = 9, cost = 2, wielder = { inc_damage = { [DamageType.MIND] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.MIND] = ego.wielder.inc_damage[engine.DamageType.MIND] end), } newEntity{ power_source = {arcane=true}, name = " of time (#RESIST#)", suffix=true, instant_resolve="last", keywords = {time=true}, level_range = {1, 50}, rarity = 12, cost = 2, wielder = { inc_damage = { [DamageType.TEMPORAL] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e, ego) ego.wielder.resists[engine.DamageType.TEMPORAL] = ego.wielder.inc_damage[engine.DamageType.TEMPORAL] end), } -- Arcane Damage doesn't get resist too so we give it +mana instead newEntity{ power_source = {arcane=true}, name = "shimmering ", prefix=true, instant_resolve=true, keywords = {shimmering=true}, level_range = {1, 50}, rarity = 12, cost = 6, wielder = { inc_damage = { [DamageType.ARCANE] = resolvers.mbonus_material(10, 10) }, max_mana = resolvers.mbonus_material(100, 10), }, } -- Saving Throws (robes give good saves) newEntity{ power_source = {technique=true}, name = " of protection", suffix=true, instant_resolve=true, keywords = {prot=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { combat_armor = resolvers.mbonus_material(3, 2), combat_def = resolvers.mbonus_material(3, 2), combat_physresist = resolvers.mbonus_material(15, 15), }, } newEntity{ power_source = {psionic=true}, name = "dreamer's ", prefix=true, instant_resolve=true, keywords = {dreamer=true}, level_range = {20, 50}, greater_ego = 1, rarity = 30, cost = 60, wielder = { lucid_dreamer=1, sleep=1, resists={ [DamageType.MIND] = resolvers.mbonus_material(20, 10), [DamageType.DARKNESS] = resolvers.mbonus_material(20, 10), }, combat_physresist = resolvers.mbonus_material(10, 10), combat_spellresist = resolvers.mbonus_material(10, 10), combat_mentalresist = resolvers.mbonus_material(20, 20), }, } newEntity{ power_source = {arcane=true}, name = "dispeller's ", prefix=true, instant_resolve=true, keywords = {dispeller=true}, level_range = {30, 50}, greater_ego = 1, rarity = 30, cost = 60, wielder = { resists={ [DamageType.FIRE] = resolvers.mbonus_material(6, 6), [DamageType.COLD] = resolvers.mbonus_material(6, 6), [DamageType.BLIGHT] = resolvers.mbonus_material(6, 6), [DamageType.LIGHTNING] = resolvers.mbonus_material(6, 6), [DamageType.DARKNESS] = resolvers.mbonus_material(6, 6), [DamageType.LIGHT] = resolvers.mbonus_material(6, 6), }, combat_physresist = resolvers.mbonus_material(10, 10), combat_mentalresist = resolvers.mbonus_material(10, 10), combat_spellresist = resolvers.mbonus_material(20, 20), }, } -- The rest newEntity{ power_source = {arcane=true}, name = " of alchemy", suffix=true, instant_resolve=true, keywords = {alchemy=true}, level_range = {20, 50}, greater_ego = 1, rarity = 20, cost = 40, wielder = { inc_damage = { [DamageType.ACID] = resolvers.mbonus_material(10, 5), [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 5), [DamageType.FIRE] = resolvers.mbonus_material(10, 5), [DamageType.COLD] = resolvers.mbonus_material(10, 5), }, resists={ [DamageType.ACID] = resolvers.mbonus_material(10, 10), [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 10), [DamageType.FIRE] = resolvers.mbonus_material(10, 10), [DamageType.COLD] = resolvers.mbonus_material(10, 10), }, talent_cd_reduction = { [Talents.T_REFIT_GOLEM] = resolvers.mbonus_material(4, 2), } }, } newEntity{ power_source = {arcane=true}, name = "spellwoven ", prefix=true, instant_resolve=true, keywords = {spellwoven=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { combat_spellresist = resolvers.mbonus_material(15, 15), combat_spellpower = resolvers.mbonus_material(4, 2), combat_spellcrit = resolvers.mbonus_material(4, 2), }, } newEntity{ power_source = {arcane=true}, name = " of Linaniil", suffix=true, instant_resolve=true, keywords = {Linaniil=true}, level_range = {35, 50}, greater_ego = 1, rarity = 25, cost = 60, wielder = { combat_spellpower = resolvers.mbonus_material(15, 15), combat_spellcrit = resolvers.mbonus_material(10, 5), max_mana = resolvers.mbonus_material(60, 40), mana_regen = resolvers.mbonus_material(30, 10, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {arcane=true}, name = " of Angolwen", suffix=true, instant_resolve=true, keywords = {Angolwen=true}, level_range = {35, 50}, greater_ego = 1, rarity = 20, cost = 60, wielder = { inc_stats = { [Stats.STAT_MAG] = resolvers.mbonus_material(4, 2), [Stats.STAT_WIL] = resolvers.mbonus_material(4, 2), }, combat_spellpower = resolvers.mbonus_material(15, 5), spellsurge_on_crit = resolvers.mbonus_material(5, 2), silence_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {arcane=true}, name = "stargazer's ", prefix=true, instant_resolve=true, keywords = {stargazer=true}, level_range = {30, 50}, greater_ego = 1, rarity = 15, cost = 30, wielder = { inc_stats = { [Stats.STAT_CUN] = resolvers.mbonus_material(5, 1), }, inc_damage = { [DamageType.LIGHT] = resolvers.mbonus_material(15, 5), [DamageType.DARKNESS] = resolvers.mbonus_material(15, 5), }, combat_spellpower = resolvers.mbonus_material(5, 5), combat_spellcrit = resolvers.mbonus_material(5, 5), }, } newEntity{ power_source = {arcane=true}, name = "ancient ", prefix=true, instant_resolve=true, keywords = {ancient=true}, level_range = {30, 50}, greater_ego = 1, rarity = 15, cost = 40, wielder = { inc_stats = { [Stats.STAT_MAG] = resolvers.mbonus_material(9, 1), }, inc_damage = { [DamageType.TEMPORAL] = resolvers.mbonus_material(15, 5), [DamageType.PHYSICAL] = resolvers.mbonus_material(15, 5), }, resists_pen = { [DamageType.TEMPORAL] = resolvers.mbonus_material(10, 5), [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 5), }, paradox_reduce_anomalies = resolvers.mbonus_material(8, 8), }, } newEntity{ power_source = {arcane=true}, name = " of power", suffix=true, instant_resolve=true, keywords = {power=true}, level_range = {20, 50}, greater_ego = 1, rarity = 18, cost = 15, wielder = { inc_damage = { all = resolvers.mbonus_material(15, 5), }, combat_spellpower = resolvers.mbonus_material(10, 10), }, } newEntity{ power_source = {arcane=true}, name = "sunsealed ", prefix=true, instant_resolve=true, keywords = {sunseal=true}, level_range = {40, 50}, greater_ego = 1, rarity = 30, cost = 80, wielder = { resists={ [DamageType.LIGHT] = resolvers.mbonus_material(10, 5), [DamageType.DARKNESS] = resolvers.mbonus_material(10, 5), }, inc_damage = { [DamageType.LIGHT] = resolvers.mbonus_material(15, 5), }, inc_stats = { [Stats.STAT_MAG] = resolvers.mbonus_material(7, 3), }, combat_armor = resolvers.mbonus_material(5, 3), combat_def = resolvers.mbonus_material(5, 3), lite = resolvers.mbonus_material(3,1), max_life=resolvers.mbonus_material(40, 30), }, } newEntity{ power_source = {nature=true}, name = " of life", suffix=true, instant_resolve=true, keywords = {life=true}, level_range = {20, 50}, greater_ego = 1, rarity = 20, cost = 60, wielder = { max_life=resolvers.mbonus_material(60, 40), life_regen = resolvers.mbonus_material(45, 15, function(e, v) v=v/10 return 0, v end), healing_factor = resolvers.mbonus_material(20, 10, function(e, v) v=v/100 return 0, v end), resists={ [DamageType.BLIGHT] = resolvers.mbonus_material(15, 5), }, }, } newEntity{ power_source = {antimagic=true}, name = "slimy ", prefix=true, instant_resolve=true, keywords = {slimy=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { on_melee_hit={ [DamageType.ITEM_NATURE_SLOW] = resolvers.mbonus_material(7, 3), [DamageType.ITEM_ANTIMAGIC_MANABURN] = resolvers.mbonus_material(7, 3) }, }, } newEntity{ power_source = {nature=true}, name = "stormwoven ", prefix=true, instant_resolve=true, keywords = {storm=true}, level_range = {30, 50}, greater_ego = 1, rarity = 16, cost = 50, wielder = { resists={ [DamageType.COLD] = resolvers.mbonus_material(10, 5), [DamageType.LIGHTNING] = resolvers.mbonus_material(10, 5), }, inc_stats = { [Stats.STAT_STR] = resolvers.mbonus_material(4, 4), [Stats.STAT_MAG] = resolvers.mbonus_material(4, 4), [Stats.STAT_WIL] = resolvers.mbonus_material(4, 4), }, inc_damage = { [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 5), [DamageType.COLD] = resolvers.mbonus_material(15, 5), [DamageType.LIGHTNING] = resolvers.mbonus_material(15, 5), }, }, } newEntity{ power_source = {nature=true}, name = "verdant ", prefix=true, instant_resolve=true, keywords = {verdant=true}, level_range = {20, 50}, greater_ego = 1, rarity = 15, cost = 30, wielder = { inc_stats = { [Stats.STAT_CON] = resolvers.mbonus_material(8, 2), }, inc_damage = { [DamageType.NATURE] = resolvers.mbonus_material(15, 5), }, disease_immune = resolvers.mbonus_material(30, 20, function(e, v) return 0, v/100 end), poison_immune = resolvers.mbonus_material(30, 20, function(e, v) return 0, v/100 end), }, } newEntity{ power_source = {psionic=true}, name = "mindwoven ", prefix=true, instant_resolve=true, keywords = {mindwoven=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { combat_mentalresist = resolvers.mbonus_material(15, 15), combat_mindpower = resolvers.mbonus_material(4, 2), combat_mindcrit = resolvers.mbonus_material(4, 2), }, } newEntity{ power_source = {psionic=true}, name = "tormentor's ", prefix=true, instant_resolve=true, keywords = {tormentor=true}, level_range = {30, 50}, greater_ego = 1, rarity = 30, cost = 60, wielder = { inc_stats = { [Stats.STAT_CUN] = resolvers.mbonus_material(9, 1), }, combat_critical_power = resolvers.mbonus_material(10, 10), hate_on_crit = resolvers.mbonus_material(3, 2), psi_on_crit = resolvers.mbonus_material(4, 1), }, } newEntity{ power_source = {psionic=true}, name = "focusing ", prefix=true, instant_resolve=true, keywords = {focus=true}, level_range = {15, 50}, rarity = 10, cost = 10, wielder = { inc_stats = { [Stats.STAT_MAG] = resolvers.mbonus_material(4, 4), [Stats.STAT_WIL] = resolvers.mbonus_material(4, 4), }, mana_regen = resolvers.mbonus_material(30, 10, function(e, v) v=v/100 return 0, v end), psi_regen = resolvers.mbonus_material(30, 10, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {psionic=true}, name = "fearwoven ", prefix=true, instant_resolve=true, keywords = {fearwoven=true}, level_range = {40, 50}, greater_ego = 1, rarity = 40, cost = 80, wielder = { inc_damage = { [DamageType.PHYSICAL] = resolvers.mbonus_material(15, 5), [DamageType.DARKNESS] = resolvers.mbonus_material(15, 5), }, resists_pen = { [DamageType.PHYSICAL] = resolvers.mbonus_material(15, 5), [DamageType.DARKNESS] = resolvers.mbonus_material(15, 5), }, max_hate = resolvers.mbonus_material(10, 5), combat_mindpower = resolvers.mbonus_material(5, 5), combat_mindcrit = resolvers.mbonus_material(4, 1), }, } newEntity{ power_source = {psionic=true}, name = "psion's ", prefix=true, instant_resolve=true, keywords = {psion=true}, level_range = {40, 50}, greater_ego = 1, rarity = 40, cost = 80, wielder = { inc_damage = { [DamageType.MIND] = resolvers.mbonus_material(15, 5), }, resists_pen = { [DamageType.MIND] = resolvers.mbonus_material(15, 5), }, max_psi = resolvers.mbonus_material(30, 10), psi_regen = resolvers.mbonus_material(70, 30, function(e, v) v=v/100 return 0, v end), combat_mindpower = resolvers.mbonus_material(5, 5), combat_mindcrit = resolvers.mbonus_material(4, 1), }, }
gpl-3.0
saraedum/luci-packages-old
applications/luci-asterisk/luasrc/model/cbi/asterisk/dialzones.lua
91
3529
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: trunks.lua 4025 2009-01-11 23:37:21Z jow $ ]]-- local ast = require("luci.asterisk") local uci = require("luci.model.uci").cursor() --[[ Dialzone overview table ]] if not arg[1] then zonemap = Map("asterisk", "Dial Zones", [[ Dial zones hold patterns of dialed numbers to match. Each zone has one or more trunks assigned. If the first trunk is congested, Asterisk will try to use the next available connection. If all trunks fail, then the following zones in the parent dialplan are tried. ]]) local zones, znames = ast.dialzone.zones() zonetbl = zonemap:section(Table, zones, "Zone Overview") zonetbl.sectionhead = "Zone" zonetbl.addremove = true zonetbl.anonymous = false zonetbl.extedit = luci.dispatcher.build_url( "admin", "asterisk", "dialplans", "zones", "%s" ) function zonetbl.cfgsections(self) return znames end function zonetbl.parse(self) for k, v in pairs(self.map:formvaluetable( luci.cbi.REMOVE_PREFIX .. self.config ) or {}) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end uci:delete("asterisk", k) uci:save("asterisk") self.data[k] = nil for i = 1,#znames do if znames[i] == k then table.remove(znames, i) break end end end Table.parse(self) end zonetbl:option(DummyValue, "description", "Description") zonetbl:option(DummyValue, "addprefix") match = zonetbl:option(DummyValue, "matches") function match.cfgvalue(self, s) return table.concat(zones[s].matches, ", ") end trunks = zonetbl:option(DummyValue, "trunk") trunks.template = "asterisk/cbi/cell" function trunks.cfgvalue(self, s) return ast.tools.hyperlinks(zones[s].trunks) end return zonemap --[[ Zone edit form ]] else zoneedit = Map("asterisk", "Edit Dialzone") entry = zoneedit:section(NamedSection, arg[1]) entry.title = "Zone %q" % arg[1]; back = entry:option(DummyValue, "_overview", "Back to dialzone overview") back.value = "" back.titleref = luci.dispatcher.build_url( "admin", "asterisk", "dialplans", "zones" ) desc = entry:option(Value, "description", "Description") function desc.cfgvalue(self, s, ...) return Value.cfgvalue(self, s, ...) or s end trunks = entry:option(MultiValue, "uses", "Used trunks") trunks.widget = "checkbox" uci:foreach("asterisk", "sip", function(s) if s.provider == "yes" then trunks:value( "SIP/%s" % s['.name'], "SIP/%s (%s)" %{ s['.name'], s.host or 'n/a' } ) end end) match = entry:option(DynamicList, "match", "Number matches") intl = entry:option(DynamicList, "international", "Intl. prefix matches (optional)") aprefix = entry:option(Value, "addprefix", "Add prefix to dial out (optional)") ccode = entry:option(Value, "countrycode", "Effective countrycode (optional)") lzone = entry:option(ListValue, "localzone", "Dialzone for local numbers") lzone:value("", "no special treatment of local numbers") for _, z in ipairs(ast.dialzone.zones()) do lzone:value(z.name, "%q (%s)" %{ z.name, z.description }) end --for _, v in ipairs(find_outgoing_contexts(zoneedit.uci)) do -- lzone:value(unpack(v)) --end lprefix = entry:option(Value, "localprefix", "Prefix for local calls (optional)") return zoneedit end
apache-2.0
musenshen/SandBoxLua
src/framework/cc/ui/UIScrollView.lua
9
26436
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -------------------------------- -- @module UIScrollView --[[-- quick 滚动控件 ]] local UIScrollView = class("UIScrollView", function() return cc.ClippingRegionNode:create() end) UIScrollView.BG_ZORDER = -100 UIScrollView.TOUCH_ZORDER = -99 UIScrollView.DIRECTION_BOTH = 0 UIScrollView.DIRECTION_VERTICAL = 1 UIScrollView.DIRECTION_HORIZONTAL = 2 -- start -- -------------------------------- -- 滚动控件的构建函数 -- @function [parent=#UIScrollView] new -- @param table params 参数表 --[[-- 滚动控件的构建函数 可用参数有: - direction 滚动控件的滚动方向,默认为垂直与水平方向都可滚动 - viewRect 列表控件的显示区域 - scrollbarImgH 水平方向的滚动条 - scrollbarImgV 垂直方向的滚动条 - bgColor 背景色,nil表示无背景色 - bgStartColor 渐变背景开始色,nil表示无背景色 - bgEndColor 渐变背景结束色,nil表示无背景色 - bg 背景图 - bgScale9 背景图是否可缩放 - capInsets 缩放区域 ]] -- end -- function UIScrollView:ctor(params) self.bBounce = true self.nShakeVal = 5 self.direction = UIScrollView.DIRECTION_BOTH self.layoutPadding = {left = 0, right = 0, top = 0, bottom = 0} self.speed = {x = 0, y = 0} if not params then return end if params.viewRect then self:setViewRect(params.viewRect) end if params.direction then self:setDirection(params.direction) end if params.scrollbarImgH then self.sbH = display.newScale9Sprite(params.scrollbarImgH, 100):addTo(self) end if params.scrollbarImgV then self.sbV = display.newScale9Sprite(params.scrollbarImgV, 100):addTo(self) end -- touchOnContent true:当触摸在滚动内容上才有效 false:当触摸在显示区域(viewRect_)就有效 -- 当内容小于显示区域时,两者就有区别了 self:setTouchType(params.touchOnContent or true) self:addBgColorIf(params) self:addBgGradientColorIf(params) self:addBgIf(params) self:addNodeEventListener(cc.NODE_ENTER_FRAME_EVENT, function(...) self:update_(...) end) self:scheduleUpdate() end function UIScrollView:addBgColorIf(params) if not params.bgColor then return end -- display.newColorLayer(params.bgColor) cc.LayerColor:create(params.bgColor) :size(params.viewRect.width, params.viewRect.height) :pos(params.viewRect.x, params.viewRect.y) :addTo(self, UIScrollView.BG_ZORDER) :setTouchEnabled(false) end function UIScrollView:addBgGradientColorIf(params) if not params.bgStartColor or not params.bgEndColor then return end local layer = cc.LayerGradient:create(params.bgStartColor, params.bgEndColor) :size(params.viewRect.width, params.viewRect.height) :pos(params.viewRect.x, params.viewRect.y) :addTo(self, UIScrollView.BG_ZORDER) :setTouchEnabled(false) layer:setVector(params.bgVector) end function UIScrollView:addBgIf(params) if not params.bg then return end local bg if params.bgScale9 then bg = display.newScale9Sprite(params.bg, nil, nil, nil, params.capInsets) else bg = display.newSprite(params.bg) end bg:size(params.viewRect.width, params.viewRect.height) :pos(params.viewRect.x + params.viewRect.width/2, params.viewRect.y + params.viewRect.height/2) :addTo(self, UIScrollView.BG_ZORDER) :setTouchEnabled(false) end function UIScrollView:setViewRect(rect) self:setClippingRegion(rect) self.viewRect_ = rect self.viewRectIsNodeSpace = false return self end -- start -- -------------------------------- -- 得到滚动控件的显示区域 -- @function [parent=#UIScrollView] getViewRect -- @return Rect#Rect -- end -- function UIScrollView:getViewRect() return self.viewRect_ end -- start -- -------------------------------- -- 设置布局四周的空白 -- @function [parent=#UIScrollView] setLayoutPadding -- @param number top 上边的空白 -- @param number right 右边的空白 -- @param number bottom 下边的空白 -- @param number left 左边的空白 -- @return UIScrollView#UIScrollView -- end -- function UIScrollView:setLayoutPadding(top, right, bottom, left) if not self.layoutPadding then self.layoutPadding = {} end self.layoutPadding.top = top self.layoutPadding.right = right self.layoutPadding.bottom = bottom self.layoutPadding.left = left return self end function UIScrollView:setActualRect(rect) self.actualRect_ = rect end -- start -- -------------------------------- -- 设置滚动方向 -- @function [parent=#UIScrollView] setDirection -- @param number dir 滚动方向 -- @return UIScrollView#UIScrollView -- end -- function UIScrollView:setDirection(dir) self.direction = dir return self end -- start -- -------------------------------- -- 获取滚动方向 -- @function [parent=#UIScrollView] getDirection -- @return number#number -- end -- function UIScrollView:getDirection() return self.direction end -- start -- -------------------------------- -- 设置滚动控件是否开启回弹功能 -- @function [parent=#UIScrollView] setBounceable -- @param boolean bBounceable 是否开启回弹 -- @return UIScrollView#UIScrollView -- end -- function UIScrollView:setBounceable(bBounceable) self.bBounce = bBounceable return self end -- start -- -------------------------------- -- 设置触摸响应方式 -- true:当触摸在滚动内容上才有效 false:当触摸在显示区域(viewRect_)就有效 -- 内容大于显示区域时,两者无差别 -- 内容小于显示区域时,true:在空白区域触摸无效,false:在空白区域触摸也可滚动内容 -- @function [parent=#UIScrollView] setTouchType -- @param boolean bTouchOnContent 是否触控到滚动内容上才有效 -- @return UIScrollView#UIScrollView -- end -- function UIScrollView:setTouchType(bTouchOnContent) self.touchOnContent = bTouchOnContent return self end --[[-- 重置位置,主要用在纵向滚动时 ]] function UIScrollView:resetPosition() if UIScrollView.DIRECTION_VERTICAL ~= self.direction then return end local x, y = self.scrollNode:getPosition() local bound = self.scrollNode:getCascadeBoundingBox() local disY = self.viewRect_.y + self.viewRect_.height - bound.y - bound.height y = y + disY self.scrollNode:setPosition(x, y) end -- start -- -------------------------------- -- 判断一个node是否在滚动控件的显示区域中 -- @function [parent=#UIScrollView] isItemInViewRect -- @param node item scrollView中的项 -- @return boolean#boolean -- end -- function UIScrollView:isItemInViewRect(item) if "userdata" ~= type(item) then item = nil end if not item then print("UIScrollView - isItemInViewRect item is not right") return end local bound = item:getCascadeBoundingBox() -- local point = cc.p(bound.x, bound.y) -- local parent = item -- while true do -- parent = parent:getParent() -- point = parent:convertToNodeSpace(point) -- if parent == self.scrollNode then -- break -- end -- end -- bound.x = point.x -- bound.y = point.y return cc.rectIntersectsRect(self:getViewRectInWorldSpace(), bound) end -- start -- -------------------------------- -- 设置scrollview可触摸 -- @function [parent=#UIScrollView] setTouchEnabled -- @param boolean bEnabled 是否开启触摸 -- @return UIScrollView#UIScrollView -- end -- function UIScrollView:setTouchEnabled(bEnabled) if not self.scrollNode then return end self.scrollNode:setTouchEnabled(bEnabled) return self end -- start -- -------------------------------- -- 将要显示的node加到scrollview中,scrollView只支持滚动一个node -- @function [parent=#UIScrollView] addScrollNode -- @param node node 要显示的项 -- @return UIScrollView#UIScrollView -- end -- function UIScrollView:addScrollNode(node) self:addChild(node) self.scrollNode = node if not self.viewRect_ then self.viewRect_ = self.scrollNode:getCascadeBoundingBox() self:setViewRect(self.viewRect_) end node:setTouchSwallowEnabled(false) node:setTouchEnabled(true) -- node:addNodeEventListener(cc.NODE_TOUCH_EVENT, function (event) -- return self:onTouch_(event) -- end) node:addNodeEventListener(cc.NODE_TOUCH_CAPTURE_EVENT, function (event) return self:onTouchCapture_(event) end) self:addTouchNode() return self end -- start -- -------------------------------- -- 返回scrollView中的滚动node -- @function [parent=#UIScrollView] getScrollNode -- @return node#node 滚动node -- end -- function UIScrollView:getScrollNode() return self.scrollNode end -- start -- -------------------------------- -- 注册滚动控件的监听函数 -- @function [parent=#UIScrollView] onScroll -- @param function listener 监听函数 -- @return UIScrollView#UIScrollView -- end -- function UIScrollView:onScroll(listener) self.scrollListener_ = listener return self end -- private function UIScrollView:calcLayoutPadding() local boundBox = self.scrollNode:getCascadeBoundingBox() self.layoutPadding.left = boundBox.x - self.actualRect_.x self.layoutPadding.right = self.actualRect_.x + self.actualRect_.width - boundBox.x - boundBox.width self.layoutPadding.top = boundBox.y - self.actualRect_.y self.layoutPadding.bottom = self.actualRect_.y + self.actualRect_.height - boundBox.y - boundBox.height end function UIScrollView:update_(dt) self:drawScrollBar() end function UIScrollView:onTouchCapture_(event) if ("began" == event.name or "moved" == event.name or "ended" == event.name) and self:isTouchInViewRect(event) then return true else return false end end function UIScrollView:onTouch_(event) if "began" == event.name and not self:isTouchInViewRect(event) then printInfo("UIScrollView - touch didn't in viewRect") return false end if "began" == event.name and self.touchOnContent then local cascadeBound = self.scrollNode:getCascadeBoundingBox() if not cc.rectContainsPoint(cascadeBound, cc.p(event.x, event.y)) then return false end end if "began" == event.name then self.prevX_ = event.x self.prevY_ = event.y self.bDrag_ = false local x,y = self.scrollNode:getPosition() self.position_ = {x = x, y = y} transition.stopTarget(self.scrollNode) self:callListener_{name = "began", x = event.x, y = event.y} self:enableScrollBar() -- self:changeViewRectToNodeSpaceIf() self.scaleToWorldSpace_ = self:scaleToParent_() return true elseif "moved" == event.name then if self:isShake(event) then return end self.bDrag_ = true self.speed.x = event.x - event.prevX self.speed.y = event.y - event.prevY if self.direction == UIScrollView.DIRECTION_VERTICAL then self.speed.x = 0 elseif self.direction == UIScrollView.DIRECTION_HORIZONTAL then self.speed.y = 0 else -- do nothing end self:scrollBy(self.speed.x, self.speed.y) self:callListener_{name = "moved", x = event.x, y = event.y} elseif "ended" == event.name then if self.bDrag_ then self.bDrag_ = false self:scrollAuto() self:callListener_{name = "ended", x = event.x, y = event.y} self:disableScrollBar() else self:callListener_{name = "clicked", x = event.x, y = event.y} end end end function UIScrollView:isTouchInViewRect(event) -- dump(self.viewRect_, "viewRect:") local viewRect = self:convertToWorldSpace(cc.p(self.viewRect_.x, self.viewRect_.y)) viewRect.width = self.viewRect_.width viewRect.height = self.viewRect_.height -- dump(viewRect, "new viewRect:") return cc.rectContainsPoint(viewRect, cc.p(event.x, event.y)) end function UIScrollView:isTouchInScrollNode(event) local cascadeBound = self:getScrollNodeRect() return cc.rectContainsPoint(cascadeBound, cc.p(event.x, event.y)) end function UIScrollView:scrollTo(p, y) local x_, y_ if "table" == type(p) then x_ = p.x or 0 y_ = p.y or 0 else x_ = p y_ = y end self.position_ = cc.p(x_, y_) self.scrollNode:setPosition(self.position_) end function UIScrollView:moveXY(orgX, orgY, speedX, speedY) if self.bBounce then -- bounce enable return orgX + speedX, orgY + speedY end local cascadeBound = self:getScrollNodeRect() local viewRect = self:getViewRectInWorldSpace() local x, y = orgX, orgY local disX, disY if speedX > 0 then if cascadeBound.x < viewRect.x then disX = viewRect.x - cascadeBound.x disX = disX / self.scaleToWorldSpace_.x x = orgX + math.min(disX, speedX) end else if cascadeBound.x + cascadeBound.width > viewRect.x + viewRect.width then disX = viewRect.x + viewRect.width - cascadeBound.x - cascadeBound.width disX = disX / self.scaleToWorldSpace_.x x = orgX + math.max(disX, speedX) end end if speedY > 0 then if cascadeBound.y < viewRect.y then disY = viewRect.y - cascadeBound.y disY = disY / self.scaleToWorldSpace_.y y = orgY + math.min(disY, speedY) end else if cascadeBound.y + cascadeBound.height > viewRect.y + viewRect.height then disY = viewRect.y + viewRect.height - cascadeBound.y - cascadeBound.height disY = disY / self.scaleToWorldSpace_.y y = orgY + math.max(disY, speedY) end end return x, y end function UIScrollView:scrollBy(x, y) self.position_.x, self.position_.y = self:moveXY(self.position_.x, self.position_.y, x, y) -- self.position_.x = self.position_.x + x -- self.position_.y = self.position_.y + y self.scrollNode:setPosition(self.position_) if self.actualRect_ then self.actualRect_.x = self.actualRect_.x + x self.actualRect_.y = self.actualRect_.y + y end end function UIScrollView:scrollAuto() if self:twiningScroll() then return end self:elasticScroll() end -- fast drag function UIScrollView:twiningScroll() if self:isSideShow() then -- printInfo("UIScrollView - side is show, so elastic scroll") return false end if math.abs(self.speed.x) < 10 and math.abs(self.speed.y) < 10 then -- printInfo("#DEBUG, UIScrollView - isn't twinking scroll:" -- .. self.speed.x .. " " .. self.speed.y) return false end local disX, disY = self:moveXY(0, 0, self.speed.x*6, self.speed.y*6) transition.moveBy(self.scrollNode, {x = disX, y = disY, time = 0.3, easing = "sineOut", onComplete = function() self:elasticScroll() end}) end function UIScrollView:elasticScroll() local cascadeBound = self:getScrollNodeRect() local disX, disY = 0, 0 local viewRect = self:getViewRectInWorldSpace() -- dump(cascadeBound, "UIScrollView - cascBoundingBox:") -- dump(viewRect, "UIScrollView - viewRect:") if cascadeBound.width < viewRect.width then disX = viewRect.x - cascadeBound.x else if cascadeBound.x > viewRect.x then disX = viewRect.x - cascadeBound.x elseif cascadeBound.x + cascadeBound.width < viewRect.x + viewRect.width then disX = viewRect.x + viewRect.width - cascadeBound.x - cascadeBound.width end end if cascadeBound.height < viewRect.height then disY = viewRect.y + viewRect.height - cascadeBound.y - cascadeBound.height else if cascadeBound.y > viewRect.y then disY = viewRect.y - cascadeBound.y elseif cascadeBound.y + cascadeBound.height < viewRect.y + viewRect.height then disY = viewRect.y + viewRect.height - cascadeBound.y - cascadeBound.height end end if 0 == disX and 0 == disY then return end transition.moveBy(self.scrollNode, {x = disX, y = disY, time = 0.3, easing = "backout", onComplete = function() self:callListener_{name = "scrollEnd"} end}) end function UIScrollView:getScrollNodeRect() local bound = self.scrollNode:getCascadeBoundingBox() -- bound.x = bound.x - self.layoutPadding.left -- bound.y = bound.y - self.layoutPadding.bottom -- bound.width = bound.width + self.layoutPadding.left + self.layoutPadding.right -- bound.height = bound.height + self.layoutPadding.bottom + self.layoutPadding.top return bound end function UIScrollView:getViewRectInWorldSpace() local rect = self:convertToWorldSpace( cc.p(self.viewRect_.x, self.viewRect_.y)) rect.width = self.viewRect_.width rect.height = self.viewRect_.height return rect end -- 是否显示到边缘 function UIScrollView:isSideShow() local bound = self.scrollNode:getCascadeBoundingBox() if bound.x > self.viewRect_.x or bound.y > self.viewRect_.y or bound.x + bound.width < self.viewRect_.x + self.viewRect_.width or bound.y + bound.height < self.viewRect_.y + self.viewRect_.height then return true end return false end function UIScrollView:callListener_(event) if not self.scrollListener_ then return end event.scrollView = self self.scrollListener_(event) end function UIScrollView:enableScrollBar() local bound = self.scrollNode:getCascadeBoundingBox() if self.sbV then self.sbV:setVisible(false) transition.stopTarget(self.sbV) self.sbV:setOpacity(128) local size = self.sbV:getContentSize() if self.viewRect_.height < bound.height then local barH = self.viewRect_.height*self.viewRect_.height/bound.height if barH < size.width then -- 保证bar不会太小 barH = size.width end self.sbV:setContentSize(size.width, barH) self.sbV:setPosition( self.viewRect_.x + self.viewRect_.width - size.width/2, self.viewRect_.y + barH/2) end end if self.sbH then self.sbH:setVisible(false) transition.stopTarget(self.sbH) self.sbH:setOpacity(128) local size = self.sbH:getContentSize() if self.viewRect_.width < bound.width then local barW = self.viewRect_.width*self.viewRect_.width/bound.width if barW < size.height then barW = size.height end self.sbH:setContentSize(barW, size.height) self.sbH:setPosition(self.viewRect_.x + barW/2, self.viewRect_.y + size.height/2) end end end function UIScrollView:disableScrollBar() if self.sbV then transition.fadeOut(self.sbV, {time = 0.3, onComplete = function() self.sbV:setOpacity(128) self.sbV:setVisible(false) end}) end if self.sbH then transition.fadeOut(self.sbH, {time = 1.5, onComplete = function() self.sbH:setOpacity(128) self.sbH:setVisible(false) end}) end end function UIScrollView:drawScrollBar() if not self.bDrag_ then return end if not self.sbV and not self.sbH then return end local bound = self.scrollNode:getCascadeBoundingBox() if self.sbV then self.sbV:setVisible(true) local size = self.sbV:getContentSize() local posY = (self.viewRect_.y - bound.y)*(self.viewRect_.height - size.height)/(bound.height - self.viewRect_.height) + self.viewRect_.y + size.height/2 local x, y = self.sbV:getPosition() self.sbV:setPosition(x, posY) end if self.sbH then self.sbH:setVisible(true) local size = self.sbH:getContentSize() local posX = (self.viewRect_.x - bound.x)*(self.viewRect_.width - size.width)/(bound.width - self.viewRect_.width) + self.viewRect_.x + size.width/2 local x, y = self.sbH:getPosition() self.sbH:setPosition(posX, y) end end function UIScrollView:addScrollBarIf() if not self.sb then self.sb = cc.DrawNode:create():addTo(self) end drawNode = cc.DrawNode:create() drawNode:drawSegment(points[1], points[2], radius, borderColor) end function UIScrollView:changeViewRectToNodeSpaceIf() if self.viewRectIsNodeSpace then return end -- local nodePoint = self:convertToNodeSpace(cc.p(self.viewRect_.x, self.viewRect_.y)) local posX, posY = self:getPosition() local ws = self:convertToWorldSpace(cc.p(posX, posY)) self.viewRect_.x = self.viewRect_.x + ws.x self.viewRect_.y = self.viewRect_.y + ws.y self.viewRectIsNodeSpace = true end function UIScrollView:isShake(event) if math.abs(event.x - self.prevX_) < self.nShakeVal and math.abs(event.y - self.prevY_) < self.nShakeVal then return true end end function UIScrollView:scaleToParent_() local parent local node = self local scale = {x = 1, y = 1} while true do scale.x = scale.x * node:getScaleX() scale.y = scale.y * node:getScaleY() parent = node:getParent() if not parent then break end node = parent end return scale end --[[-- 加一个大小为viewRect的touch node ]] function UIScrollView:addTouchNode() local node if self.touchNode_ then node = self.touchNode_ else node = display.newNode() self.touchNode_ = node node:setLocalZOrder(UIScrollView.TOUCH_ZORDER) node:setTouchSwallowEnabled(true) node:setTouchEnabled(true) node:addNodeEventListener(cc.NODE_TOUCH_EVENT, function (event) return self:onTouch_(event) end) self:addChild(node) end node:setContentSize(self.viewRect_.width, self.viewRect_.height) node:setPosition(self.viewRect_.x, self.viewRect_.y) return self end --[[-- scrollView的填充方法,可以自动把一个table里的node有序的填充到scrollview里。 ~~~ lua --填充100个相同大小的图片。 local view = cc.ui.UIScrollView.new( {viewRect = cc.rect(100,100, 400, 400), direction = 2}) self:addChild(view); local t = {} for i = 1, 100 do local png = cc.ui.UIImage.new("GreenButton.png") t[#t+1] = png cc.ui.UILabel.new({text = i, size = 24, color = cc.c3b(100,100,100)}) :align(display.CENTER, png:getContentSize().width/2, png:getContentSize().height/2) :addTo(png) end view:fill(t, {itemSize = (t[#t]):getContentSize()}) ~~~ 注意:参数nodes 是table结构,且一定要是{node1,node2,node3,...}不能是{a=node1,b=node2,c=node3,...} @param nodes node集 @param params 参见fill函数头定义。 -- params = extend({ ... ]] function UIScrollView:fill(nodes,params) --参数的继承用法,把param2的参数增加覆盖到param1中。 local extend = function(param1,param2) if not param2 then return param1 end for k , v in pairs(param2) do param1[k] = param2[k] end return param1 end local params = extend({ --自动间距 autoGap = true, --宽间距 widthGap = 0, --高间距 heightGap = 0, --自动行列 autoTable = true, --行数目 rowCount = 3, --列数目 cellCount = 3, --填充项大小 itemSize = cc.size(50 , 50) },params) if #nodes == 0 then return nil end --基本坐标工具方法 local SIZE = function(node) return node:getContentSize() end local W = function(node) return node:getContentSize().width end local H = function(node) return node:getContentSize().height end local S_SIZE = function(node , w , h) return node:setContentSize(cc.size(w , h)) end local S_XY = function(node , x , y) node:setPosition(x,y) end local AX = function(node) return node:getAnchorPoint().x end local AY = function(node) return node:getAnchorPoint().y end --创建一个容器node local innerContainer = display.newNode() --初始容器大小为视图大小 S_SIZE(innerContainer , self:getViewRect().width , self:getViewRect().height) self:addScrollNode(innerContainer) S_XY(innerContainer , self.viewRect_.x , self.viewRect_.y) --如果是纵向布局 if self.direction == cc.ui.UIScrollView.DIRECTION_VERTICAL then --自动布局 if params.autoTable then params.cellCount = math.floor(self.viewRect_.width / params.itemSize.width) end --自动间隔 if params.autoGap then params.widthGap = (self.viewRect_.width - (params.cellCount * params.itemSize.width)) / (params.cellCount + 1) params.heightGap = params.widthGap end --填充量 params.rowCount = math.ceil(#nodes / params.cellCount) --避免动态尺寸少于设计尺寸 local v_h = (params.itemSize.height + params.heightGap) * params.rowCount + params.heightGap if v_h < self.viewRect_.height then v_h = self.viewRect_.height end S_SIZE(innerContainer , self.viewRect_.width , v_h) for i = 1 , #nodes do local n = nodes[i] local x = 0.0 local y = 0.0 --不管描点如何,总是有标准居中方式设置坐标。 x = params.widthGap + math.floor((i - 1) % params.cellCount) * (params.widthGap + params.itemSize.width) y = H(innerContainer) - (math.floor((i - 1) / params.cellCount) + 1) * (params.heightGap + params.itemSize.height) x = x + W(n) * AX(n) y = y + H(n) * AY(n) S_XY(n , x ,y) n:addTo(innerContainer) end --如果是横向布局 -- elseif(self.direction==cc.ui.UIScrollView.DIRECTION_HORIZONTAL) then else if params.autoTable then params.rowCount = math.floor(self.viewRect_.height / params.itemSize.height) end if params.autoGap then params.heightGap = (self.viewRect_.height - (params.rowCount * params.itemSize.height)) / (params.rowCount + 1) params.widthGap = params.heightGap end params.cellCount = math.ceil(#nodes / params.rowCount) --避免动态尺寸少于设计尺寸。 local v_w = (params.itemSize.width + params.widthGap) * params.cellCount + params.widthGap if v_w < self.viewRect_.width then v_h = self.viewRect_.width end S_SIZE(innerContainer , v_w ,self.viewRect_.height) for i = 1, #nodes do local n = nodes[i] local x = 0.0 local y = 0.0 --不管描点如何,总是有标准居中方式设置坐标。 x = params.widthGap + math.floor((i - 1) / params.rowCount ) * (params.widthGap + params.itemSize.width) y = H(innerContainer) - (math.floor((i - 1) % params.rowCount ) +1 ) * (params.heightGap + params.itemSize.height) x = x + W(n) * AX(n) y = y + H(n) * AY(n) S_XY(n , x , y) n:addTo(innerContainer) end end end return UIScrollView
mit
enginix/lua-websockets
spec/client_ev_spec.lua
3
9088
local websocket = require'websocket' local socket = require'socket' local client = require'websocket.client' local ev = require'ev' local frame = require'websocket.frame' local port = os.getenv('LUAWS_WSTEST_PORT') or 11000 local req_ws = ' (requires external websocket server @port '..port..')' local url = 'ws://127.0.0.1:'..port setloop('ev') describe( 'The client (ev) module', function() local wsc it( 'exposes the correct interface', function() assert.is_table(client) assert.is_function(client.ev) end) it( 'can be constructed', function() wsc = client.ev() end) it( 'can connect and calls on_open'..req_ws, function(done) settimeout(10) wsc:on_open(async(function(ws) assert.is_equal(ws,wsc) done() end)) wsc:connect(url,'echo-protocol') end) it( 'calls on_error if already connected'..req_ws, function(done) settimeout(3) wsc:on_error(async(function(ws,err) assert.is_equal(ws,wsc) assert.is_equal(err,'wrong state') ws:on_error() ws:on_close(function() done() end) ws:close() end)) wsc:connect(url,'echo-protocol') end) it( 'calls on_error on bad protocol'..req_ws, function(done) settimeout(3) wsc:on_error(async(function(ws,err) assert.is_equal(ws,wsc) assert.is_equal(err,'bad protocol') ws:on_error() done() end)) wsc:connect('ws2://127.0.0.1:'..port,'echo-protocol') end) it( 'can parse HTTP request header byte per byte', function(done) local resp = { 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-Websocket-Accept: e2123as3', 'Sec-Websocket-Protocol: chat', '\r\n' } resp = table.concat(resp,'\r\n') assert.is_equal(resp:sub(#resp-3),'\r\n\r\n') local socket = require'socket' local http_serv = socket.bind('*',port + 20) local http_con wsc:on_error(async(function(ws,err) assert.is_equal(err,'accept failed') ws:close() http_serv:close() http_con:close() done() end)) wsc:on_open(async(function() assert.is_nil('should never happen') end)) wsc:connect('ws://127.0.0.1:'..(port+20),'chat') http_con = http_serv:accept() local i = 1 ev.Timer.new(function(loop,timer) if i <= #resp then local byte = resp:sub(i,i) http_con:send(byte) i = i + 1 else timer:stop(loop) end end,0.0001,0.0001):start(ev.Loop.default) end) it( 'properly calls on_error if socket error on handshake occurs', function(done) local resp = { 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', } resp = table.concat(resp,'\r\n') local socket = require'socket' local http_serv = socket.bind('*',port + 20) local http_con wsc:on_error(async(function(ws,err) assert.is_equal(err,'accept failed') ws:on_close(function() done() end) ws:close() http_serv:close() http_con:close() end)) wsc:on_open(async(function() assert.is_nil('should never happen') end)) wsc:connect('ws://127.0.0.1:'..(port+20),'chat') http_con = http_serv:accept() local i = 1 ev.Timer.new(function(loop,timer) if i <= #resp then local byte = resp:sub(i,i) http_con:send(byte) i = i + 1 else timer:stop(loop) http_con:close() end end,0.0001,0.0001):start(ev.Loop.default) end) it( 'can open and close immediatly (in CLOSING state)'..req_ws, function(done) wsc:on_error(async(function(_,err) assert.is_nil(err or 'should never happen') end)) wsc:on_close(function(_,was_clean,code) assert.is_false(was_clean) assert.is_equal(code,1006) done() end) wsc:connect(url,'echo-protocol') wsc:close() end) it( 'socket err gets forwarded to on_error', function(done) settimeout(6.0) wsc:on_error(async(function(ws,err) assert.is_same(ws,wsc) if socket.tcp6 then assert.is_equal(err, 'host or service not provided, or not known') else assert.is_equal(err,'host not found') end -- wsc:close() done() end)) wsc:on_close(async(function() assert.is_nil(err or 'should never happen') end)) wsc:connect('ws://does_not_exist','echo-protocol') end) it( 'can send and receive data'..req_ws, function(done) settimeout(6.0) assert.is_function(wsc.send) wsc:on_message( async( function(ws,message,opcode) assert.is_equal(ws,wsc) assert.is_same(message,'Hello again') assert.is_same(opcode,frame.TEXT) done() end)) wsc:on_open(function() wsc:send('Hello again') end) wsc:connect(url,'echo-protocol') end) local random_text = function(len) local chars = {} for i=1,len do chars[i] = string.char(math.random(33,126)) end return table.concat(chars) end it( 'can send and receive data 127 byte messages'..req_ws, function(done) settimeout(6.0) local msg = random_text(127) wsc:on_message( async( function(ws,message,opcode) assert.is_same(#msg,#message) assert.is_same(msg,message) assert.is_same(opcode,frame.TEXT) done() end)) wsc:send(msg) end) it( 'can send and receive data 0xffff-1 byte messages'..req_ws, function(done) settimeout(10.0) local msg = random_text(0xffff-1) wsc:on_message( async( function(ws,message,opcode) assert.is_same(#msg,#message) assert.is_same(msg,message) assert.is_same(opcode,frame.TEXT) done() end)) wsc:send(msg) end) it( 'can send and receive data 0xffff+1 byte messages'..req_ws, function(done) settimeout(10.0) local msg = random_text(0xffff+1) wsc:on_message( async( function(ws,message,opcode) assert.is_same(#msg,#message) assert.is_same(msg,message) assert.is_same(opcode,frame.TEXT) done() end)) wsc:send(msg) end) it( 'closes cleanly'..req_ws, function(done) settimeout(6.0) wsc:on_close(async(function(_,was_clean,code,reason) assert.is_true(was_clean) assert.is_true(code >= 1000) assert.is_string(reason) done() end)) wsc:close() end) it( 'echoing 10 messages works'..req_ws, function(done) settimeout(3.0) wsc:on_error(async(function(_,err) assert.is_nil(err or 'should never happen') end)) wsc:on_close(async(function() assert.is_nil('should not happen yet') end)) wsc:on_message(async(function() assert.is_nil('should not happen yet') end)) wsc:on_open(async(function(ws) assert.is_same(ws,wsc) local count = 0 local msg = 'Hello websockets' wsc:on_message(async(function(ws,message,opcode) count = count + 1 assert.is_same(ws,wsc) assert.is_equal(message,msg..count) assert.is_equal(opcode,websocket.TEXT) if count == 10 then ws:on_close(async(function(_,was_clean,opcode,reason) assert.is_true(was_clean) assert.is_true(opcode >= 1000) done() end)) ws:close() end end)) for i=1,10 do wsc:send(msg..i) end end)) wsc:connect(url,'echo-protocol') end) end)
mit
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/rooms/interstice.lua
1
1033
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org return { [[#!!!!!!!!!!!#]], [[!...........!]], [[!...........!]], [[!.####.####.!]], [[!....#.#..#.!]], [[!.#..###..#.!]], [[###.......###]], [[!.#..###..#.!]], [[!.#..#.#....!]], [[!.####.####.!]], [[!...........!]], [[!...........!]], [[#!!!!!!!!!!!#]], }
gpl-3.0
kuoruan/lede-luci
applications/luci-app-ltqtapi/luasrc/controller/ltqtapi.lua
73
1071
-- Copyright 2019 John Crispin <blogic@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.ltqtapi", package.seeall) function index() if not nixio.fs.access("/etc/config/telephony") then return end page = node("admin", "telephony") page.target = firstchild() page.title = _("VoIP") page.order = 90 entry({"admin", "telephony", "account"}, cbi("luci_ltqtapi/account") , _("Account"), 10) entry({"admin", "telephony", "contact"}, cbi("luci_ltqtapi/contact") , _("Contacts"), 20) entry({"admin", "telephony", "status"}, call("tapi_status")).leaf = true end function tapi_status() local st = { } local state = require "luci.model.uci".cursor_state() state:load("telephony") st.status = "Offline"; if state:get("telephony", "state", "port1", "0") == "0" then st.line1 = "Idle"; else st.line1 = "Calling"; end if state:get("telephony", "state", "port2", "0") == "0" then st.line2 = "Idle"; else st.line2 = "Calling"; end luci.http.prepare_content("application/json") luci.http.write_json(st) end
apache-2.0
kuoruan/lede-luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/unixsock.lua
73
1191
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("luci_statistics", translate("Unixsock Plugin Configuration"), translate( "The unixsock plugin creates a unix socket which can be used " .. "to read collected data from a running collectd instance." )) -- collectd_unixsock config section s = m:section( NamedSection, "collectd_unixsock", "luci_statistics" ) -- collectd_unixsock.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_unixsock.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile" ) socketfile.default = "/var/run/collect-query.socket" socketfile:depends( "enable", 1 ) -- collectd_unixsock.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup" ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_unixsock.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms" ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) return m
apache-2.0
teslamint/luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/interface.lua
68
1060
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") m = Map("luci_statistics", translate("Interface Plugin Configuration"), translate( "The interface plugin collects traffic statistics on " .. "selected interfaces." )) -- collectd_interface config section s = m:section( NamedSection, "collectd_interface", "luci_statistics" ) -- collectd_interface.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_interface.interfaces (Interface) interfaces = s:option( MultiValue, "Interfaces", translate("Monitor interfaces") ) interfaces.widget = "select" interfaces.size = 5 interfaces:depends( "enable", 1 ) for k, v in pairs(luci.sys.net.devices()) do interfaces:value(v) end -- collectd_interface.ignoreselected (IgnoreSelected) ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") ) ignoreselected.default = 0 ignoreselected:depends( "enable", 1 ) return m
apache-2.0
kuoruan/lede-luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/interface.lua
68
1060
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") m = Map("luci_statistics", translate("Interface Plugin Configuration"), translate( "The interface plugin collects traffic statistics on " .. "selected interfaces." )) -- collectd_interface config section s = m:section( NamedSection, "collectd_interface", "luci_statistics" ) -- collectd_interface.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_interface.interfaces (Interface) interfaces = s:option( MultiValue, "Interfaces", translate("Monitor interfaces") ) interfaces.widget = "select" interfaces.size = 5 interfaces:depends( "enable", 1 ) for k, v in pairs(luci.sys.net.devices()) do interfaces:value(v) end -- collectd_interface.ignoreselected (IgnoreSelected) ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") ) ignoreselected.default = 0 ignoreselected:depends( "enable", 1 ) return m
apache-2.0
Blackdutchie/Zero-K
LuaUI/i18nlib/i18n/init.lua
5
5957
local i18n = {} local store local locale local pluralizeFunction local defaultLocale = 'en' local fallbackLocale = defaultLocale local path = "LuaUI/i18nlib/i18n/" local plural = VFS.Include(path .. 'plural.lua') local interpolate = VFS.Include(path .. 'interpolate.lua') local variants = VFS.Include(path .. 'variants.lua') local version = VFS.Include(path .. 'version.lua') i18n.plural, i18n.interpolate, i18n.variants, i18n.version, i18n._VERSION = plural, interpolate, variants, version, version -- private stuff local function dotSplit(str) local fields, length = {},0 str:gsub("[^%.]+", function(c) length = length + 1 fields[length] = c end) return fields, length end local function isPluralTable(t) return type(t) == 'table' and type(t.other) == 'string' end local function isPresent(str) return type(str) == 'string' and #str > 0 end local function assertPresent(functionName, paramName, value) if isPresent(value) then return end local msg = "i18n.%s requires a non-empty string on its %s. Got %s (a %s value)." error(msg:format(functionName, paramName, tostring(value), type(value))) end local function assertPresentOrPlural(functionName, paramName, value) if isPresent(value) or isPluralTable(value) then return end local msg = "i18n.%s requires a non-empty string or plural-form table on its %s. Got %s (a %s value)." error(msg:format(functionName, paramName, tostring(value), type(value))) end local function assertPresentOrTable(functionName, paramName, value) if isPresent(value) or type(value) == 'table' then return end local msg = "i18n.%s requires a non-empty string or table on its %s. Got %s (a %s value)." error(msg:format(functionName, paramName, tostring(value), type(value))) end local function assertFunctionOrNil(functionName, paramName, value) if value == nil or type(value) == 'function' then return end local msg = "i18n.%s requires a function (or nil) on param %s. Got %s (a %s value)." error(msg:format(functionName, paramName, tostring(value), type(value))) end local function defaultPluralizeFunction(count) return plural.get(variants.root(i18n.getLocale()), count) end local function pluralize(t, data) assertPresentOrPlural('interpolatePluralTable', 't', t) data = data or {} local count = data.count or 1 local plural_form = pluralizeFunction(count) return t[plural_form] end local function treatNode(node, data) if type(node) == 'string' then return interpolate(node, data) elseif isPluralTable(node) then return interpolate(pluralize(node, data), data) end return node end local function recursiveLoad(currentContext, data) local composedKey for k,v in pairs(data) do composedKey = (currentContext and (currentContext .. '.') or "") .. tostring(k) assertPresent('load', composedKey, k) assertPresentOrTable('load', composedKey, v) if type(v) == 'string' then i18n.set(composedKey, v) else recursiveLoad(composedKey, v) end end end local function localizedTranslate(key, locale, data) local path, length = dotSplit(locale .. "." .. key) local node = store for i=1, length do node = node[path[i]] if not node then return nil end end return treatNode(node, data) end -- public interface function i18n.set(key, value) assertPresent('set', 'key', key) assertPresentOrPlural('set', 'value', value) local path, length = dotSplit(key) local node = store for i=1, length-1 do key = path[i] node[key] = node[key] or {} node = node[key] end local lastKey = path[length] node[lastKey] = value end local missingTranslations = {} function i18n.translate(key, data, newLocale) assertPresent('translate', 'key', key) data = data or {} local usedLocale = newLocale or locale local fallbacks = variants.fallbacks(usedLocale, fallbackLocale) for i=1, #fallbacks do local fallback = fallbacks[i] local value = localizedTranslate(key, fallback, data) if value then return value else if missingTranslations[key] == nil then missingTranslations[key] = { } end local missingTranslation = missingTranslations[key] if not missingTranslation[fallback] then Spring.Log("i18n", "warning", "\"" .. key .. "\" is not translated in " .. fallback) missingTranslation[fallback] = true end end end if missingTranslations[key] == nil then missingTranslations[key] = { } end local missingTranslation = missingTranslations[key] if not missingTranslation["_all"] then Spring.Log("i18n", "error", "No translation found for \"" .. key .. "\"") missingTranslation["_all"] = true end return data.default or key end function i18n.setLocale(newLocale, newPluralizeFunction) assertPresent('setLocale', 'newLocale', newLocale) assertFunctionOrNil('setLocale', 'newPluralizeFunction', newPluralizeFunction) locale = newLocale pluralizeFunction = newPluralizeFunction or defaultPluralizeFunction end function i18n.setFallbackLocale(newFallbackLocale) assertPresent('setFallbackLocale', 'newFallbackLocale', newFallbackLocale) fallbackLocale = newFallbackLocale end function i18n.getFallbackLocale() return fallbackLocale end function i18n.getLocale() return locale end function i18n.reset() store = {} plural.reset() i18n.setLocale(defaultLocale) i18n.setFallbackLocale(defaultLocale) end function i18n.load(data) recursiveLoad(nil, data) end function i18n.loadFile(path) local success, data = pcall(function() local chunk = VFS.LoadFile(path, VFS.ZIP_FIRST) x = assert(loadstring(chunk)) return x() end) if not success then Spring.Log("i18n", LOG.ERROR, "Failed to parse file " .. path .. ": ") Spring.Log("i18n", LOG.ERROR, data) return nil end i18n.load(data) end setmetatable(i18n, {__call = function(_, ...) return i18n.translate(...) end}) i18n.reset() return i18n
gpl-2.0
Blackdutchie/Zero-K
units/tawf114.lua
2
6919
unitDef = { unitname = [[tawf114]], name = [[Banisher]], description = [[Heavy Riot Support Tank]], acceleration = 0.02181, brakeRate = 0.04282, buildCostEnergy = 520, buildCostMetal = 520, builder = false, buildPic = [[TAWF114.png]], buildTime = 520, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], corpse = [[DEAD]], customParams = { description_bp = [[Tanque de mísseis pesado]], description_fr = [[Tank Lance-Missile Lourd]], description_de = [[Schwerer Riot Unterstützungspanzer]], description_pl = [[Ciezki czolg wsparcia]], helptext = [[Remarkably mobile for a riot platform, the Banisher packs twin high-velocity fragmentation missiles that are devastating to light units and aircraft alike, although they have limited range. Like other riot units, the Banisher does not have the range and speed to hold its own against most skirmishers. The missile is quite effective at flattening terrain so it is particularly useful at knocking down walls that Welders cannot reach.]], helptext_bp = [[Como um escaramuçador pesado, O Banisher adiciona poder de fogo de alcançe médio-longo para a força de assalto de Logos. Seus mísseis guiados s?o rápidos e devastadores contra unidades terrestres e aéreas, embora tenham um tempo de recarga significante. Banishers n?o acompanhados por outras unidades podem ser superados facilmente por grandes grupos de pequenas unidades.]], helptext_fr = [[Les Banishers sont arm?s de deux lance-missiles lourds ? t?te chercheuse. Capable d'attaquer les cibles au sol ou dans les airs, ils font d'?normes d?g?ts, mais sont lent a recharger. Impuissant contre les nu?es d'ennemis et indispensable contre les grosses cibles, son blindage ne lui permet pas d'?tre en premi?re ligne.]], helptext_de = [[Erstaunlich beweglich für eine Rioteinheit. Der Banisher ist mit Zwillings-Hochgeschwindigkeits Splitterraketen ausgerüstet, die verheerend für leichte Einheiten und Lufteinheiten sind, obwohl sie nur eine begrenzte Reichweite haben. Der Banisher wird schnell von Sturmeinheiten überrascht und sogar von Raider, weshalb du ihn mit deinen Abschirmungseinheiten beschützen musst. Anders als andere Rioteinheiten besitzt der Banisher die nötige Geschwindigkeit und Reichweite, um sich gegen die meisten Skirmishern zu halten.]], helptext_pl = [[Ruchomy jak na jednostke wsparcia, Banisher posiada ciezkie rakiety krotkiego zasiegu, ktore szybko niszcza grupy lekkich jednostek, sa skuteczne przeciw lotnictwu i wyrownuja teren. Banishera latwo zniszczyc jednostkami szturmowymi lub rozdzielonymi lekkimi jednostkami, ale dobrze radzi sobie z innymi, wolniejszmi jednostkami o mniejszym zasiegu.]], }, explodeAs = [[BIG_UNITEX]], footprintX = 4, footprintZ = 4, iconType = [[tankriot]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, mass = 291, maxDamage = 1650, maxSlope = 18, maxVelocity = 2.3, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TANK4]], moveState = 0, noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE SUB]], objectName = [[corbanish.s3o]], script = [[tawf114.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], side = [[CORE]], sightDistance = 400, smoothAnim = true, trackOffset = 8, trackStrength = 10, trackStretch = 1, trackType = [[StdTank]], trackWidth = 48, turninplace = 0, turnRate = 355, workerTime = 0, weapons = { { def = [[TAWF_BANISHER]], mainDir = [[0 0 1]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { TAWF_BANISHER = { name = [[Heavy Missile]], areaOfEffect = 160, cegTag = [[BANISHERTRAIL]], craterBoost = 1, craterMult = 2, customParams = { gatherradius = [[120]], smoothradius = [[80]], smoothmult = [[0.25]], }, damage = { default = 440.5, subs = 22, }, edgeEffectiveness = 0.4, explosionGenerator = [[custom:xamelimpact]], fireStarter = 20, flightTime = 4, impulseBoost = 0, impulseFactor = 0.6, interceptedByShieldType = 2, model = [[corbanishrk.s3o]], noSelfDamage = true, range = 340, reloadtime = 2.3, smokeTrail = false, soundHit = [[weapon/bomb_hit]], soundStart = [[weapon/missile/banisher_fire]], startVelocity = 400, tolerance = 9000, tracks = true, trajectoryHeight = 0.45, turnRate = 22000, turret = true, weaponAcceleration = 70, weaponTimer = 5, weaponType = [[MissileLauncher]], weaponVelocity = 400, }, }, featureDefs = { DEAD = { description = [[Wreckage - Banisher]], blocking = true, category = [[corpses]], damage = 1650, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 3, footprintZ = 3, height = [[30]], hitdensity = [[100]], metal = 208, object = [[corbanish_dead.s3o]], reclaimable = true, reclaimTime = 208, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Banisher]], blocking = false, category = [[heaps]], damage = 1650, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 3, footprintZ = 3, height = [[5]], hitdensity = [[100]], metal = 104, object = [[debris3x3a.s3o]], reclaimable = true, reclaimTime = 104, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ tawf114 = unitDef })
gpl-2.0
Blackdutchie/Zero-K
units/armdeva.lua
3
5556
unitDef = { unitname = [[armdeva]], name = [[Stardust]], description = [[Anti-Swarm Turret]], activateWhenBuilt = true, buildCostEnergy = 220, buildCostMetal = 220, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 5, buildingGroundDecalSizeY = 5, buildingGroundDecalType = [[armdeva_aoplane.dds]], buildPic = [[armdeva.png]], buildTime = 220, canAttack = true, category = [[FLOAT TURRET]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[45 45 45]], collisionVolumeTest = 1, collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { description_de = [[Anti-Schwarm EMG]], description_fr = [[Mitrailleurs Anti-Nuée]], description_pl = [[Wiezyczka Wsparcia]], helptext = [[The Stardust sports a powerful autocannon. While it has a short range and is thus even more vulnerable to skirmishers than the LLT, its high rate of fire and AoE allow it to quickly chew up swarms of lighter units.]], helptext_de = [[Stardust ist ein Geschützturm mit einem lang perfektionierten und tödlichen energetischen Maschinengewehr. Zwar besitzt es nur eine kurze Reichweite, wodurch es sehr verletzbar gegenüber Skirmishern ist, dennoch machen es die hohe Feuerrate und die AoE zu einer guten Verteidigung gegen Schwärme und leichte Einheiten.]], helptext_fr = [[Le Stardust est une tourelle mitrailleuse r haute energie. Son incroyable cadence de tir lui permettent d'arreter quasiment nimporte quelle nuée de Pilleur ou d'unités légcres, cependant sa portée est relativement limitée, et étant prcs du sol nimporte quel obstacle l'empeche de tirer.]], helptext_pl = [[Stardust posiada dzialko o bardzo duzej sile i szerokim obszarze dzialania, co pozwala mu niszczyc hordy lzejszych jednostek. Ma jednak niski zasieg, co pozwala harcownikom i jednostkom z wiekszym zasiegiem atakowac go bez mozliwosci kontrataku.]], aimposoffset = [[0 12 0]], midposoffset = [[0 4 0]], }, defaultmissiontype = [[GUARD_NOMOVE]], explodeAs = [[LARGE_BUILDINGEX]], floater = true, footprintX = 3, footprintZ = 3, iconType = [[defenseriot]], levelGround = false, maxDamage = 1500, maxSlope = 18, minCloakDistance = 150, noChaseCategory = [[FIXEDWING LAND SHIP SWIM GUNSHIP SUB HOVER]], objectName = [[afury.s3o]], script = "armdeva.lua", seismicSignature = 4, selfDestructAs = [[LARGE_BUILDINGEX]], sfxtypes = { explosiongenerators = { [[custom:WARMUZZLE]], [[custom:DEVA_SHELLS]], }, }, sightDistance = 451, useBuildingGroundDecal = true, yardMap = [[ooo ooo ooo]], weapons = { { def = [[ARMDEVA_WEAPON]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { ARMDEVA_WEAPON = { name = [[Pulse Autocannon]], accuracy = 2300, alphaDecay = 0.7, areaOfEffect = 96, avoidFeature = false, burnblow = true, craterBoost = 0.15, craterMult = 0.3, damage = { default = 45, subs = 2.25, }, edgeEffectiveness = 0.5, explosionGenerator = [[custom:EMG_HIT_HE]], firestarter = 70, impulseBoost = 0, impulseFactor = 0.4, intensity = 0.7, interceptedByShieldType = 1, noSelfDamage = true, range = 410, reloadtime = 0.12, rgbColor = [[1 0.95 0.4]], separation = 1.5, soundHit = [[weapon/cannon/emg_hit]], soundStart = [[weapon/heavy_emg]], soundStartVolume = 0.5, stages = 10, turret = true, weaponType = [[Cannon]], weaponVelocity = 550, }, }, featureDefs = { DEAD = { description = [[Wreckage - Stardust]], blocking = true, damage = 1500, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, metal = 88, object = [[afury_dead.s3o]], reclaimable = true, reclaimTime = 88, }, HEAP = { description = [[Debris - Stardust]], blocking = false, damage = 1500, footprintX = 3, footprintZ = 3, metal = 44, object = [[debris4x4b.s3o]], reclaimable = true, reclaimTime = 44, }, }, } return lowerkeys({ armdeva = unitDef })
gpl-2.0
Blackdutchie/Zero-K
LuaRules/Gadgets/unit_AA_anti_bait.lua
12
6520
local versionNumber = "v0.1" function gadget:GetInfo() return { name = "AA anti-bait", desc = versionNumber .. " Managed Allowed Weapon Target for Hacksaw and Screamer to ignore bait when other AA is present nearby", author = "Jseah", date = "04/26/13", license = "GNU GPL, v2 or later", layer = 0, enabled = false -- loaded by default? } end if (not gadgetHandler:IsSyncedCode()) then return end --SYNCED-- include("LuaRules/Configs/customcmds.h.lua") local unitAICmdDesc = { id = CMD_UNIT_AI, type = CMDTYPE.ICON_MODE, name = 'Unit AI', action = 'unitai', tooltip = 'Toggles smart unit AI for the unit', params = {1, 'AI Off','AI On'} } local GetUnitsInCylinder = Spring.GetUnitsInCylinder local GetUnitPosition = Spring.GetUnitPosition local GetUnitDefID = Spring.GetUnitDefID local FindUnitCmdDesc = Spring.FindUnitCmdDesc local EditUnitCmdDesc = Spring.EditUnitCmdDesc local GetUnitCmdDesc = Spring.GetUnitCmdDescs local InsertUnitCmdDesc = Spring.InsertUnitCmdDesc local hpthreshold = 650 -- maxhp below which an air unit is considered bait local baitexceptions = {["phoenix"] = {["missiletower"] = 1, ["screamer"] = 1}} -- units which are never considered bait, "name" = 1 means that tower will consider the target to be part of this category local alwaysbait = {["corvamp"] = {["missiletower"] = 1, ["screamer"] = 1}} -- units which are always considered bait local AAunittypes = {["missiletower"] = 100, ["screamer"] = 300} -- what is valid for anti-bait behaviour -- number is the threshold of "points" above which a turret is considered escorted if it has at least that amount within half range local AAescort = { -- points of how much each AA unit is worth ["corrl"] = 100, ["armcir"] = 350, ["corrazor"] = 250, ["corflak"] = 350, ["corvamp"] = 100, ["fighter"] = 80, ["gunshipsupport"] = 100, ["armjeth"] = 60, ["corcrash"] = 80, ["vehaa"] = 60, ["armaak"] = 250, ["corarch"] = 250, ["corsent"] = 250} local AA = {} -- {id = unitID, escorted = boolean, range = maxrange, threshold = integer from unittypes} local AAcount = 1 local AAref = {} -- {[unitID] = index in AA table} local updatespeed = 30 -- frames over which the escort states will be updated local updatecount = 1 local remUnitDefID = {} local Echo = Spring.Echo local IsAA = { [UnitDefNames.missiletower.id] = true, [UnitDefNames.screamer.id] = true, } -------------------FUNCTIONS------------------ function Isair(ud) return ud.canFly or false end function IsBait(AAname, unitDef) if not Isair(unitDef) then return false end if unitDef.health < 650 then if baitexceptions[unitDef.name] == nil then return true end --Echo(baitexceptions[unitDef.name][AAname]) if baitexceptions[unitDef.name][AAname] == nil then return true end end if alwaysbait[unitDef.name] ~= nil then --Echo(alwaysbait[unitDef.name][AAname]) if alwaysbait[unitDef.name][AAname] ~= nil then return true end end return false end function IsMicroCMD(unitID) if unitID ~= nil then local cmdDescID = FindUnitCmdDesc(unitID, CMD_UNIT_AI) local cmdDesc = GetUnitCmdDesc(unitID, cmdDescID, cmdDescID) local nparams = cmdDesc[1].params if nparams[1] == '1' then return true end end return false end function AddAA(unitID, ud) AA[AAcount] = {id = unitID, escorted = false, range = ud.maxWeaponRange, threshold = AAunittypes[ud.name]} AAref[unitID] = AAcount AAcount = AAcount + 1 end function removeAA(unitID) local index = AAref[unitID] AA[index] = AA[AAcount - 1] AAref[AA[index].id] = index AA[AAcount] = nil AAcount = AAcount - 1 AAref[unitID] = nil end function updateAA(AAunitID, index) local range = AA[index].range local x, y, z = GetUnitPosition(AAunitID) local units = GetUnitsInCylinder(x, z, range / 2) local threshold = AA[index].threshold AA[index].escorted = false for _, unitID in pairs(units) do local unitDefID = GetUnitDefID(unitID) local ud = UnitDefs[unitDefID] if AAescort[ud.name] ~= nil then threshold = threshold - AAescort[ud.name] --ud.metalCost if threshold <= 0 then AA[index].escorted = true return nil end end end end -------------------CALL INS------------------- function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID) local ud = UnitDefs[unitDefID] remUnitDefID[unitID] = unitDefID if IsAA(ud.name) then InsertUnitCmdDesc(unitID, unitAICmdDesc) local cmdDescID = FindUnitCmdDesc(unitID, CMD_UNIT_AI) EditUnitCmdDesc(unitID, cmdDescID, {params = {0, 'AI Off','AI On'}}) AddAA(unitID, ud) end end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) local ud = UnitDefs[unitDefID] remUnitDefID[unitID] = nil if IsAA(ud.name) then removeAA(unitID) end end function gadget:Initialize() Echo("AA anti-bait Gadget Enabled") for _, unitID in pairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) gadget:UnitCreated(unitID, unitDefID) end end function gadget:GameFrame() ----Echo("update") for i = 1, AAcount - 1 do if math.fmod(i, updatespeed) == updatecount then updateAA(AA[i].id, i) end end updatecount = updatecount + 1 if updatecount > updatespeed then updatecount = 1 end end function gadget:AllowWeaponTarget(attackerID, targetID, attackerWeaponNum, attackerWeaponDefID, defPriority) local unitDefID = remUnitDefID[attackerID] if IsAA[unitDefID] and IsMicroCMD(attackerID) and AA[AAref[attackerID]].escorted then local ud = UnitDefs[unitDefID] --Echo(AA[AAref[attackerID]].escorted) local tunitDefID = Spring.GetUnitDefID(targetID) local tud = UnitDefs[tunitDefID] if IsBait(ud.name, tud) then --Echo("bait") return false, 1 end end return true, 1 end function gadget:AllowCommand_GetWantedCommand() return {[CMD_UNIT_AI] = true} end function gadget:AllowCommand_GetWantedUnitDefID() return true end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) local ud = UnitDefs[unitDefID] if IsAA(ud.name) then if cmdID == CMD_UNIT_AI then local cmdDescID = FindUnitCmdDesc(unitID, CMD_UNIT_AI) if cmdParams[1] == 0 then nparams = {0, 'AI Off','AI On'} else nparams = {1, 'AI Off','AI On'} end EditUnitCmdDesc(unitID, cmdDescID, {params = nparams}) end end return true end
gpl-2.0
Blackdutchie/Zero-K
effects/gundam_otaplas.lua
50
48727
-- miniotaplas_fireball11 -- otaplas_fireball3 -- otaplas_fireball16 -- otaplas_fireball14 -- ota_plas -- miniotaplas_fireball17 -- otaplas_fireball18 -- otaplas_fireball1 -- otaplas_fireball11 -- miniotaplas_fireball13 -- otaplas_fireball10 -- miniotaplas_fireball16 -- otaplas_fireball13 -- miniotaplas_fireball2 -- otaplas_fireball7 -- miniotaplas_fireball14 -- otaplas_fireball12 -- miniotaplas_fireball7 -- otaplas_fireball17 -- miniotaplas_fireball9 -- miniotaplas_fireball18 -- miniota_plas -- miniotaplas_fireball3 -- otaplas_fireball6 -- otaplas_fireball4 -- miniotaplas_fireball5 -- otaplas_fireball8 -- miniotaplas_fireball15 -- otaplas_fireball2 -- miniotaplas_fireball6 -- otaplas_fireball15 -- otaplas_fireball9 -- miniotaplas_fireball8 -- miniotaplas_fireball4 -- miniotaplas_fireball10 -- miniotaplas_fireball12 -- miniotaplas_fireball1 -- otaplas_fireball5 return { ["miniotaplas_fireball11"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas11]], }, }, }, ["otaplas_fireball3"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas3]], }, }, }, ["otaplas_fireball16"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas16]], }, }, }, ["otaplas_fireball14"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas14]], }, }, }, ["ota_plas"] = { frame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:OTAPLAS_FIREBALL1]], pos = [[0, 0, 0]], }, }, frame10 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 18, explosiongenerator = [[custom:OTAPLAS_FIREBALL10]], pos = [[0, 9, 0]], }, }, frame11 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 20, explosiongenerator = [[custom:OTAPLAS_FIREBALL11]], pos = [[0, 10, 0]], }, }, frame12 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 22, explosiongenerator = [[custom:OTAPLAS_FIREBALL12]], pos = [[0, 11, 0]], }, }, frame13 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 24, explosiongenerator = [[custom:OTAPLAS_FIREBALL13]], pos = [[0, 12, 0]], }, }, frame14 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 26, explosiongenerator = [[custom:OTAPLAS_FIREBALL14]], pos = [[0, 13, 0]], }, }, frame15 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 28, explosiongenerator = [[custom:OTAPLAS_FIREBALL15]], pos = [[0, 14, 0]], }, }, frame16 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 30, explosiongenerator = [[custom:OTAPLAS_FIREBALL16]], pos = [[0, 15, 0]], }, }, frame17 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 32, explosiongenerator = [[custom:OTAPLAS_FIREBALL17]], pos = [[0, 16, 0]], }, }, frame18 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 34, explosiongenerator = [[custom:OTAPLAS_FIREBALL18]], pos = [[0, 17, 0]], }, }, frame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 2, explosiongenerator = [[custom:OTAPLAS_FIREBALL2]], pos = [[0, 1, 0]], }, }, frame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 4, explosiongenerator = [[custom:OTAPLAS_FIREBALL3]], pos = [[0, 2, 0]], }, }, frame4 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 6, explosiongenerator = [[custom:OTAPLAS_FIREBALL4]], pos = [[0, 3, 0]], }, }, frame5 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 8, explosiongenerator = [[custom:OTAPLAS_FIREBALL5]], pos = [[0, 4, 0]], }, }, frame6 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 10, explosiongenerator = [[custom:OTAPLAS_FIREBALL6]], pos = [[0, 5, 0]], }, }, frame7 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 12, explosiongenerator = [[custom:OTAPLAS_FIREBALL7]], pos = [[0, 6, 0]], }, }, frame8 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 14, explosiongenerator = [[custom:OTAPLAS_FIREBALL8]], pos = [[0, 7, 0]], }, }, frame9 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 16, explosiongenerator = [[custom:OTAPLAS_FIREBALL9]], pos = [[0, 8, 0]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 40, ttl = 20, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0.69999998807907, }, }, }, ["miniotaplas_fireball17"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas17]], }, }, }, ["otaplas_fireball18"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas18]], }, }, }, ["otaplas_fireball1"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 1 1 0.01 1 1 1 0.01 .5 .5 .5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas1]], }, }, }, ["otaplas_fireball11"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas11]], }, }, }, ["miniotaplas_fireball13"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas13]], }, }, }, ["otaplas_fireball10"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas10]], }, }, }, ["miniotaplas_fireball16"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas16]], }, }, }, ["otaplas_fireball13"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas13]], }, }, }, ["miniotaplas_fireball2"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .5, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas2]], }, }, }, ["otaplas_fireball7"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas7]], }, }, }, ["miniotaplas_fireball14"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas14]], }, }, }, ["otaplas_fireball12"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas12]], }, }, }, ["miniotaplas_fireball7"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas7]], }, }, }, ["otaplas_fireball17"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas17]], }, }, }, ["miniotaplas_fireball9"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas9]], }, }, }, ["miniotaplas_fireball18"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas18]], }, }, }, ["miniota_plas"] = { frame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL1]], pos = [[0, 0, 0]], }, }, frame10 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 18, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL10]], pos = [[0, 9, 0]], }, }, frame11 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 20, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL11]], pos = [[0, 10, 0]], }, }, frame12 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 22, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL12]], pos = [[0, 11, 0]], }, }, frame13 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 24, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL13]], pos = [[0, 12, 0]], }, }, frame14 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 26, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL14]], pos = [[0, 13, 0]], }, }, frame15 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 28, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL15]], pos = [[0, 14, 0]], }, }, frame16 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 30, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL16]], pos = [[0, 15, 0]], }, }, frame17 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 32, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL17]], pos = [[0, 16, 0]], }, }, frame18 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 34, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL18]], pos = [[0, 17, 0]], }, }, frame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 2, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL2]], pos = [[0, 1, 0]], }, }, frame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 4, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL3]], pos = [[0, 2, 0]], }, }, frame4 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 6, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL4]], pos = [[0, 3, 0]], }, }, frame5 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 8, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL5]], pos = [[0, 4, 0]], }, }, frame6 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 10, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL6]], pos = [[0, 5, 0]], }, }, frame7 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 12, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL7]], pos = [[0, 6, 0]], }, }, frame8 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 14, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL8]], pos = [[0, 7, 0]], }, }, frame9 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 16, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL9]], pos = [[0, 8, 0]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 40, ttl = 20, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0.69999998807907, }, }, }, ["miniotaplas_fireball3"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas3]], }, }, }, ["otaplas_fireball6"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas6]], }, }, }, ["otaplas_fireball4"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas4]], }, }, }, ["miniotaplas_fireball5"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas5]], }, }, }, ["otaplas_fireball8"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas8]], }, }, }, ["miniotaplas_fireball15"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas15]], }, }, }, ["otaplas_fireball2"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .5, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas2]], }, }, }, ["miniotaplas_fireball6"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas6]], }, }, }, ["otaplas_fireball15"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas15]], }, }, }, ["otaplas_fireball9"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas9]], }, }, }, ["miniotaplas_fireball8"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas8]], }, }, }, ["miniotaplas_fireball4"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas4]], }, }, }, ["miniotaplas_fireball10"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas10]], }, }, }, ["miniotaplas_fireball12"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas12]], }, }, }, ["miniotaplas_fireball1"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 1 1 0.01 1 1 1 0.01 .5 .5 .5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas1]], }, }, }, ["otaplas_fireball5"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas5]], }, }, }, }
gpl-2.0
electricpandafishstudios/Spoon
game/thirdparty/socket/tp.lua
146
3608
----------------------------------------------------------------------------- -- Unified SMTP/FTP subsystem -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: tp.lua,v 1.22 2006/03/14 09:04:15 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local socket = require("socket") local ltn12 = require("ltn12") module("socket.tp") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- TIMEOUT = 60 ----------------------------------------------------------------------------- -- Implementation ----------------------------------------------------------------------------- -- gets server reply (works for SMTP and FTP) local function get_reply(c) local code, current, sep local line, err = c:receive() local reply = line if err then return nil, err end code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) if not code then return nil, "invalid server reply" end if sep == "-" then -- reply is multiline repeat line, err = c:receive() if err then return nil, err end current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) reply = reply .. "\n" .. line -- reply ends with same code until code == current and sep == " " end return code, reply end -- metatable for sock object local metat = { __index = {} } function metat.__index:check(ok) local code, reply = get_reply(self.c) if not code then return nil, reply end if base.type(ok) ~= "function" then if base.type(ok) == "table" then for i, v in base.ipairs(ok) do if string.find(code, v) then return base.tonumber(code), reply end end return nil, reply else if string.find(code, ok) then return base.tonumber(code), reply else return nil, reply end end else return ok(base.tonumber(code), reply) end end function metat.__index:command(cmd, arg) if arg then return self.c:send(cmd .. " " .. arg.. "\r\n") else return self.c:send(cmd .. "\r\n") end end function metat.__index:sink(snk, pat) local chunk, err = c:receive(pat) return snk(chunk, err) end function metat.__index:send(data) return self.c:send(data) end function metat.__index:receive(pat) return self.c:receive(pat) end function metat.__index:getfd() return self.c:getfd() end function metat.__index:dirty() return self.c:dirty() end function metat.__index:getcontrol() return self.c end function metat.__index:source(source, step) local sink = socket.sink("keep-open", self.c) local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) return ret, err end -- closes the underlying c function metat.__index:close() self.c:close() return 1 end -- connect with server and return c object function connect(host, port, timeout, create) local c, e = (create or socket.tcp)() if not c then return nil, e end c:settimeout(timeout or TIMEOUT) local r, e = c:connect(host, port) if not r then c:close() return nil, e end return base.setmetatable({c = c}, metat) end
gpl-3.0
hexahedronic/basewars
basewars_free/gamemode/modules/drugs.lua
2
7625
MODULE.Name = "Drugs" MODULE.Author = "Q2F2 & Ghosty" local tag = "BaseWars.Drugs" local PLAYER = debug.getregistry().Player local DRUG_REMOVE = 0 local DRUG_FAILED = 1 MODULE.EffectTable = { ["Stun"] = { Apply = function(ply, dur) ply.StunDuration = dur if ply.StunDuration > 70 then ply.StunDuration = 70 end ply:ConCommand("pp_motionblur 1") ply:ConCommand("pp_motionblur_addalpha 0.1") ply:ConCommand("pp_motionblur_delay 0.035") local blindamount = ply.StunDuration * 0.025 if blindamount > 1 then blindamount = 1 end ply:ConCommand("pp_motionblur_drawalpha " .. blindamount) end, Check = function(ply) ply.StunDuration = ply.StunDuration - 1 if ply:HasDrug("Antidote") then ply.StunDuration = ply.StunDuration - 3 end local blindamount = ply.StunDuration * 0.025 if blindamount > 1 then blindamount = 1 end ply:ConCommand("pp_motionblur_drawalpha " .. blindamount) if ply.StunDuration > 25 then local Mult = ply.StunDuration - 25 local Ang = Angle(Mult * math.random() * 0.2, Mult * math.random() * 0.2, Mult * math.random() * 0.2) ply:ViewPunch(Ang) end if ply.StunDuration < 1 then return DRUG_REMOVE end end, Remove = function(ply) ply.StunDuration = nil ply:ConCommand("pp_motionblur 0") end, }, ["Poison"] = { Apply = function(ply, dur, attk, infl) ply.PoisonAttacker = attk ply.PoisonInflictor = infl ply.PoisonDuration = dur if ply.PoisonDuration > 70 then ply.PoisonDuration = 70 end ply:TakeDamage(math.ceil(ply.PoisonDuration / 8), attk, infl) end, Check = function(ply) ply.PoisonDuration = ply.PoisonDuration - 1 if ply:HasDrug("Antidote") then ply.PoisonDuration = ply.PoisonDuration - 3 end ply:TakeDamage(math.ceil(ply.PoisonDuration / 8), ply.PoisonAttacker, ply.PoisonInflictor) if ply.PoisonDuration < 1 then return DRUG_REMOVE end end, Remove = function(ply) ply.PoisonDuration = nil end, }, ["Steroid"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.SteroidEffect, BASEWARS_NOTIFICATION_DRUG) ply:SetWalkSpeed(BaseWars.Config.Drugs.Steroid.Walk) ply:SetRunSpeed(BaseWars.Config.Drugs.Steroid.Run) end, Check = function(ply) -- None. end, Remove = function(ply) ply:Notify(BaseWars.LANG.SteroidRemove, BASEWARS_NOTIFICATION_DRUG) ply:SetWalkSpeed(BaseWars.Config.DefaultWalk) ply:SetRunSpeed(BaseWars.Config.DefaultRun) end, }, ["Regen"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.RegenEffect, BASEWARS_NOTIFICATION_DRUG) end, Check = function(ply) if ply:Health() < ply:GetMaxHealth() then ply:SetHealth(ply:Health() + 2) if ply:Health() > ply:GetMaxHealth() then ply:SetHealth(ply:GetMaxHealth()) end elseif ply:Armor() < 100 then ply:SetArmor(ply:Armor() + 1) if ply:Armor() > 100 then ply:SetArmor(100) end end end, Remove = function(ply) ply:Notify(BaseWars.LANG.RegenRemove, BASEWARS_NOTIFICATION_DRUG) end, }, ["Shield"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.ShieldEffect, BASEWARS_NOTIFICATION_DRUG) end, Check = function(ply) -- None. -- Handled in EntityTakeDamage. end, Remove = function(ply) ply:Notify(BaseWars.LANG.ShieldRemove, BASEWARS_NOTIFICATION_DRUG) end, }, ["Rage"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.RageEffect, BASEWARS_NOTIFICATION_DRUG) end, Check = function(ply) -- None. -- Handled in EntityTakeDamage. end, Remove = function(ply) ply:Notify(BaseWars.LANG.RageRemove, BASEWARS_NOTIFICATION_DRUG) end, }, ["PainKiller"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.PainKillerEffect, BASEWARS_NOTIFICATION_DRUG) end, Check = function(ply) -- None. -- Handled in EntityTakeDamage. end, Remove = function(ply) ply:Notify(BaseWars.LANG.PainKillerRemove, BASEWARS_NOTIFICATION_DRUG) end, }, ["Antidote"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.AntidoteEffect, BASEWARS_NOTIFICATION_DRUG) end, Check = function(ply) -- None. -- Passive drug effector. end, Remove = function(ply) ply:Notify(BaseWars.LANG.AntidoteRemove, BASEWARS_NOTIFICATION_DRUG) end, }, ["Adrenaline"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.AdrenalineEffect, BASEWARS_NOTIFICATION_DRUG) ply:SetMaxHealth(ply:GetMaxHealth() * BaseWars.Config.Drugs.Adrenaline.Mult) ply:SetHealth(ply:Health() * BaseWars.Config.Drugs.Adrenaline.Mult) end, Check = function(ply) -- None. end, Remove = function(ply) ply:Notify(BaseWars.LANG.AdrenalineRemove, BASEWARS_NOTIFICATION_DRUG) ply:SetMaxHealth(ply:GetMaxHealth() / BaseWars.Config.Drugs.Adrenaline.Mult) ply:SetHealth(math.max(ply:Health() / BaseWars.Config.Drugs.Adrenaline.Mult, 1)) end, }, ["DoubleJump"] = { Apply = function(ply, dur) ply:Notify(BaseWars.LANG.DoubleJumpEffect, BASEWARS_NOTIFICATION_DRUG) end, Check = function(ply) -- None. -- Handled in KeyPress. end, Remove = function(ply) ply:Notify(BaseWars.LANG.DoubleJumpRemove, BASEWARS_NOTIFICATION_DRUG) end, }, } function MODULE:HasDrug(ply, effect) return ply:GetNWBool(tag .. "." .. effect) end PLAYER.HasDrug = Curry(MODULE.HasDrug) function MODULE:RemoveDrug(ply, effect) if CLIENT then return end if not BaseWars.Ents:ValidPlayer(ply) then return false end local E = self.EffectTable[effect] local TID = ply:SteamID64() .. "." .. tag .. "." .. effect if not E then return false end if not ply:HasDrug(effect) then return false end BaseWars.UTIL.TimerAdvDestroy(TID) E.Remove(ply) ply:SetNWBool(tag .. "." .. effect, false) if ply.__Effects then ply.__Effects[effect] = nil end ply:EmitSound("player/spy_uncloak.wav") return true end PLAYER.RemoveDrug = Curry(MODULE.RemoveDrug) function MODULE:ClearDrugs(ply) if CLIENT then return end local Effects = ply.__Effects if not Effects then return false end for k, v in next, Effects do local Res = ply:RemoveDrug(v) if not Res then BaseWars.UTIL.Log("DRUG ERROR ", ply, " -> Failed to remove effect '", v, "'.") continue end end return true end PLAYER.ClearDrugs = Curry(MODULE.ClearDrugs) function MODULE:ApplyDrug(ply, effect, dur, ...) if CLIENT then return end if not BaseWars.Ents:ValidPlayer(ply) then return false end local dur = dur or (BaseWars.Config.Drugs[effect] and BaseWars.Config.Drugs[effect].Duration or 60) local E = self.EffectTable[effect] local TID = ply:SteamID64() .. "." .. tag .. "." .. effect if not E then return false end if ply:HasDrug(effect) then ply:RemoveDrug(effect) end local Res = E.Apply(ply, dur, ...) if Res == DRUG_FAILED then return false end ply.__Effects = ply.__Effects or {} ply.__Effects[effect] = effect ply:SetNWBool(tag .. "." .. effect, true) local Done = function() if not BaseWars.Ents:ValidPlayer(ply) then return end E.Remove(ply) ply:SetNWBool(tag .. "." .. effect, false) ply.__Effects[effect] = nil end local Tick = function() if not BaseWars.Ents:ValidPlayer(ply) then BaseWars.UTIL.TimerAdvDestroy(TID) return end local Res = E.Check(ply) if Res == DRUG_REMOVE then ply:RemoveDrug(effect) return end if not ply:Alive() then ply:RemoveDrug(effect) return end end BaseWars.UTIL.TimerAdv(TID, 0.3, dur / 0.3, Tick, Done) ply:EmitSound("player/spy_cloak.wav") return true end PLAYER.ApplyDrug = Curry(MODULE.ApplyDrug)
mit