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
chelog/brawl
addons/brawl-weapons/lua/cw/client/cw_clientmenu.lua
1
6247
local function CW2_GetLaserQualityText(level) if level <= 1 then return " Normal" end return " High" end CustomizableWeaponry.renderTargetSizes = {[1] = {size = 256, text = "Low (256x256)"}, [2] = {size = 512, text = "Medium (512x512)"}, [3] = {size = 768, text = "High (768x768)"}, [4] = {size = 1024, text = "Very high (1024x1024)"}} function CustomizableWeaponry:clampRenderTargetLevel(level) return math.Clamp(level, 1, #self.renderTargetSizes) end function CustomizableWeaponry:getRenderTargetData(level) return self.renderTargetSizes[self:clampRenderTargetLevel(level)] end function CustomizableWeaponry:getRenderTargetText(level) return self.renderTargetSizes[self:clampRenderTargetLevel(level)].text end function CustomizableWeaponry:getRenderTargetSize(level) return self.renderTargetSizes[self:clampRenderTargetLevel(level)].size end local function CW2_ClientsidePanel(panel) panel:ClearControls() panel:AddControl("Label", {Text = "HUD Control"}) panel:AddControl("CheckBox", {Label = "Use custom HUD?", Command = "cw_customhud"}) panel:AddControl("CheckBox", {Label = "HUD: use 3D2D ammo display?", Command = "cw_customhud_ammo"}) panel:AddControl("CheckBox", {Label = "Display crosshair?", Command = "cw_crosshair"}) panel:AddControl("Label", {Text = "Visual effects control"}) panel:AddControl("CheckBox", {Label = "BLUR: On reload?", Command = "cw_blur_reload"}) panel:AddControl("CheckBox", {Label = "BLUR: On customize?", Command = "cw_blur_customize"}) panel:AddControl("CheckBox", {Label = "BLUR: On aim?", Command = "cw_blur_aim_telescopic"}) panel:AddControl("CheckBox", {Label = "Use simple telescopics?", Command = "cw_simple_telescopics"}) panel:AddControl("CheckBox", {Label = "FREE AIM: activate?", Command = "cw_freeaim"}) panel:AddControl("CheckBox", {Label = "FREE AIM: use auto-center?", Command = "cw_freeaim_autocenter"}) panel:AddControl("CheckBox", {Label = "FREE AIM: auto-center while aiming?", Command = "cw_freeaim_autocenter_aim"}) -- autocenter time slider local slider = vgui.Create("DNumSlider", panel) slider:SetDecimals(2) slider:SetMin(0.1) slider:SetMax(2) slider:SetConVar("cw_freeaim_autocenter_time") slider:SetValue(GetConVarNumber("cw_freeaim_autocenter_time")) slider:SetText("AUTO-CENTER: time") panel:AddItem(slider) local slider = vgui.Create("DNumSlider", panel) slider:SetDecimals(2) slider:SetMin(0) slider:SetMax(0.9) slider:SetConVar("cw_freeaim_center_mouse_impendance") slider:SetValue(GetConVarNumber("cw_freeaim_center_mouse_impendance")) slider:SetText("FREE AIM: mouse impendance") panel:AddItem(slider) local slider = vgui.Create("DNumSlider", panel) slider:SetDecimals(3) slider:SetMin(0) slider:SetMax(0.05) slider:SetConVar("cw_freeaim_lazyaim") slider:SetValue(GetConVarNumber("cw_freeaim_lazyaim")) slider:SetText("FREE AIM: 'lazy aim'") panel:AddItem(slider) -- pitch limit local slider = vgui.Create("DNumSlider", panel) slider:SetDecimals(1) slider:SetMin(5) slider:SetMax(15) slider:SetConVar("cw_freeaim_pitchlimit") slider:SetValue(GetConVarNumber("cw_freeaim_pitchlimit")) slider:SetText("FREE AIM: pitch freedom") panel:AddItem(slider) local slider = vgui.Create("DNumSlider", panel) slider:SetDecimals(1) slider:SetMin(5) slider:SetMax(30) slider:SetConVar("cw_freeaim_yawlimit") slider:SetValue(GetConVarNumber("cw_freeaim_yawlimit")) slider:SetText("FREE AIM: yaw freedom") panel:AddItem(slider) local laserQ = vgui.Create("DComboBox", panel) laserQ:SetText("Laser quality:" .. CW2_GetLaserQualityText(GetConVarNumber("cw_laser_quality"))) laserQ.ConVar = "cw_laser_quality" laserQ:AddChoice("Normal") laserQ:AddChoice("High") laserQ.OnSelect = function(panel, index, value, data) laserQ:SetText("Laser quality:" .. CW2_GetLaserQualityText(tonumber(index))) RunConsoleCommand(laserQ.ConVar, tonumber(index)) end panel:AddItem(laserQ) local rtScope = vgui.Create("DComboBox", panel) rtScope:SetText("RT scope quality: " .. CustomizableWeaponry:getRenderTargetText(GetConVarNumber("cw_rt_scope_quality"))) rtScope.ConVar = "cw_rt_scope_quality" for key, data in ipairs(CustomizableWeaponry.renderTargetSizes) do rtScope:AddChoice(data.text) end rtScope.OnSelect = function(panel, index, value, data) index = tonumber(index) rtScope:SetText("RT scope quality: " .. CustomizableWeaponry:getRenderTargetText(index)) local prevQuality = GetConVarNumber(rtScope.ConVar) RunConsoleCommand(rtScope.ConVar, index) local wepBase = weapons.GetStored("cw_base") if prevQuality ~= tonumber(index) then -- only re-create the render target in case we changed the quality wepBase:initRenderTarget(CustomizableWeaponry:getRenderTargetSize(index)) end end panel:AddItem(rtScope) panel:AddControl("Label", {Text = "Misc"}) panel:AddControl("CheckBox", {Label = "Custom weapon origins?", Command = "cw_alternative_vm_pos"}) panel:AddControl("Button", {Label = "Drop CW 2.0 weapon", Command = "cw_dropweapon"}) end local function CW2_AdminPanel(panel) if not LocalPlayer():IsAdmin() then panel:AddControl("Label", {Text = "Not an admin - don't look here."}) return end local checkBox = "CheckBox" local baseText = "ON SPAWN: Give " local questionMark = "?" panel:AddControl(checkBox, {Label = "Keep attachments after dying?", Command = "cw_keep_attachments_post_death"}) for k, v in ipairs(CustomizableWeaponry.registeredAttachments) do if v.displayName and v.clcvar then panel:AddControl(checkBox, {Label = baseText .. v.displayName .. questionMark, Command = v.clcvar}) end end panel:AddControl("Button", {Label = "Apply Changes", Command = "cw_applychanges"}) end local function CW2_PopulateToolMenu() spawnmenu.AddToolMenuOption("Utilities", "CW 2.0 SWEPs", "CW 2.0 Client", "Client", "", "", CW2_ClientsidePanel) spawnmenu.AddToolMenuOption("Utilities", "CW 2.0 SWEPs", "CW 2.0 Admin", "Admin", "", "", CW2_AdminPanel) end hook.Add("PopulateToolMenu", "CW2_PopulateToolMenu", CW2_PopulateToolMenu)
gpl-3.0
LaFamiglia/Illarion-Content
npc/base/consequence/warp.lua
4
1102
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local class = require("base.class") local consequence = require("npc.base.consequence.consequence") local _warp_helper local warp = class(consequence, function(self, x, y, z) consequence:init(self) self["x"] = tonumber(x) self["y"] = tonumber(y) self["z"] = tonumber(z) self["perform"] = _warp_helper end) function _warp_helper(self, npcChar, player) player:warp(position(self.x,self.y,self.z)) end return warp
agpl-3.0
bsmr-games/lipsofsuna
data/lipsofsuna/core/objects/object-chunk-manager.lua
1
2787
--- Implements partitioning and swapping of map objects. -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module core.objects.object_chunk_manager -- @alias ObjectChunkManager local Class = require("system/class") local ChunkManager = require("system/chunk-manager") local ObjectChunk = require("core/objects/object-chunk") local ObjectChunkLoader = require("core/objects/object-chunk-loader") local Program = require("system/core") local Time = require("system/time") --- Implements partitioning and swapping of map objects. -- @type ObjectChunkManager local ObjectChunkManager = Class("ObjectChunkManager", ChunkManager) --- Creates a new sector manager. -- @param clss ObjectChunkManager class. -- @param manager Object manager. -- @param chunk_size Chunk size. -- @param grid_size Grid size. -- @return ObjectChunkManager. ObjectChunkManager.new = function(clss, manager, chunk_size, grid_size) local create = function(m, x, z) return ObjectChunk(m, x, z) end local self = ChunkManager.new(clss, chunk_size, grid_size, create) self.manager = manager return self end --- Increases the timestamp of the sectors inside the given sphere. -- @param self ObjectChunkManager. -- @param point Position vector, in world units. -- @param radius Refresh radius, in world units. ObjectChunkManager.refresh = function(self, point, radius) local x0,z0,x1,z1 = self:get_chunk_xz_range_by_point(point, radius or 10) for x = x0,x1 do for z = z0,z1 do local id = self:get_chunk_id_by_xz(x, z) local chunk = self.chunks[id] if not chunk then self:load_chunk(x, z) else chunk.time = Time:get_secs() end end end end --- Saves all active sectors to the database. -- @param self ObjectChunkManager. ObjectChunkManager.save_world = function(self) if not self.database then return end self.database:query("BEGIN TRANSACTION;") for k,v in pairs(self.chunks) do v:save() end self.database:query("END TRANSACTION;") end --- Waits for a sector to finish loading. -- @param self ObjectChunkManager. -- @param id Chunk ID. ObjectChunkManager.wait_sector_load = function(self, id) local chunk = self.chunks[sector] if not chunk then return end if not chunk.loader then return end chunk.loader:finish() chunk.loader = nil end --- Gets the idle time of the chunk. -- @param self ObjectChunkManager. -- @param id Chunk ID. -- @return Idle time in seconds. ObjectChunkManager.get_sector_idle = function(self, id) local chunk = self.chunks[sector] if not chunk then return end return Time:get_secs() - chunk.time end return ObjectChunkManager
gpl-3.0
Noltari/luci
protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua
2
4048
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache 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", ListValue, "ipv6", translate("Obtain IPv6-Address"), translate("Enable IPv6 negotiation on the PPP link")) ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" 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 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:set(section, "keepalive", "0") end end keepalive_interval.remove = keepalive_interval.write keepalive_failure.write = keepalive_interval.write keepalive_failure.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" host_uniq = section:taboption("advanced", Value, "host_uniq", translate("Host-Uniq tag content"), translate("Raw hex-encoded bytes. Leave empty unless your ISP require this")) host_uniq.placeholder = translate("auto") host_uniq.datatype = "hexstring" 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
LaFamiglia/Illarion-Content
monster/race_10_mummy/id_110_king.lua
1
1560
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 110, Dead King, Level: 7, Armourtype: medium, Weapontype: slashing local base = require("monster.base.base") local mageBehaviour = require("monster.base.behaviour.mage") local monstermagic = require("monster.base.monstermagic") local mummies = require("monster.race_10_mummy.base") local M = mummies.generateCallbacks() local orgOnSpawn = M.onSpawn function M.onSpawn(monster) if orgOnSpawn ~= nil then orgOnSpawn(monster) end base.setColor{monster = monster, target = base.SKIN_COLOR, red = 255, green = 255, blue = 120} end local magic = monstermagic() magic.addWarping{probability = 0.15, usage = magic.ONLY_NEAR_ENEMY} magic.addSummon{probability = 0.03, monsters = {103, 593, 536}} -- summon mummy, skeleton and scarab magic.addVioletFlame{probability = 0.02, damage = {from = 1500, to = 2500}} M = magic.addCallbacks(M) return mageBehaviour.addCallbacks(magic, M)
agpl-3.0
BHYCHIK/tntlua
spammerdb.lua
5
2479
-- spammerdb.lua local function get_value(flags, stype) return math.floor(flags / (4 ^ stype)) % 4 end local function set_value(v, stype, old_flags) return old_flags + v * 4 ^ stype end function spammerdb_get(userid, stype, ...) -- client sends integers encoded as BER-strings userid = box.unpack('i', userid) stype = box.unpack('i', stype) local emails = {...} for i, email in ipairs(emails) do if #email > 0 then local tuple = box.select(0, 0, userid, email) if tuple ~= nil then local flags = string.byte(tuple[2]) -- box.unpack('b', tuple[2]) local v = get_value(flags, stype) if v > 0 then return { box.pack('b', v), box.pack('i', i) } end end end end return { box.pack('b', 0), box.pack('i', 0) } end function spammerdb_getall(userid) -- client sends integers encoded as BER-strings userid = box.unpack('i', userid) local result = {} local tuples = { box.select(0, 0, userid) } for _, tuple in pairs(tuples) do local flags = string.byte(tuple[2]) -- box.unpack('b', tuple[2]) for stype = 0, 3 do local v = get_value(flags, stype) if v > 0 then table.insert(result, { tuple[1], box.pack('b', v), stype }) end end end return unpack(result) end function spammerdb_set(userid, stype, email, value) -- client sends integers encoded as BER-strings userid = box.unpack('i', userid) stype = box.unpack('i', stype) value = string.byte(value) --box.unpack('b', value) local tuple = box.select(0, 0, userid, email) if tuple ~= nil then local flags = string.byte(tuple[2]) -- box.unpack('b', tuple[2]) local v = get_value(flags, stype) -- mark already exists - do nothing if v == value then return end local new_flags = set_value(value - v, stype, flags) if new_flags == 0 then -- last spam mark for this email deleted box.delete(0, userid, email) else box.replace(0, userid, email, box.pack('b', new_flags)) end elseif value > 0 then local new_flags = set_value(value, stype, 0) box.insert(0, userid, email, box.pack('b', new_flags)) end end -- -- Delete all spammerdb lines for user @userid. -- Returns flag of deletion success. -- function spammerdb_delall(userid) -- client sends integers encoded as BER-strings userid = box.unpack('i', userid) local tuples = { box.select(0, 0, userid) } for _, tuple in pairs(tuples) do box.delete(0, userid, tuple[1]) end return box.pack('i', #tuples) end
bsd-2-clause
pigparadise/skynet
service/datacenterd.lua
8
1949
local skynet = require "skynet" local command = {} local database = {} local wait_queue = {} local mode = {} local function query(db, key, ...) if key == nil then return db else return query(db[key], ...) end end function command.QUERY(key, ...) local d = database[key] if d ~= nil then return query(d, ...) end end local function update(db, key, value, ...) if select("#",...) == 0 then local ret = db[key] db[key] = value return ret, value else if db[key] == nil then db[key] = {} end return update(db[key], value, ...) end end local function wakeup(db, key1, ...) if key1 == nil then return end local q = db[key1] if q == nil then return end if q[mode] == "queue" then db[key1] = nil if select("#", ...) ~= 1 then -- throw error because can't wake up a branch for _,response in ipairs(q) do response(false) end else return q end else -- it's branch return wakeup(q , ...) end end function command.UPDATE(...) local ret, value = update(database, ...) if ret ~= nil or value == nil then return ret end local q = wakeup(wait_queue, ...) if q then for _, response in ipairs(q) do response(true,value) end end end local function waitfor(db, key1, key2, ...) if key2 == nil then -- push queue local q = db[key1] if q == nil then q = { [mode] = "queue" } db[key1] = q else assert(q[mode] == "queue") end table.insert(q, skynet.response()) else local q = db[key1] if q == nil then q = { [mode] = "branch" } db[key1] = q else assert(q[mode] == "branch") end return waitfor(q, key2, ...) end end skynet.start(function() skynet.dispatch("lua", function (_, _, cmd, ...) if cmd == "WAIT" then local ret = command.QUERY(...) if ret ~= nil then skynet.ret(skynet.pack(ret)) else waitfor(wait_queue, ...) end else local f = assert(command[cmd]) skynet.ret(skynet.pack(f(...))) end end) end)
mit
adminomega/exterme-orginal
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
spark0511/blueteambot
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
chegenipapi/sajadchegen
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
LaFamiglia/Illarion-Content
alchemy/base/alchemy.lua
1
38279
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- ds_base_alchemy.lua local common = require("base.common") local licence = require("base.licence") local M = {} function M.InitAlchemy() InitPlantSubstance() InitPotions() end function InitPlantSubstance() setPlantSubstance(15,"","") setPlantSubstance(80,"","") setPlantSubstance(154,"","") setPlantSubstance(200,"","") setPlantSubstance(201,"","") setPlantSubstance(259,"","") setPlantSubstance(290,"","") setPlantSubstance(302,"","") setPlantSubstance(772,"","") setPlantSubstance(778,"","") setPlantSubstance(1207,"","") setPlantSubstance(2493,"","") setPlantSubstance(138,"","Dracolin") setPlantSubstance(146,"","Echolon") setPlantSubstance(152,"Echolon","") setPlantSubstance(754,"","Caprazin") setPlantSubstance(755,"","Illidrium") setPlantSubstance(756,"Caprazin","") setPlantSubstance(757,"Dracolin","") setPlantSubstance(758,"Adrazin","") setPlantSubstance(760,"","Fenolin") setPlantSubstance(761,"Illidrium","") setPlantSubstance(762,"","Orcanol") setPlantSubstance(764,"","Adrazin") setPlantSubstance(765,"Hyperborelium","") setPlantSubstance(766,"","Hyperborelium") setPlantSubstance(768,"Orcanol","") setPlantSubstance(769,"Fenolin","") setPlantSubstance(81,"Illidrium","Orcanol") setPlantSubstance(133,"Adrazin","Orcanol") setPlantSubstance(134,"Fenolin","Illidrium") setPlantSubstance(135,"Fenolin","Adrazin") setPlantSubstance(136,"Adrazin","Fenolin") setPlantSubstance(137,"Echolon","Illidrium") setPlantSubstance(140,"Fenolin","Hyperborelium") setPlantSubstance(141,"Caprazin","Echolon") setPlantSubstance(142,"Hyperborelium","Dracolin") setPlantSubstance(143,"Illidrium","Dracolin") setPlantSubstance(144,"Adrazin","Dracolin") setPlantSubstance(145,"Hyperborelium","Orcanol") setPlantSubstance(147,"Echolon","Adrazin") setPlantSubstance(148,"Echolon","Caprazin") setPlantSubstance(149,"Hyperborelium","Echolon") setPlantSubstance(151,"Caprazin","Dracolin") setPlantSubstance(153,"Fenolin","Caprazin") setPlantSubstance(155,"Illidrium","Echolon") setPlantSubstance(156,"Orcanol","Adrazin") setPlantSubstance(158,"Illidrium","Fenolin") setPlantSubstance(159,"Dracolin","Hyperborelium") setPlantSubstance(160,"Adrazin","Echolon") setPlantSubstance(161,"Orcanol","Hyperborelium") setPlantSubstance(162,"Hyperborelium","Fenolin") setPlantSubstance(163,"Orcanol","Illidrium") setPlantSubstance(199,"Caprazin","Orcanol") setPlantSubstance(388,"Caprazin","Fenolin") setPlantSubstance(752,"Orcanol","Caprazin") setPlantSubstance(753,"Dracolin","Adrazin") setPlantSubstance(759,"Dracolin","Illidrium") setPlantSubstance(763,"Dracolin","Caprazin") setPlantSubstance(767,"Echolon","Hyperborelium") end function setPlantSubstance(id, plusSubstance, minusSubstance) if plantList == nil then plantList = {} end plantList[id] = {plusSubstance, minusSubstance} end function M.getPlantSubstance(id, User) if not plantList[id] then return false end local plus, minus if plantList[id][1] ~= nil then plus = plantList[id][1] end if plantList[id][2] ~= nil then minus = plantList[id][2] end return plus, minus end -- the list of possible potions effects potionsList = {}; ingredientsList = {} M.potionName = {} idList = {} -- on reload, this function is called -- setPotion(effect id, stock data, gemdust ,Herb1, Herb2, Herb3, Herb4, Herb5, Herb6, Herb7, Herb8) -- every effect id is only used once! -- gemdust is the id of the gemdust used. indirectly, the potion kind -- stock data is the concentration of the active substances put together in the following order: Adrazin, Illidrium, Caprazin, Hyperborelium, Echolon, Dracolin, Orcanol, Fenolin -- Herb1...Herb8 are optional. If you use only x Herbs and x < 8 just write false for the rest -- Example: setPotion(15, 459, 95554553, 133, 15, 81, false, false, false, false, false) -- for an better overview, we save the names in an own list function InitPotions() -- body liquid potions M.potionName[10] = {"Dragon Breath","Drachenatem"} setPotion(10, 450, 58325631, 755, 755, 141, 141, 141, 146, false, false) -- done -- body liquid end -- bombs M.potionName[301] = {"Small Explosion","Kleine Explosion"} setPotion(301, 446, 34374416, 755, 755, 755, 146, 141 ,141, 141, 133) M.potionName[302] = {"Medium Explosion","Mittlere Explosion"} setPotion(302, 446, 44156426, 755, 755, 146, 146, 141 ,141, 141, 133) M.potionName[304] = {"Big Explosion","Große Explosion"} setPotion(304, 446, 22446419, 755, 146, 146, 146, 141 ,141, 141, 133) -- done M.potionName[306] = {"Small Mana Annihilator","Kleiner Manaannihilator"} setPotion(306, 446, 22856451, 138, 138, 138, 146, 134, 134, 134, 133) M.potionName[307] = {"Medium Mana Annihilator","Mittlerer Manaannihilator"} setPotion(307, 446, 21957432, 138, 138, 146, 146, 134, 134, 134, 133) M.potionName[309] = {"Big Mana Annihilator","Großer Manaannihilator"} setPotion(309, 446, 22955451, 138, 146, 146, 146, 134, 134, 134, 133) M.potionName[311] = {"Small Nutrition Annihilator","Kleiner Nahrungsannihilator"} setPotion(311, 446, 26843821, 754, 754, 754, 146, 135, 135, 135, 133) M.potionName[312] = {"Medium Nutrition Annihilator","Mittlerer Nahrungsannihilator"} setPotion(312, 446, 15873523, 754, 754, 146, 146, 135, 135, 135, 133) M.potionName[314] = {"Big Nutrition Annihilator","Großer Nahrungsannihilator"} setPotion(314, 446, 15783424, 754, 146, 146, 146, 135, 135, 135, 133) M.potionName[316] = {"Small Slime Barrier","Kleine Schleimbarriere"} setPotion(316, 446, 86386546, 140, 140, 140, 152, 146, false, false, false) M.potionName[317] = {"Big Slime Barrier","Große Schleimbarriere"} setPotion(317, 446, 76576456, 140, 140, 140, 140, 152, 152, 146, 146) M.potionName[318] = {"Lennier's Dream","Lenniers Traum"} setPotion(318, 446, 57932798, 765,146,146,146,148,15,151,764) -- bombs end -- quality raiser M.potionName[400] = {"Quality Raiser for Potions based on Emerald Powder","Qualitätsheber für Tränke auf Smaragdstaubbasis"} setPotion(400, 448, 69487354, 763, 768, 133, 133, 133, false, false, false) M.potionName[401] = {"Quality Raiser for Potions based on Ruby Powder","Qualitätsheber für Tränke auf Rubinstaubbasis"} setPotion(401, 448, 64966357, 763, 758, 133, 133, 133, false, false, false) M.potionName[402] = {"Quality Raiser for Potions based on Sapphire Powder","Qualitätsheber für Tränke auf Saphirstaubbasis"} setPotion(402, 448, 62497378, 763, 146, 133, 133, 133, false, false, false) M.potionName[403] = {"Quality Raiser for Potions based on Obsidian Powder","Qualitätsheber für Tränke auf Obsidianstaubbasis"} setPotion(403, 448, 64489753, 763, 766, 133, 133, 133, false, false, false) M.potionName[404] = {"Quality Raiser for Potions based on Amethyst Powder","Qualitätsheber für Tränke auf Amethyststaubbasis"} setPotion(404, 448, 67645954, 763, 152, 133, 133, 133, false, false, false) M.potionName[405] = {"Quality Raiser for Potions based on Topaz Powder","Qualitätsheber für Tränke auf Topasstaubbasis"} setPotion(405, 448, 64873297, 763, 761, 133, 133, 133, false, false, false) M.potionName[406] = {"Quality Raiser for Potions based on Diamond Powder","Qualitätsheber für Tränke auf Diamantstaubbasis"} setPotion(406, 448, 64763659, 763, 756, 133, 133, 133, false, false, false) -- quality raiser end -- transformation potions M.potionName[500] = {"Shape Shifter Male Human","Verwandler Männlicher Mensch"} setPotion(500, 449, 64135842, 766, 161, 754, 752, false, false, false, false) M.potionName[501] = {"Shape Shifter Female Human","Verwandler Weiblicher Mensch"} setPotion(501, 449, 64135842, 766, 162, 754, 752, false, false, false, false) M.potionName[510] = {"Shape Shifter Male Dwarf","Verwandler Männlicher Zwerg"} setPotion(510, 449, 74385866, 766, 161, 762, 759, false, false, false, false) M.potionName[511] = {"Shape Shifter Female Dwarf","Verwandler Weiblicher Zwerg"} setPotion(511, 449, 74385866, 766, 162, 762, 759, false, false, false, false) M.potionName[520] = {"Shape Shifter Male Halfling","Verwandler Männlicher Halbling"} setPotion(520, 449, 84452136, 766, 161, 765, 151, false, false, false, false) M.potionName[521] = {"Shape Shifter Female Halfling","Verwandler Weiblicher Halbling"} setPotion(521, 449, 84452136, 766, 162, 765, 151, false, false, false, false) M.potionName[530] = {"Shape Shifter Male Elf","Verwandler Männlicher Elf"} setPotion(530, 449, 87372749, 766, 161, 756, 753, false, false, false, false) M.potionName[531] = {"Shape Shifter Female Elf","Verwandler Weiblicher Elf"} setPotion(531, 449, 87372749, 766, 162, 756, 753, false, false, false, false) M.potionName[540] = {"Shape Shifter Male Orc","Verwandler Männlicher Ork"} setPotion(540, 449, 63584498, 766, 161, 764, 763, false, false, false, false) M.potionName[541] = {"Shape Shifter Female Orc","Verwandler Weiblicher Ork"} setPotion(541, 449, 63584498, 766, 162, 764, 763, false, false, false, false) M.potionName[550] = {"Shape Shifter Male Lizardman","Verwandler Männlicher Echsenmensch"} setPotion(550, 449, 23417592, 766, 161, 760, 767, false, false, false, false) M.potionName[551] = {"Shape Shifter Female Echsenmensch","Verwandler Weiblicher Echsenmensch"} setPotion(551, 449, 23417592, 766, 162, 760, 767, false, false, false, false) M.potionName[560] = {"Shape Shifter Dog","Verwandler Hund"} setPotion(560, 449, 31397191, 766, 152, 81, 81, 762, false, false, false) -- transformation potions end --language potions M.potionName[600] = {"Language Potion Common Language","Sprachtrank Handelssprache"} setPotion(600, 452, 26727482, 756, 765, 135, false, false, false, false, false) M.potionName[601] = {"Language Potion Human Language","Sprachtrank Menschensprache"} setPotion(601, 452, 28751379, 756, 765, 769, false, false, false, false, false) M.potionName[602] = {"Language Potion Dwarf Language","Sprachtrank Zwergensprache"} setPotion(602, 452, 23369487, 756, 765, 762, false, false, false, false, false) M.potionName[603] = {"Language Potion Elf Language","Sprachtrank Elfensprache"} setPotion(603, 452, 51397674, 756, 765, 138, false, false, false, false, false) M.potionName[604] = {"Language Potion Lizard Language","Sprachtrank Echsensprache"} setPotion(604, 452, 85612648, 756, 765, 761, false, false, false, false, false) M.potionName[605] = {"Language Potion Orc Language","Sprachtrank Orksprache"} setPotion(605, 452, 58641767, 756, 765, 764, false, false, false, false, false) M.potionName[606] = {"Language Potion Halfling Language","Sprachtrank Halblingssprache"} setPotion(606, 452, 56612824, 756, 765, 768, false, false, false, false, false) M.potionName[607] = {"Language Potion Ancient Language","Sprachtrank Antike Sprache"} setPotion(607, 452, 25796346, 756, 756, 765, 152, false, false, false, false) -- language potions end end function setPotion(effect,gemdust,stock,essenceHerb1,essenceHerb2,essenceHerb3,essenceHerb4,essenceHerb5,essenceHerb6,essenceHerb7,essenceHerb8) table.insert(idList,effect) setPotionEffect(effect,gemdust,stock,essenceHerb1,essenceHerb2,essenceHerb3,essenceHerb4,essenceHerb5,essenceHerb6,essenceHerb7,essenceHerb8) setPotionIngredients(effect,gemdust,stock,essenceHerb1,essenceHerb2,essenceHerb3,essenceHerb4,essenceHerb5,essenceHerb6,essenceHerb7,essenceHerb8) end --- Set the effect of a potion -- @param resultingEffect the resulting effect of the potion -- @param ... the components effecting the potion one by one function setPotionEffect(resultingEffect, ...) local currentList = potionsList; local args = table.pack(...) for i=1,args.n do if (currentList[args[i]] == nil) then currentList[args[i]] = {}; end; currentList = currentList[args[i]]; end; currentList[0] = resultingEffect; end; function setPotionIngredients(effect,gemdust,stock,essenceHerb1,essenceHerb2,essenceHerb3,essenceHerb4,essenceHerb5,essenceHerb6,essenceHerb7,essenceHerb8) if ingredientsList == nil then ingredientsList = {} end ingredientsList[effect] = {gemdust,stock,essenceHerb1,essenceHerb2,essenceHerb3,essenceHerb4,essenceHerb5,essenceHerb6,essenceHerb7,essenceHerb8} end --- Get the effect of a potion -- @param ... the components effecting the potion one by one -- @return the resulting effect of the potion function getPotion(...) local currentList = potionsList; local args = table.pack(...) for i=1,args.n do if (currentList[args[i]] == nil) then return 0; end; currentList = currentList[args[i]]; end; if (currentList[0] == nil) then return 0; end; return currentList[0]; end; function M.getIngredients(effectId) if ingredientsList[effectId] == nil then return else return ingredientsList[effectId] end end --stock,sapphire ,ruby,emerald,obsidian ,amethyst,topaz,diamant gemDustList = {"non",446 ,447 ,448 ,449 ,450 ,451 ,452} gemList = {"non",284 ,46 ,45 ,283 ,197 ,198 ,285} cauldronList = {1012 ,1011 ,1016,1013 ,1009 ,1015 ,1018 ,1017} M.bottleList = {331 ,327 ,59 ,165 ,329 ,166 ,167 ,330} --Qualitätsbezeichnungen M.qListDe={"fürchterliche","schlechte","schwache","leicht schwache","durchschnittliche","gute","sehr gute","großartige","hervorragende"}; M.qListEn={"awful","bad","weak","slightly weak","average","good","very good","great","outstanding"}; -- Liste der Wirkstoffnamen M.wirkstoff = {}; M.wirkung_de = {}; M.wirkung_en = {}; M.wirkstoff[1] = "Adrazin"; M.wirkstoff[2] = "Illidrium"; M.wirkstoff[3] = "Caprazin"; M.wirkstoff[4] = "Hyperborelium"; M.wirkstoff[5] = "Echolon"; M.wirkstoff[6] = "Dracolin"; M.wirkstoff[7] = "Orcanol"; M.wirkstoff[8] = "Fenolin"; M.wirkung_de[1] = "gesättigte Anreicherung"; M.wirkung_de[2] = "eine sehr ausgeprägte Menge"; M.wirkung_de[3] = "merklich"; M.wirkung_de[4] = "schwache Konzentration"; M.wirkung_de[5] = "kein"; M.wirkung_de[6] = "geringe Mengen"; M.wirkung_de[7] = "etwas"; M.wirkung_de[8] = "konzentriertes"; M.wirkung_de[9] = "hoch toxisches"; M.wirkung_en[1] = "saturated solution"; M.wirkung_en[2] = "dominant marked"; M.wirkung_en[3] = "distinctive"; M.wirkung_en[4] = "slightly marked"; M.wirkung_en[5] = "no"; M.wirkung_en[6] = "slightly pronounced"; M.wirkung_en[7] = "enriched"; M.wirkung_en[8] = "dominant pronounced"; M.wirkung_en[9] = "highly toxic"; --Wirkungen auf Attribute --Reihe 1 attr_r1 = {}; untererGrenzwert = {}; obererGrenzwert = {}; attr_r1[1] ="hitpoints"; untererGrenzwert[1] = 0; obererGrenzwert[1] = 10000; attr_r1[2] ="body_height"; untererGrenzwert[2] = 35; obererGrenzwert[2] = 84; attr_r1[3] ="foodlevel"; untererGrenzwert[3] = 0; obererGrenzwert[3] = 50000; attr_r1[4] ="luck" ; untererGrenzwert[4] = 0; obererGrenzwert[4] = 100; attr_r1[5] ="attitude"; untererGrenzwert[5] = 0; obererGrenzwert[5] = 100; attr_r1[6] ="poisonvalue"; untererGrenzwert[6] = 0; obererGrenzwert[6] = 10000; attr_r1[7] ="mental capacity"; untererGrenzwert[7] = 0; obererGrenzwert[7] = 2400; attr_r1[8] ="mana"; untererGrenzwert[8] = 0; obererGrenzwert[8] = 10000; --Reihe 2 attr_r2 = {}; attr_r2[1] ="strength"; attr_r2[2] ="perception"; attr_r2[3] ="dexterity"; attr_r2[4] ="intelligence"; attr_r2[5] ="essence"; attr_r2[6] ="willpower"; attr_r2[7] ="constitution"; attr_r2[8] ="agility"; taste = {}; taste[0] ={"fruchtig","herb" ,"bitter" ,"faulig" ,"sauer" ,"salzig" ,"scharf" ,"süß"}; taste[1] ={"fruity" ,"tartly" ,"bitter" ,"putrefactive","sour" ,"salty" ,"hot" ,"sweet"}; -- ------------------------------------------------------------------------------- function M.CheckAttrRow(User,dataZList) local retVal = true if dataZList[9] == 0 then -- Attributsreihe 1 soll angewandt werden else -- Attributsreihe 2 soll angewandt werden retVal = false end return retVal end -- ------------------------------------------------------------------------------- function M.ImpactRow1(User,dataZList) for i=1,8 do if dataZList[i] < 4 then User:inform(dataZList[i].." Vor-Wirkung R1 : "..attr_r1[i].." : "..User:increaseAttrib(attr_r1[i],0 )) User:setAttrib(attr_r1[i],(User:increaseAttrib(attr_r1[i],0)*(dataZList[i]*30/100))) User:inform("Nach-Wirkung R1: "..attr_r1[i].." : "..User:increaseAttrib(attr_r1[i],0 )) elseif dataZList[i] > 5 then User:inform(dataZList[i].." Vor-Wirkung R1 : "..attr_r1[i].." : "..User:increaseAttrib(attr_r1[i],0 )) local dasIstWirkung = math.floor(User:increaseAttrib(attr_r1[i],0)+(User:increaseAttrib(attr_r1[i],0)*(dataZList[i]-5)*10/100)) if dasIstWirkung > obererGrenzwert[i] then dasIstWirkung = obererGrenzwert[i] end User:setAttrib(attr_r1[i],dasIstWirkung) User:inform("Nach-Wirkung R1: "..attr_r1[i].." : "..User:increaseAttrib(attr_r1[i],0 )) end end --User:inform("debug 13") end -- -------------------------------------------------------------------------------- function M.SplitData(User,theData) local myData local dataZList = {} for i=1,8 do myData = math.floor(theData/(10^(8-i))) myData = myData - (math.floor(myData/10))*10 dataZList[i] = myData end return dataZList end function M.DataListToNumber(dataList) local theData = 0 for i=1,8 do theData = theData + dataList[i]*10^(8-i) end return theData end function M.SubstanceDatasToList(theItem) local substanceList = {} for i=1,8 do local concentration = tonumber(theItem:getData(M.wirkstoff[i].."Concentration")) if concentration ~= nil then table.insert(substanceList,concentration) end end return substanceList end -- probably, works only with lists containing no other lists -- todo: make it also possibel to check lists containing list(s) function M.CheckListsIfEqual(ListOne,ListTwo) local check = true if #ListOne == #ListTwo then for i=1,#ListOne do if ListOne[i] ~= ListTwo[i] then check = false break end end else check = false end return check end function M.generateTasteMessage(Character,dataZList) local textDe = "Der Trank schmeckt "; local textEn = "The potion tastes "; local anyTaste = false; local usedTastes = {}; for i=1,8 do if dataZList[i] > 5 then if usedTastes[i]==nil or usedTastes[i]<dataZList[i] then usedTastes[i] = dataZList[i]; end anyTaste = true; elseif dataZList[i] < 5 then if usedTastes[9-i]==nil or usedTastes[9-i]<dataZList[i] then usedTastes[9-i] = dataZList[i]; end anyTaste = true; end end if not anyTaste then textDe = textDe .. "nach nichts."; textEn = textEn .. "like nothing."; else for i=1,8 do if usedTastes[i]~=nil then if usedTastes[i] > 8 or usedTastes[i] < 2 then textDe = textDe .. "sehr "; textEn = textEn .. "very "; elseif (usedTastes[i] < 7 and usedTastes[i] > 5) or (usedTastes[i] > 3 and usedTastes[i] < 5) then textDe = textDe .. "etwas "; textEn = textEn .. "slightly "; end textDe = textDe..taste[0][i]..", "; textEn = textEn..taste[1][i]..", "; end end textDe = string.sub(textDe, 0, -3); textDe = textDe.."."; textEn = string.sub(textEn, 0, -3); textEn = textEn.."."; end common.InformNLS(Character,textDe,textEn); end function M.CheckIfGemDust(itemId) local retVal for i,checkId in pairs(gemDustList) do if itemId == checkId then retVal = itemId break; end end return retVal end FOOD_NEEDED = 250 function M.checkFood(User) if not common.FitForHardWork(User, FOOD_NEEDED) then return false end return true end function M.lowerFood(User) common.GetHungry(User, FOOD_NEEDED) end function M.CheckIfPlant(itemId) if plantList[itemId] ~= nil or itemId == 157 then return true end return false end function M.CheckIfPotionBottle(SourceItem, User) local retVal for i,checkId in pairs(M.bottleList) do local theItem = SourceItem if theItem.id == checkId then retVal = theItem break; end end return retVal end function M.GetCauldronInfront(User,Item) local retVal Item = common.GetFrontItem(User) if (Item ~= nil) and (Item.id >= 1008) and (Item.id <= 1018) then retVal = Item end return retVal end function M.CheckIfAlchemist(User) if (User:getMagicType() ~= 3) then return false else return true end end function M.getBottleFromEffect(effectId) -- won't work with NORMAL primar and secundar attribute potins, since the both have 11111111 - 99999999 as a range for effect ids if (effectId >= 1) and (effectId <= 99) then return 166 elseif (effectId >= 100) and (effectId <= 199) then return 59 elseif (effectId >= 200) and (effectId <= 299) then return 167 elseif (effectId >= 300) and (effectId <= 399) then return 327 elseif (effectId >= 400) and (effectId <= 499) then return 165 elseif (effectId >= 500) and (effectId <= 599) then return 329 elseif (effectId >= 600) and (effectId <= 699) then return 330 end return end function M.RemoveEssenceBrew(Item) for i=1,8 do Item:setData("essenceHerb"..i,"") end end function M.RemoveStock(Item) for i=1,8 do Item:setData(M.wirkstoff[i].."Concentration","") end end function M.RemoveAll(Item) M.RemoveEssenceBrew(Item) M.RemoveStock(Item) Item:setData("potionEffectId","") Item:setData("potionQuality","") Item:setData("filledWith","") if (Item.id >= 1008) or (Item.id <= 1018) then Item.id = 1008 else Item.id = 164 end end function M.EmptyBottle(User,Bottle) if math.random(1,20) == 1 then world:erase(Bottle,1) -- bottle breaks common.InformNLS(User, "Die Flasche zerbricht.", "The bottle breaks.", Player.lowPriority) else if Bottle.number > 1 then -- if we empty a bottle (stock, potion or essence brew) it should normally never be a stack! but to be one the safe side, we check anyway User:createItem(164,1,333,nil) world:erase(Bottle,1) else M.RemoveAll(Bottle) Bottle.id = 164 Bottle.quality = 333 world:changeItem(Bottle) end end end function M.FillFromTo(fromItem,toItem) -- copies all datas (and quality and id) from fromItem to toItem for i=1,8 do toItem:setData(M.wirkstoff[i].."Concentration",fromItem:getData(M.wirkstoff[i].."Concentration")) toItem:setData("essenceHerb"..i,fromItem:getData("essenceHerb"..i)) end toItem:setData("filledWith",fromItem:getData("filledWith")) toItem:setData("potionEffectId",fromItem:getData("potionEffectId")) local quality = tonumber(fromItem:getData("potionQuality")) if quality == nil then quality = fromItem.quality end if toItem.id >= 1008 and toItem.id <= 1018 then toItem:setData("potionQuality",quality) else toItem.quality = quality end local reGem, reDust, reCauldron, reBottle if fromItem.id >= 1008 and fromItem.id <= 1018 then reGem, reDust, reCauldron, reBottle = M.GemDustBottleCauldron(nil, nil, fromItem.id, nil) else reGem, reDust, reCauldron, reBottle = M.GemDustBottleCauldron(nil, nil, nil, fromItem.id) end if toItem.id >= 1008 and toItem.id <= 1018 then toItem.id = reCauldron else toItem.id = reBottle end world:changeItem(toItem) end function M.CheckExplosionAndCleanList(User) local check = false if USER_EXPLOSION_LIST then if USER_EXPLOSION_LIST[User.id] == true then check = true USER_EXPLOSION_LIST[User.id] = nil end end return check end function M.CauldronDestruction(User,cauldron,effectId) if USER_EXPLOSION_LIST == nil then -- note: it's global! USER_EXPLOSION_LIST = {} end if (effectId < 1) or (effectId > 3) or (effectId == nil) then effectId = 1 end local textDE local textEN if effectId == 1 then world:gfx(1,cauldron.pos) world:makeSound(5,cauldron.pos) User:inform("Der Inhalt des Kessels verpufft.", "The substance in the cauldron blows out." ) elseif effectId == 2 then world:makeSound(5,cauldron.pos) world:gfx(36,cauldron.pos) User:inform("Deine letzte Handlung scheint den Inhalt des Kessels zerstört und zu einer Explosion geführt zu haben.", "Your last doing seems to have destroyed the substance in the cauldron and caused an explosion." ) local myVictims = world:getPlayersInRangeOf(cauldron.pos,1) -- we hurt everyone around the cauldron! for i=1,#myVictims do myVictims[i]:increaseAttrib("hitpoints",-3000) common.HighInformNLS(myVictims[i], "Du wirst von einer Explosion getroffen.", "You are hit by an explosion.") end end USER_EXPLOSION_LIST[User.id] = true M.RemoveAll(cauldron) cauldron.id = 1008 world:changeItem(cauldron) end function M.SetQuality(User,Item) -- skill has an influence of 75% on the mean local skillQuali = User:getSkill(Character.alchemy)*0.75 -- attributes have an influence of 25% on the mean (if the sum of the attributes is 54 or higher, we reach the maixmum influence) local attribCalc = (((User:increaseAttrib("essence",0) + User:increaseAttrib("perception",0) + User:increaseAttrib("intelligence",0) )/3))*5 local attribQuali = common.Scale(0,25,attribCalc) -- the mean local mean = common.Scale(1,9,(attribQuali + skillQuali)) -- normal distribution; mean determined by skill and attributes; fixed standard deviation local quality = Random.normal(mean, 4.5); quality = common.Limit(quality, 1, 9); Item:setData("potionQuality",quality*100+99)-- duarability is useless, we set it anway end function M.GemDustBottleCauldron(gemId, gemdustId, cauldronId, bottleId) -- this function returns matching gem id, gemdust id, cauldron id and bottle id -- only one parameter is needed; if there are more than one, only the first one will be taken into account local myList local myValue if gemId then myList = gemList myValue = gemId elseif gemdustId then myList = gemDustList myValue = gemdustId elseif cauldronId then myList = cauldronList myValue = cauldronId elseif bottleId then myList = M.bottleList myValue = bottleId else return end local reGem, reGemdust, reCauldron, reBottle for i=1,#myList do if myList[i] == myValue then reGem = gemList[i] reGemdust = gemDustList[i] reCauldron = cauldronList[i] reBottle = M.bottleList[i] break end end return reGem, reGemdust, reCauldron, reBottle end ---------------------------------------------------- -- combine of stock and essence brew to create a potion -- function is only called when item 331 is a stock or when a potion-bottle is an essence brew function M.CombineStockEssence( User, stock, essenceBrew) local cauldron = M.GetCauldronInfront(User) if cauldron then -- we get the gem dust used as an ingredient; and the new cauldron id we need later local reGem, ingredientGemdust, newCauldron, reBottle if cauldron:getData("filledWith") == "essenceBrew" then reGem, ingredientGemdust, newCauldron, reBottle = M.GemDustBottleCauldron(nil, nil, essenceBrew.id, nil) else reGem, ingredientGemdust, newCauldron, reBottle = M.GemDustBottleCauldron(nil, nil, nil, essenceBrew.id) end -- create our ingredients list local myIngredients = {} -- firstly, the gem dust which has been used (indirectly, that is the potion kind) myIngredients[1] = ingredientGemdust -- secondly, the stock local stockConc = "" for i=1,8 do local currentSubs = stock:getData(M.wirkstoff[i].."Concentration") if currentSubs == "" then currentSubs = 5 end stockConc = stockConc..currentSubs end myIngredients[2] = tonumber(stockConc) -- thirdly, the (at maximum) eight herbs of the essenceBrew for i=1,8 do if essenceBrew:getData("essenceHerb"..i) ~= "" then myIngredients[i+2] = tonumber(essenceBrew:getData("essenceHerb"..i)) else myIngredients[i+2] = false end end -- get the potion effect id local effectID if (myIngredients[3] == false) and (ingredientGemdust == 447 or ingredientGemdust == 450) then -- potion kind is primary or secondary attributes AND there was no plant in the essence brew -> stock concentration determines the effect effectID = stockConc else if ingredientGemdust == 447 then if myIngredients[3] == 136 and myIngredients[4] == 136 and myIngredients[5] == 761 and myIngredients[6] == 765 and myIngredients[7] == 159 then debug("stockCocn is "..stockConc) effectID = 59*100000000+stockConc debug("eefctID is "..effectID) else effectID = getPotion(myIngredients[1],myIngredients[2],myIngredients[3],myIngredients[4],myIngredients[5],myIngredients[6],myIngredients[7],myIngredients[8],myIngredients[9],myIngredients[10]) end else effectID = getPotion(myIngredients[1],myIngredients[2],myIngredients[3],myIngredients[4],myIngredients[5],myIngredients[6],myIngredients[7],myIngredients[8],myIngredients[9],myIngredients[10]) end end -- check if char is able to combine effectID = tonumber(effectID) if effectID >= 1000 and effectID <= 1999 then if User:getQuestProgress(effectID+1000) == 0 then User:inform("Du versuchst die Gebräue zu verbinden, doch sie scheinen sich nicht vermischen zu wollen. Scheinbar beherrscht du diesen Trank noch nicht richtig.", "You try to combine the brews but they just don't admix. It seem that you haven't learned how to create this potion properly.") return false end end -- delte old cauldron datas and add new ones M.RemoveAll(cauldron) M.SetQuality(User,cauldron) cauldron.id = newCauldron debug("effect id 2: "..effectID) cauldron:setData("potionEffectId", ""..effectID) cauldron:setData("filledWith", "potion") world:changeItem(cauldron) debug("effect id after adding: "..cauldron:getData("potionEffectId")) world:makeSound(13,cauldron.pos) world:gfx(52,cauldron.pos) -- and learn! User:learn(Character.alchemy, 80/2, 100) return true end end function M.FillIntoCauldron(User,SourceItem,cauldron,ltstate) -- function to fill stock, essencebrew or potion into a cauldron -- is the char an alchemist? local anAlchemist = M.CheckIfAlchemist(User,"Nur jene, die in die Kunst der Alchemie eingeführt worden sind, können hier ihr Werk vollrichten.","Only those who have been introduced to the art of alchemy are able to work here.") if not anAlchemist then return end if licence.licence(User) then --checks if user is citizen or has a licence return -- avoids crafting if user is neither citizen nor has a licence end if not M.checkFood(User) then return end if ( ltstate == Action.abort ) then common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.") return end if ( ltstate == Action.none ) then local actionDuration if (SourceItem:getData("filledWith") =="essenceBrew") and (cauldron:getData("filledWith") == "stock") then actionDuration = 80 -- when we combine a stock and an essence brew, it takes longer else actionDuration = 20 end User:startAction( actionDuration, 21, 5, 10, 45) return end if (SourceItem:getData("filledWith") =="essenceBrew") then -- essence brew should be filled into the cauldron -- water, essence brew or potion is in the cauldron; leads to a failure if cauldron:getData("filledWith") == "water" then M.CauldronDestruction(User,cauldron,1) elseif cauldron:getData("filledWith") == "essenceBrew" then M.CauldronDestruction(User,cauldron,2) elseif cauldron:getData("filledWith") == "potion" then if cauldron.id == 1013 then -- support potion alchemy.item.id_165_blue_bottle.SupportEssencebrew(User,cauldron,SourceItem) else M.CauldronDestruction(User,cauldron,2) end elseif cauldron:getData("filledWith") == "stock" then -- stock is in the cauldron; we call the combin function M.CombineStockEssence( User, cauldron, SourceItem) if check == false then return end else -- nothing in the cauldron, we just fill in the essence brew M.FillFromTo(SourceItem,cauldron) end elseif (SourceItem:getData("filledWith")=="potion") then -- potion should be filled into the cauldron -- water, essence brew, potion or stock is in the cauldron; leads to a failure if cauldron:getData("cauldronFilledWith") == "water" then M.CauldronDestruction(User,cauldron,1) elseif cauldron:getData("cauldronFilledWith") == "essenceBrew" then M.CauldronDestruction(User,cauldron,2) elseif cauldron:getData("filledWith") == "potion" then if cauldron.id == 1013 then -- support potion alchemy.item.id_165_blue_bottle.SupportPotion(User,cauldron,SourceItem) else M.CauldronDestruction(User,cauldron,2) end elseif cauldron:getData("filledWith") == "stock" then M.CauldronDestruction(User,cauldron,2) else -- nothing in the cauldron, we just fill in the potion M.FillFromTo(SourceItem,cauldron) world:changeItem(cauldron) end end M.EmptyBottle(User,SourceItem) end -- a bug led to a situation that some potions missed the "filledWith"-data -- this function will be called whenever seomething is done to a potion and set the proper data function M.repairPotion(Item) if tonumber(Item:getData("potionEffectId")) ~= nil then Item:setData("filledWith","potion") world:changeItem(Item) end end -- return a list containing values for actionStart --@param theIngredient can be: "water","bottle","plant","gemPowder","stock","essenceBrew","potion"; everything else gets a default value function M.GetStartAction(User, theIngredient, cauldron) local duration = 0 local gfxId = 0 local gfxIntervall = 0 local sfxId = 0 local sfxIntervall = 0 if theIngredient == "water" then -- bucket with water duration = 20 gfxId = 21 gfxIntervall = 5 sfxId = 0 sfxIntervall = 0 elseif theIngredient == "bottle" then -- empty bottle duration = 20 gfxId = 21 gfxIntervall = 5 sfxId = 15 sfxIntervall = 25 elseif theIngredient == "plant" then -- plant or rotten tree bark duration = 50 gfxId = 21 gfxIntervall = 5 sfxId = 15 sfxIntervall = 25 elseif theIngredient == "gemPowder" then -- gem powder duration = 80 gfxId = 21 gfxIntervall = 5 sfxId = 0 sfxIntervall = 0 elseif (theIngredient == "stock" and cauldron:getData("filledWith")=="essenceBrew") or (theIngredient =="essenceBrew" and cauldron:getData("filledWith")=="stock") then -- we combine stock and essence brew duration = 80 gfxId = 21 gfxIntervall = 5 sfxId = 10 sfxIntervall = 45 elseif theIngredient == "stock" or theIngredient == "essenceBrew" or theIngredient == "potion" then duration = 20 gfxId = 21 gfxIntervall = 5 sfxId = 10 sfxIntervall = 45 end return duration,gfxId,gfxIntervall,sfxId,sfxIntervall end return M
agpl-3.0
Ali-2h/wwefucker
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
MustaphaTR/OpenRA
mods/d2k/maps/atreides-02b/atreides02b-AI.lua
14
1137
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(9) }, normal = { DateTime.Seconds(2), DateTime.Seconds(7) }, hard = { DateTime.Seconds(1), DateTime.Seconds(5) } } HarkonnenInfantryTypes = { "light_inf" } ActivateAI = function() IdlingUnits[harkonnen] = { } DefendAndRepairBase(harkonnen, HarkonnenBase, 0.75, AttackGroupSize[Difficulty]) local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end local toBuild = function() return HarkonnenInfantryTypes end local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5 ProduceUnits(harkonnen, HBarracks, delay, toBuild, AttackGroupSize[Difficulty], attackThresholdSize) end
gpl-3.0
RedSnake64/openwrt-luci-packages
applications/luci-app-freifunk-widgets/luasrc/model/cbi/freifunk/widgets/widgets_overview.lua
68
1868
-- Copyright 2012 Manuel Munz <freifunk at somakoma dot de> -- Licensed to the public under the Apache License 2.0. local uci = require "luci.model.uci".cursor() local fs = require "nixio.fs" local utl = require "luci.util" m = Map("freifunk-widgets", translate("Widgets"), translate("Configure installed widgets.")) wdg = m:section(TypedSection, "widget", translate("Widgets")) wdg.addremove = true wdg.extedit = luci.dispatcher.build_url("admin/freifunk/widgets/widget/%s") wdg.template = "cbi/tblsection" wdg.sortable = true --[[ function wdg.create(...) local sid = TypedSection.create(...) luci.http.redirect(wdg.extedit % sid) end ]]-- local en = wdg:option(Flag, "enabled", translate("Enable")) en.rmempty = false --en.default = "0" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local tmpl = wdg:option(ListValue, "template", translate("Template")) local file for file in fs.dir("/usr/lib/lua/luci/view/freifunk/widgets/") do if file ~= "." and file ~= ".." then tmpl:value(file) end end local title = wdg:option(Value, "title", translate("Title")) title.rmempty = true local width = wdg:option(Value, "width", translate("Width")) width.rmempty = true local height = wdg:option(Value, "height", translate("Height")) height.rmempty = true local pr = wdg:option(Value, "paddingright", translate("Padding right")) pr.rmempty = true function m.on_commit(self) -- clean custom text files whose config has been deleted local dir = "/usr/share/customtext/" local active = {} uci:foreach("freifunk-widgets", "widget", function(s) if s["template"] == "html" then table.insert(active, s[".name"]) end end ) local file for file in fs.dir(dir) do local filename = string.gsub(file, ".html", "") if not utl.contains(active, filename) then fs.unlink(dir .. file) end end end return m
apache-2.0
luiseduardohdbackup/WarriorQuest
WarriorQuest/runtime/win32/Cocos2dConstants.lua
13
16741
cc = cc or {} cc.SPRITE_INDEX_NOT_INITIALIZED = 0xffffffff cc.TMX_ORIENTATION_HEX = 0x1 cc.TMX_ORIENTATION_ISO = 0x2 cc.TMX_ORIENTATION_ORTHO = 0x0 cc.Z_COMPRESSION_BZIP2 = 0x1 cc.Z_COMPRESSION_GZIP = 0x2 cc.Z_COMPRESSION_NONE = 0x3 cc.Z_COMPRESSION_ZLIB = 0x0 cc.BLEND_DST = 0x303 cc.BLEND_SRC = 0x1 cc.DIRECTOR_IOS_USE_BACKGROUND_THREAD = 0x0 cc.DIRECTOR_MAC_THREAD = 0x0 cc.DIRECTOR_STATS_INTERVAL = 0.1 cc.ENABLE_BOX2_D_INTEGRATION = 0x0 cc.ENABLE_DEPRECATED = 0x1 cc.ENABLE_GL_STATE_CACHE = 0x1 cc.ENABLE_PROFILERS = 0x0 cc.ENABLE_STACKABLE_ACTIONS = 0x1 cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0x0 cc.GL_ALL = 0x0 cc.LABELATLAS_DEBUG_DRAW = 0x0 cc.LABELBMFONT_DEBUG_DRAW = 0x0 cc.MAC_USE_DISPLAY_LINK_THREAD = 0x0 cc.MAC_USE_MAIN_THREAD = 0x2 cc.MAC_USE_OWN_THREAD = 0x1 cc.NODE_RENDER_SUBPIXEL = 0x1 cc.PVRMIPMAP_MAX = 0x10 cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 0x1 cc.SPRITE_DEBUG_DRAW = 0x0 cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0x0 cc.TEXTURE_ATLAS_USE_VAO = 0x1 cc.USE_L_A88_LABELS = 0x1 cc.ACTION_TAG_INVALID = -1 cc.DEVICE_MAC = 0x6 cc.DEVICE_MAC_RETINA_DISPLAY = 0x7 cc.DEVICEI_PAD = 0x4 cc.DEVICEI_PAD_RETINA_DISPLAY = 0x5 cc.DEVICEI_PHONE = 0x0 cc.DEVICEI_PHONE5 = 0x2 cc.DEVICEI_PHONE5_RETINA_DISPLAY = 0x3 cc.DEVICEI_PHONE_RETINA_DISPLAY = 0x1 cc.DIRECTOR_PROJECTION2_D = 0x0 cc.DIRECTOR_PROJECTION3_D = 0x1 cc.DIRECTOR_PROJECTION_CUSTOM = 0x2 cc.DIRECTOR_PROJECTION_DEFAULT = 0x1 cc.FILE_UTILS_SEARCH_DIRECTORY_MODE = 0x1 cc.FILE_UTILS_SEARCH_SUFFIX_MODE = 0x0 cc.FLIPED_ALL = 0xe0000000 cc.FLIPPED_MASK = 0x1fffffff cc.IMAGE_FORMAT_JPEG = 0x0 cc.IMAGE_FORMAT_PNG = 0x1 cc.ITEM_SIZE = 0x20 cc.LABEL_AUTOMATIC_WIDTH = -1 cc.LINE_BREAK_MODE_CHARACTER_WRAP = 0x1 cc.LINE_BREAK_MODE_CLIP = 0x2 cc.LINE_BREAK_MODE_HEAD_TRUNCATION = 0x3 cc.LINE_BREAK_MODE_MIDDLE_TRUNCATION = 0x5 cc.LINE_BREAK_MODE_TAIL_TRUNCATION = 0x4 cc.LINE_BREAK_MODE_WORD_WRAP = 0x0 cc.MAC_VERSION_10_6 = 0xa060000 cc.MAC_VERSION_10_7 = 0xa070000 cc.MAC_VERSION_10_8 = 0xa080000 cc.MENU_HANDLER_PRIORITY = -128 cc.MENU_STATE_TRACKING_TOUCH = 0x1 cc.MENU_STATE_WAITING = 0x0 cc.NODE_TAG_INVALID = -1 cc.PARTICLE_DURATION_INFINITY = -1 cc.PARTICLE_MODE_GRAVITY = 0x0 cc.PARTICLE_MODE_RADIUS = 0x1 cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS = -1 cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE = -1 cc.POSITION_TYPE_FREE = 0x0 cc.POSITION_TYPE_GROUPED = 0x2 cc.POSITION_TYPE_RELATIVE = 0x1 cc.PRIORITY_NON_SYSTEM_MIN = -2147483647 cc.PRIORITY_SYSTEM = -2147483648 cc.PROGRESS_TIMER_TYPE_BAR = 0x1 cc.PROGRESS_TIMER_TYPE_RADIAL = 0x0 cc.REPEAT_FOREVER = 0xfffffffe cc.RESOLUTION_MAC = 0x1 cc.RESOLUTION_MAC_RETINA_DISPLAY = 0x2 cc.RESOLUTION_UNKNOWN = 0x0 cc.TMX_TILE_DIAGONAL_FLAG = 0x20000000 cc.TMX_TILE_HORIZONTAL_FLAG = 0x80000000 cc.TMX_TILE_VERTICAL_FLAG = 0x40000000 cc.TEXT_ALIGNMENT_CENTER = 0x1 cc.TEXT_ALIGNMENT_LEFT = 0x0 cc.TEXT_ALIGNMENT_RIGHT = 0x2 cc.TEXTURE2_D_PIXEL_FORMAT_AUTO = 0x0 cc.TEXTURE2_D_PIXEL_FORMAT_BGR_A8888 = 0x1 cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888 = 0x2 cc.TEXTURE2_D_PIXEL_FORMAT_RG_B888 = 0x3 cc.TEXTURE2_D_PIXEL_FORMAT_RG_B565 = 0x4 cc.TEXTURE2_D_PIXEL_FORMAT_A8 = 0x5 cc.TEXTURE2_D_PIXEL_FORMAT_I8 = 0x6 cc.TEXTURE2_D_PIXEL_FORMAT_A_I88 = 0x7 cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444 = 0x8 cc.TEXTURE2_D_PIXEL_FORMAT_RGB5_A1 = 0x9 cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC4 = 0xa cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC4A = 0xb cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC2 = 0xc cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC2A = 0xd cc.TEXTURE2_D_PIXEL_FORMAT_ETC = 0xe cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT1 = 0xf cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT3 = 0x10 cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT5 = 0x11 cc.TEXTURE2_D_PIXEL_FORMAT_DEFAULT = 0x0 cc.TOUCHES_ALL_AT_ONCE = 0x0 cc.TOUCHES_ONE_BY_ONE = 0x1 cc.TRANSITION_ORIENTATION_DOWN_OVER = 0x1 cc.TRANSITION_ORIENTATION_LEFT_OVER = 0x0 cc.TRANSITION_ORIENTATION_RIGHT_OVER = 0x1 cc.TRANSITION_ORIENTATION_UP_OVER = 0x0 cc.UNIFORM_COS_TIME = 0x5 cc.UNIFORM_MV_MATRIX = 0x1 cc.UNIFORM_MVP_MATRIX = 0x2 cc.UNIFORM_P_MATRIX = 0x0 cc.UNIFORM_RANDOM01 = 0x6 cc.UNIFORM_SAMPLER = 0x7 cc.UNIFORM_SIN_TIME = 0x4 cc.UNIFORM_TIME = 0x3 cc.UNIFORM_MAX = 0x8 cc.VERTEX_ATTRIB_FLAG_COLOR = 0x2 cc.VERTEX_ATTRIB_FLAG_NONE = 0x0 cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = 0x7 cc.VERTEX_ATTRIB_FLAG_POSITION = 0x1 cc.VERTEX_ATTRIB_FLAG_TEX_COORDS = 0x4 cc.VERTEX_ATTRIB_COLOR = 0x1 cc.VERTEX_ATTRIB_MAX = 0x3 cc.VERTEX_ATTRIB_POSITION = 0x0 cc.VERTEX_ATTRIB_TEX_COORD = 0x2 cc.VERTEX_ATTRIB_TEX_COORDS = 0x2 cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM = 0x2 cc.VERTICAL_TEXT_ALIGNMENT_CENTER = 0x1 cc.VERTICAL_TEXT_ALIGNMENT_TOP = 0x0 cc.OS_VERSION_4_0 = 0x4000000 cc.OS_VERSION_4_0_1 = 0x4000100 cc.OS_VERSION_4_1 = 0x4010000 cc.OS_VERSION_4_2 = 0x4020000 cc.OS_VERSION_4_2_1 = 0x4020100 cc.OS_VERSION_4_3 = 0x4030000 cc.OS_VERSION_4_3_1 = 0x4030100 cc.OS_VERSION_4_3_2 = 0x4030200 cc.OS_VERSION_4_3_3 = 0x4030300 cc.OS_VERSION_4_3_4 = 0x4030400 cc.OS_VERSION_4_3_5 = 0x4030500 cc.OS_VERSION_5_0 = 0x5000000 cc.OS_VERSION_5_0_1 = 0x5000100 cc.OS_VERSION_5_1_0 = 0x5010000 cc.OS_VERSION_6_0_0 = 0x6000000 cc.ANIMATION_FRAME_DISPLAYED_NOTIFICATION = 'CCAnimationFrameDisplayedNotification' cc.CHIPMUNK_IMPORT = 'chipmunk.h' cc.ATTRIBUTE_NAME_COLOR = 'a_color' cc.ATTRIBUTE_NAME_POSITION = 'a_position' cc.ATTRIBUTE_NAME_TEX_COORD = 'a_texCoord' cc.SHADER_POSITION_COLOR = 'ShaderPositionColor' cc.SHADER_POSITION_LENGTH_TEXURE_COLOR = 'ShaderPositionLengthTextureColor' cc.SHADER_POSITION_TEXTURE = 'ShaderPositionTexture' cc.SHADER_POSITION_TEXTURE_A8_COLOR = 'ShaderPositionTextureA8Color' cc.SHADER_POSITION_TEXTURE_COLOR = 'ShaderPositionTextureColor' cc.SHADER_POSITION_TEXTURE_COLOR_ALPHA_TEST = 'ShaderPositionTextureColorAlphaTest' cc.SHADER_POSITION_TEXTURE_U_COLOR = 'ShaderPositionTexture_uColor' cc.SHADER_POSITION_U_COLOR = 'ShaderPosition_uColor' cc.UNIFORM_ALPHA_TEST_VALUE_S = 'CC_AlphaValue' cc.UNIFORM_COS_TIME_S = 'CC_CosTime' cc.UNIFORM_MV_MATRIX_S = 'CC_MVMatrix' cc.UNIFORM_MVP_MATRIX_S = 'CC_MVPMatrix' cc.UNIFORM_P_MATRIX_S = 'CC_PMatrix' cc.UNIFORM_RANDOM01_S = 'CC_Random01' cc.UNIFORM_SAMPLER_S = 'CC_Texture0' cc.UNIFORM_SIN_TIME_S = 'CC_SinTime' cc.UNIFORM_TIME_S = 'CC_Time' cc.PLATFORM_OS_WINDOWS = 0 cc.PLATFORM_OS_LINUX = 1 cc.PLATFORM_OS_MAC = 2 cc.PLATFORM_OS_ANDROID = 3 cc.PLATFORM_OS_IPHONE = 4 cc.PLATFORM_OS_IPAD = 5 cc.PLATFORM_OS_BLACKBERRY = 6 cc.PLATFORM_OS_NACL = 7 cc.PLATFORM_OS_EMSCRIPTEN = 8 cc.PLATFORM_OS_TIZEN = 9 cc.SCROLLVIEW_SCRIPT_SCROLL = 0 cc.SCROLLVIEW_SCRIPT_ZOOM = 1 cc.TABLECELL_TOUCHED = 2 cc.TABLECELL_HIGH_LIGHT = 3 cc.TABLECELL_UNHIGH_LIGHT = 4 cc.TABLECELL_WILL_RECYCLE = 5 cc.TABLECELL_SIZE_FOR_INDEX = 6 cc.TABLECELL_SIZE_AT_INDEX = 7 cc.NUMBER_OF_CELLS_IN_TABLEVIEW = 8 cc.SCROLLVIEW_DIRECTION_NONE = -1 cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0 cc.SCROLLVIEW_DIRECTION_VERTICAL = 1 cc.SCROLLVIEW_DIRECTION_BOTH = 2 cc.CONTROL_EVENTTYPE_TOUCH_DOWN = 1 cc.CONTROL_EVENTTYPE_DRAG_INSIDE = 2 cc.CONTROL_EVENTTYPE_DRAG_OUTSIDE = 4 cc.CONTROL_EVENTTYPE_DRAG_ENTER = 8 cc.CONTROL_EVENTTYPE_DRAG_EXIT = 16 cc.CONTROL_EVENTTYPE_TOUCH_UP_INSIDE = 32 cc.CONTROL_EVENTTYPE_TOUCH_UP_OUTSIDE = 64 cc.CONTROL_EVENTTYPE_TOUCH_CANCEL = 128 cc.CONTROL_EVENTTYPE_VALUE_CHANGED = 256 cc.CONTROL_STATE_NORMAL = 1 cc.CONTROL_STATE_HIGH_LIGHTED = 2 cc.CONTROL_STATE_DISABLED = 4 cc.CONTROL_STATE_SELECTED = 8 cc.KEYBOARD_RETURNTYPE_DEFAULT = 0 cc.KEYBOARD_RETURNTYPE_DONE = 1 cc.KEYBOARD_RETURNTYPE_SEND = 2 cc.KEYBOARD_RETURNTYPE_SEARCH = 3 cc.KEYBOARD_RETURNTYPE_GO = 4 cc.EDITBOX_INPUT_MODE_ANY = 0 cc.EDITBOX_INPUT_MODE_EMAILADDR = 1 cc.EDITBOX_INPUT_MODE_NUMERIC = 2 cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3 cc.EDITBOX_INPUT_MODE_URL = 4 cc.EDITBOX_INPUT_MODE_DECIMAL = 5 cc.EDITBOX_INPUT_MODE_SINGLELINE = 6 cc.EDITBOX_INPUT_FLAG_PASSWORD = 0 cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1 cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2 cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3 cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4 cc.LANGUAGE_ENGLISH = 0 cc.LANGUAGE_CHINESE = 1 cc.LANGUAGE_FRENCH = 2 cc.LANGUAGE_ITALIAN = 3 cc.LANGUAGE_GERMAN = 4 cc.LANGUAGE_SPANISH = 5 cc.LANGUAGE_RUSSIAN = 6 cc.LANGUAGE_KOREAN = 7 cc.LANGUAGE_JAPANESE = 8 cc.LANGUAGE_HUNGARIAN = 9 cc.LANGUAGE_PORTUGUESE = 10 cc.LANGUAGE_ARABIC = 11 cc.NODE_ON_ENTER = 0 cc.NODE_ON_EXIT = 1 cc.NODE_ON_ENTER_TRANSITION_DID_FINISH = 2 cc.NODE_ON_EXIT_TRANSITION_DID_START = 3 cc.NODE_ON_CLEAN_UP = 4 cc.CONTROL_STEPPER_PART_MINUS = 0 cc.CONTROL_STEPPER_PART_PLUS = 1 cc.CONTROL_STEPPER_PART_NONE = 2 cc.TABLEVIEW_FILL_TOPDOWN = 0 cc.TABLEVIEW_FILL_BOTTOMUP = 1 cc.WEBSOCKET_OPEN = 0 cc.WEBSOCKET_MESSAGE = 1 cc.WEBSOCKET_CLOSE = 2 cc.WEBSOCKET_ERROR = 3 cc.WEBSOCKET_STATE_CONNECTING = 0 cc.WEBSOCKET_STATE_OPEN = 1 cc.WEBSOCKET_STATE_CLOSING = 2 cc.WEBSOCKET_STATE_CLOSED = 3 cc.XMLHTTPREQUEST_RESPONSE_STRING = 0 cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER = 1 cc.XMLHTTPREQUEST_RESPONSE_BLOB = 2 cc.XMLHTTPREQUEST_RESPONSE_DOCUMENT = 3 cc.XMLHTTPREQUEST_RESPONSE_JSON = 4 cc.ASSETSMANAGER_CREATE_FILE = 0 cc.ASSETSMANAGER_NETWORK = 1 cc.ASSETSMANAGER_NO_NEW_VERSION = 2 cc.ASSETSMANAGER_UNCOMPRESS = 3 cc.ASSETSMANAGER_PROTOCOL_PROGRESS = 0 cc.ASSETSMANAGER_PROTOCOL_SUCCESS = 1 cc.ASSETSMANAGER_PROTOCOL_ERROR = 2 cc.Handler = cc.Handler or {} cc.Handler.NODE = 0 cc.Handler.MENU_CLICKED = 1 cc.Handler.CALLFUNC = 2 cc.Handler.SCHEDULE = 3 cc.Handler.TOUCHES = 4 cc.Handler.KEYPAD = 5 cc.Handler.ACCELEROMETER = 6 cc.Handler.CONTROL_TOUCH_DOWN = 7 cc.Handler.CONTROL_TOUCH_DRAG_INSIDE = 8 cc.Handler.CONTROL_TOUCH_DRAG_OUTSIDE = 9 cc.Handler.CONTROL_TOUCH_DRAG_ENTER = 10 cc.Handler.CONTROL_TOUCH_DRAG_EXIT = 11 cc.Handler.CONTROL_TOUCH_UP_INSIDE = 12 cc.Handler.CONTROL_TOUCH_UP_OUTSIDE = 13 cc.Handler.CONTROL_TOUCH_UP_CANCEL = 14 cc.Handler.CONTROL_VALUE_CHANGED = 15 cc.Handler.WEBSOCKET_OPEN = 16 cc.Handler.WEBSOCKET_MESSAGE = 17 cc.Handler.WEBSOCKET_CLOSE = 18 cc.Handler.WEBSOCKET_ERROR = 19 cc.Handler.GL_NODE_DRAW = 20 cc.Handler.SCROLLVIEW_SCROLL = 21 cc.Handler.SCROLLVIEW_ZOOM = 22 cc.Handler.TABLECELL_TOUCHED = 23 cc.Handler.TABLECELL_HIGHLIGHT = 24 cc.Handler.TABLECELL_UNHIGHLIGHT = 25 cc.Handler.TABLECELL_WILL_RECYCLE = 26 cc.Handler.TABLECELL_SIZE_FOR_INDEX = 27 cc.Handler.TABLECELL_AT_INDEX = 28 cc.Handler.TABLEVIEW_NUMS_OF_CELLS = 29 cc.Handler.HTTPREQUEST_STATE_CHANGE = 30 cc.Handler.ASSETSMANAGER_PROGRESS = 31 cc.Handler.ASSETSMANAGER_SUCCESS = 32 cc.Handler.ASSETSMANAGER_ERROR = 33 cc.Handler.STUDIO_EVENT_LISTENER = 34 cc.Handler.ARMATURE_EVENT = 35 cc.Handler.EVENT_ACC = 36 cc.Handler.EVENT_CUSTIOM = 37 cc.Handler.EVENT_KEYBOARD_PRESSED = 38 cc.Handler.EVENT_KEYBOARD_RELEASED = 39 cc.Handler.EVENT_TOUCH_BEGAN = 40 cc.Handler.EVENT_TOUCH_MOVED = 41 cc.Handler.EVENT_TOUCH_ENDED = 42 cc.Handler.EVENT_TOUCH_CANCELLED = 43 cc.Handler.EVENT_TOUCHES_BEGAN = 44 cc.Handler.EVENT_TOUCHES_MOVED = 45 cc.Handler.EVENT_TOUCHES_ENDED = 46 cc.Handler.EVENT_TOUCHES_CANCELLED = 47 cc.Handler.EVENT_MOUSE_DOWN = 48 cc.Handler.EVENT_MOUSE_UP = 49 cc.Handler.EVENT_MOUSE_MOVE = 50 cc.Handler.EVENT_MOUSE_SCROLL = 51 cc.Handler.EVENT_SPINE = 52 cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN = 53 cc.Handler.EVENT_PHYSICS_CONTACT_PRESOLVE = 54 cc.Handler.EVENT_PHYSICS_CONTACT_POSTSOLVE = 55 cc.Handler.EVENT_PHYSICS_CONTACT_SEPERATE = 56 cc.Handler.EVENT_FOCUS = 57 cc.Handler.EVENT_CONTROLLER_CONNECTED = 58 cc.Handler.EVENT_CONTROLLER_DISCONNECTED = 59 cc.Handler.EVENT_CONTROLLER_KEYDOWN = 60 cc.Handler.EVENT_CONTROLLER_KEYUP = 61 cc.Handler.EVENT_CONTROLLER_KEYREPEAT = 62 cc.Handler.EVENT_CONTROLLER_AXIS = 63 cc.EVENT_UNKNOWN = 0 cc.EVENT_TOUCH_ONE_BY_ONE = 1 cc.EVENT_TOUCH_ALL_AT_ONCE = 2 cc.EVENT_KEYBOARD = 3 cc.EVENT_MOUSE = 4 cc.EVENT_ACCELERATION = 5 cc.EVENT_CUSTOM = 6 cc.PHYSICSSHAPE_MATERIAL_DEFAULT = {density = 0.0, restitution = 0.5, friction = 0.5} cc.PHYSICSBODY_MATERIAL_DEFAULT = {density = 0.1, restitution = 0.5, friction = 0.5} cc.GLYPHCOLLECTION_DYNAMIC = 0 cc.GLYPHCOLLECTION_NEHE = 1 cc.GLYPHCOLLECTION_ASCII = 2 cc.GLYPHCOLLECTION_CUSTOM = 3 cc.ResolutionPolicy = { EXACT_FIT = 0, NO_BORDER = 1, SHOW_ALL = 2, FIXED_HEIGHT = 3, FIXED_WIDTH = 4, UNKNOWN = 5, } cc.LabelEffect = { NORMAL = 0, OUTLINE = 1, SHADOW = 2, GLOW = 3, } cc.KeyCodeKey = { "KEY_NONE", "KEY_PAUSE", "KEY_SCROLL_LOCK", "KEY_PRINT", "KEY_SYSREQ", "KEY_BREAK", "KEY_ESCAPE", "KEY_BACKSPACE", "KEY_TAB", "KEY_BACK_TAB", "KEY_RETURN", "KEY_CAPS_LOCK", "KEY_SHIFT", "KEY_CTRL", "KEY_ALT", "KEY_MENU", "KEY_HYPER", "KEY_INSERT", "KEY_HOME", "KEY_PG_UP", "KEY_DELETE", "KEY_END", "KEY_PG_DOWN", "KEY_LEFT_ARROW", "KEY_RIGHT_ARROW", "KEY_UP_ARROW", "KEY_DOWN_ARROW", "KEY_NUM_LOCK", "KEY_KP_PLUS", "KEY_KP_MINUS", "KEY_KP_MULTIPLY", "KEY_KP_DIVIDE", "KEY_KP_ENTER", "KEY_KP_HOME", "KEY_KP_UP", "KEY_KP_PG_UP", "KEY_KP_LEFT", "KEY_KP_FIVE", "KEY_KP_RIGHT", "KEY_KP_END", "KEY_KP_DOWN", "KEY_KP_PG_DOWN", "KEY_KP_INSERT", "KEY_KP_DELETE", "KEY_F1", "KEY_F2", "KEY_F3", "KEY_F4", "KEY_F5", "KEY_F6", "KEY_F7", "KEY_F8", "KEY_F9", "KEY_F10", "KEY_F11", "KEY_F12", "KEY_SPACE", "KEY_EXCLAM", "KEY_QUOTE", "KEY_NUMBER", "KEY_DOLLAR", "KEY_PERCENT", "KEY_CIRCUMFLEX", "KEY_AMPERSAND", "KEY_APOSTROPHE", "KEY_LEFT_PARENTHESIS", "KEY_RIGHT_PARENTHESIS", "KEY_ASTERISK", "KEY_PLUS", "KEY_COMMA", "KEY_MINUS", "KEY_PERIOD", "KEY_SLASH", "KEY_0", "KEY_1", "KEY_2", "KEY_3", "KEY_4", "KEY_5", "KEY_6", "KEY_7", "KEY_8", "KEY_9", "KEY_COLON", "KEY_SEMICOLON", "KEY_LESS_THAN", "KEY_EQUAL", "KEY_GREATER_THAN", "KEY_QUESTION", "KEY_AT", "KEY_CAPITAL_A", "KEY_CAPITAL_B", "KEY_CAPITAL_C", "KEY_CAPITAL_D", "KEY_CAPITAL_E", "KEY_CAPITAL_F", "KEY_CAPITAL_G", "KEY_CAPITAL_H", "KEY_CAPITAL_I", "KEY_CAPITAL_J", "KEY_CAPITAL_K", "KEY_CAPITAL_L", "KEY_CAPITAL_M", "KEY_CAPITAL_N", "KEY_CAPITAL_O", "KEY_CAPITAL_P", "KEY_CAPITAL_Q", "KEY_CAPITAL_R", "KEY_CAPITAL_S", "KEY_CAPITAL_T", "KEY_CAPITAL_U", "KEY_CAPITAL_V", "KEY_CAPITAL_W", "KEY_CAPITAL_X", "KEY_CAPITAL_Y", "KEY_CAPITAL_Z", "KEY_LEFT_BRACKET", "KEY_BACK_SLASH", "KEY_RIGHT_BRACKET", "KEY_UNDERSCORE", "KEY_GRAVE", "KEY_A", "KEY_B", "KEY_C", "KEY_D", "KEY_E", "KEY_F", "KEY_G", "KEY_H", "KEY_I", "KEY_J", "KEY_K", "KEY_L", "KEY_M", "KEY_N", "KEY_O", "KEY_P", "KEY_Q", "KEY_R", "KEY_S", "KEY_T", "KEY_U", "KEY_V", "KEY_W", "KEY_X", "KEY_Y", "KEY_Z", "KEY_LEFT_BRACE", "KEY_BAR", "KEY_RIGHT_BRACE", "KEY_TILDE", "KEY_EURO", "KEY_POUND", "KEY_YEN", "KEY_MIDDLE_DOT", "KEY_SEARCH", "KEY_DPAD_LEFT", "KEY_DPAD_RIGHT", "KEY_DPAD_UP", "KEY_DPAD_DOWN", "KEY_DPAD_CENTER", "KEY_ENTER", "KEY_PLAY", } cc.KeyCode = { } for k,v in ipairs(cc.KeyCodeKey) do cc.KeyCode[v] = k - 1 end cc.KeyCode.KEY_BACK = cc.KeyCode.KEY_ESCAPE cc.EventCode = { BEGAN = 0, MOVED = 1, ENDED = 2, CANCELLED = 3, } cc.ControllerKey = { JOYSTICK_LEFT_X = 1000, JOYSTICK_LEFT_Y = 1001, JOYSTICK_RIGHT_X = 1002, JOYSTICK_RIGHT_Y = 1003, BUTTON_A = 1004, BUTTON_B = 1005, BUTTON_C = 1006, BUTTON_X = 1007, BUTTON_Y = 1008, BUTTON_Z = 1009, BUTTON_DPAD_UP = 1010, BUTTON_DPAD_DOWN = 1011, BUTTON_DPAD_LEFT = 1012, BUTTON_DPAD_RIGHT = 1013, BUTTON_DPAD_CENTER = 1014, BUTTON_LEFT_SHOULDER = 1015, BUTTON_RIGHT_SHOULDER = 1016, AXIS_LEFT_TRIGGER = 1017, AXIS_RIGHT_TRIGGER = 1018, BUTTON_LEFT_THUMBSTICK = 1019, BUTTON_RIGHT_THUMBSTICK = 1020, BUTTON_START = 1021, BUTTON_SELECT = 1022, BUTTON_PAUSE = 1023, KEY_MAX = 1024, }
mit
LaFamiglia/Illarion-Content
item/id_290_cabbage.lua
1
1250
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- Kohlbewegungsscript -- UPDATE items SET itm_script='item.id_290_cabbage' WHERE itm_id IN (290); local common = require("base.common") local M = {} function M.MoveItemBeforeMove(User, SourceItem, TargetItem) if (SourceItem:getData("amount") ~= "") then common.HighInformNLS(User, "Du würdest den Kohl beschädigen, ziehst du ihn mit bloßen Händen heraus. Du benötigst eine Sichel, um ihn abzuschneiden.", "You would damage the cabbage, if you pulled it out with bare hands. You need a sickle to cut it."); return false end return true end return M
agpl-3.0
yanarsin/cnnbot
plugins/stats.lua
866
4001
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
alivilteram/seedteam
plugins/stats.lua
866
4001
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
Noltari/luci
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_6to4.lua
72
1073
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, defaultroute, metric, ttl, mtu ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" 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) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
apache-2.0
dismantl/luci-0.12
modules/rpc/luasrc/controller/rpc.lua
70
4443
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local require = require local pairs = pairs local print = print local pcall = pcall local table = table module "luci.controller.rpc" function index() local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) if auth then -- if authentication token was given local sdat = luci.sauth.read(auth) if sdat then -- if given token is valid if sdat.user and luci.util.contains(accs, sdat.user) then return sdat.user, auth end end end luci.http.status(403, "Forbidden") end local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local sauth = require "luci.sauth" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local loginstat local server = {} server.challenge = function(user, pass) local sid, token, secret if sys.user.checkpasswd(user, pass) then sid = sys.uniqueid(16) token = sys.uniqueid(16) secret = sys.uniqueid(16) http.header("Set-Cookie", "sysauth=" .. sid.."; path=/") sauth.reap() sauth.write(sid, { user=user, token=token, secret=secret }) end return sid and {sid=sid, token=token, secret=secret} end server.login = function(...) local challenge = server.challenge(...) return challenge and challenge.sid end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end
apache-2.0
Inorizushi/DDR-X3
BGAnimations/BGScripts/default.lua
2
1189
--DO NOT TRY TO LOAD THIS ACTOR DIRECTLY!! --IT WILL NOT WORK!! local t = Def.ActorFrame{}; local function setVisibility(self) local song = GAMESTATE:GetCurrentSong(); local shouldShowBGScripts = false if song then shouldShowBGScripts = not song:HasBGChanges() if shouldShowBGScripts then local opts = GAMESTATE:GetSongOptionsObject('ModsLevel_Current') shouldShowBGScripts = not opts:StaticBackground() end end local bg = SCREENMAN:GetTopScreen():GetChild("SongBackground") if bg then bg:visible(not shouldShowBGScripts); end self:visible(shouldShowBGScripts); end t.OnCommand = setVisibility t.CurrentSongChangedMessageCommand = setVisibility local charName = (GAMESTATE:Env())['SNCharacter'.. ToEnumShortString(GAMESTATE:GetMasterPlayerNumber())] or "" local loadWorked = false local potentialVideo = Characters.GetDancerVideo(charName) if potentialVideo then loadWorked = true t[#t+1] = LoadActor( potentialVideo )..{ InitCommand=cmd(draworder,1;Center;zoomto,SCREEN_WIDTH+38,SCREEN_HEIGHT+38;); }; end return {bg=t, worked=loadWorked};
mit
rjeli/node9
fs/appl/syscall.lua
3
13668
-- system interface objects -- -- (see kernel startup for available kernel interfaces) local S = {} local stat = {} function stat.new(...) args = {...} self = {} self.name = "" self.uid = "" self.gid = "" self.muid = "" if not args[1] then self.qid = {path = ffi.new("uint64_t"), vers = 0, qtype = 0} self.mode = 0 self.atime = 0 self.mtime = 0 self.length = ffi.new("int64_t") self.dtype = 0 self.dev = 0 else self.qid = {path = ffi.new("uint64_t") -1, vers = -1, qtype = -1} self.mode = -1 self.atime = -1 self.mtime = -1 self.length = ffi.new("int64_t") - 1 self.dtype = -1 self.dev = -1 end function self.idtuple() return self.name, self.uid, self.gid, self.muid end setmetatable(self, { __tostring = function(dstat) return string.format("<dirstat>: name: %s, len: %s, uid: %s, gid: %s, mtime: %s", dstat.name, dstat.length, dstat.uid, dstat.gid, date(dstat.mtime)) end } ) return self end --[[ Support Functions ]]-- -- unbundles a kernel dir into a node9 sys_dir (dirstat entity) -- (stat pack/unpack) local function s_unpack(sdir, kdir) sdir.name = ffi.string(kdir.name) sdir.uid = ffi.string(kdir.uid) sdir.gid = ffi.string(kdir.gid) sdir.muid = ffi.string(kdir.muid) sdir.qid.path = kdir.qid.path sdir.qid.vers = kdir.qid.vers sdir.qid.qtype = kdir.qid.type -- really a char sdir.mode = kdir.mode sdir.atime = kdir.atime sdir.mtime = kdir.mtime sdir.length = kdir.length sdir.dtype = kdir.type sdir.dev = kdir.dev end -- misc utility functions function S.mkcstr(s) return ffi.new("char [?]", #s+1, s) end local mkcstr = S.mkcstr local function date(otime) return os.date("%c",otime) end --[[ System Calls ]]-- -- i/o buffer functions function S.mkBuffer(size) local buf = ffi.gc(n9.mkBuffer(size), n9.freeBuffer) return buf end local mkBuffer = S.mkBuffer -- -- sys requests -- function S.open(vp, s_open, path, mode) --local s_open = srq.open s_open.s = mkcstr(path) s_open.mode = mode n9.sysreq(vp, n9.Sys_open) coroutine.yield() local fd = s_open.ret if fd ~= nil then return ffi.gc(fd, n9.free_fd) else return nil end end function S.create(vp, s_create, path, mode, perm) s_create.s = mkcstr(path) s_create.mode = mode s_create.perm = perm n9.sysreq(vp, n9.Sys_create) coroutine.yield() local fd = s_create.ret if fd ~= nil then return ffi.gc(fd, n9.free_fd) else return nil end end -- sys.dup will create a new file descriptor that refers to a currently -- open file. oldfd is the integer handle of the open descriptor and -- newfd will be the integer handle of the new descriptor if it's in -- the valid descriptor range. -- notes: -- o if newfd is currently in use, the associated descriptor is -- released newfd will refer to the new descriptor. -- o if newfd is -1, the first available free integer will be used -- o the returned value is the integer handle of the new descriptor function S.dup(vp, sdup, oldfd, newfd) s_dup.old = oldfd s_dup.new = newfd n9.sysreq(vp, n9.Sys_dup) coroutine.yield() return s_dup.ret end -- sys.fildes creates a new file descriptor object by duplicating the -- file descriptor with handle 'fd'. it returns the descriptor object -- or nil if creation failed function S.fildes(vp, s_fildes, fdnum) s_fildes.fd = fdnum n9.sysreq(vp, n9.Sys_fildes) coroutine.yield() local fd = s_fildes.ret if fd ~= nil then return ffi.gc(fd, n9.free_fd) else return nil end end -- sys.seek: seek to the specified location in fd -- fd: an open file descriptor object -- offset: can be a lua number or signed 64 bit cdata -- start: specifies where to seek from and is one of: -- sys.SEEKSTART (from beginning of file) -- sys.SEEKRELA (from current location) -- sys.SEEKEND (relative to end of file, usually negative) function S.seek(vp, s_seek, fd, offset, start) s_seek.fd = fd s_seek.off = offset s_seek.start = start n9.sysreq(vp, n9.Sys_seek) coroutine.yield() return s_seek.ret end -- returns the largest I/O possible on descriptor fd's channel -- without splitting into multiple operations, 0 means undefined function S.iounit(vp, s_iounit, fd) s_iounit.fd = fd n9.sysreq(vp, n9.Sys_iounit) coroutine.yield() return s_iounit.ret end -- accepts fd, preallocated cdef array of unsigned byte -- and fills buffer with read data -- returns number of bytes read function S.read(vp, s_read, fd, buf, nbytes) s_read.fd = fd s_read.buf = buf s_read.nbytes = nbytes n9.sysreq(vp, n9.Sys_read) coroutine.yield() return s_read.ret end function S.readn(vp, s_readn, fd, buf, nbytes) s_readn.fd = fd s_readn.buf = buf s_readn.n = nbytes n9.sysreq(vp, n9.Sys_readn) coroutine.yield() return s_readn.ret end function S.pread(vp, s_pread, fd, buf, nbytes, offset) s_pread.fd = fd s_pread.buf = buf s_pread.n = nbytes s_pread.off = offset n9.sysreq(vp, n9.Sys_pread) coroutine.yield() return s_pread.ret end -- write buf to file descriptor fd -- entire buffer will be written, unless overridden -- by optional length argument function S.write(vp, s_write, fd, buf, ...) local args = {...} -- optional number of bytes to write s_write.fd = fd s_write.buf = buf s_write.nbytes = args[1] or buf.len n9.sysreq(vp, n9.Sys_write) coroutine.yield() return s_write.ret end function S.pwrite(vp, s_pwrite, fd, buf, nbytes, offset) s_pwrite.fd = fd s_pwrite.buf = buf if nbytes == 0 then s_pwrite.n = buf.len else s_pwrite.n = nbytes end s_pwrite.off = offset n9.sysreq(vp, n9.Sys_pwrite) coroutine.yield() return s_pwrite.ret end function S.sprint(fmt, ...) return string.format(fmt, ...) end function S.print(vp, s_print, fmt, ...) local tstr = string.format(fmt, ...) local tbuf = mkcstr(tstr) s_print.buf = tbuf s_print.len = #tstr n9.sysreq(vp, n9.Sys_print) coroutine.yield() return s_print.ret end function S.fprint(vp, s_fprint, fd, fmt, ...) local tstr = string.format(fmt, ...) local tbuf = mkcstr(tstr) s_fprint.fd = fd s_fprint.buf = tbuf s_fprint.len = #tstr n9.sysreq(vp, n9.Sys_fprint) coroutine.yield() return s_fprint.ret end --[[ function S.stream(vp, srq, src, dst, bufsize) n9.sys_stream(vp, src, dst, bufsize) local ret = coroutine.yield() return ret[0] end ]]-- -- construct a stat template function S.nulldir() return stat.new(-1) end -- returns the stat results for file path -- returns a table {int rc, Sys_dir} -- where: rc = 0 on success, -1 on failure -- Sys_Dir is created and populated with appropriate values -- on failure Sys_Dir is nil function S.stat(vp, s_stat, path) s_stat.s = mkcstr(path) n9.sysreq(vp, n9.Sys_stat) coroutine.yield() local rc = -1 local newstat = nil local kdir = s_stat.ret if kdir ~= nil then rc = 0 newstat = stat.new() s_unpack(newstat, kdir) end n9.free_dir(kdir) return rc, newstat end function S.fstat(vp, s_fstat, fd) s_fstat.fd = fd n9.sysreq(vp, n9.Sys_fstat) coroutine.yield() local rc = -1 local newstat = nil local kdir = s_fstat.ret if kdir ~= nil then rc = 0 newstat = stat.new() s_unpack(newstat, kdir) end n9.free_dir(kdir) return rc, newstat end function S.wstat(vp, s_wstat, path, sdir) -- (create local refs to prevent deallocation) local s_name = mkcstr(sdir.name); local s_uid = mkcstr(sdir.uid); local s_gid = mkcstr(sdir.gid); local s_muid = mkcstr(sdir.muid) -- translate to kernel dir local s_path = mkcstr(path) local s_kdir = ffi.new("Dir", { name = s_name, uid = s_suid, gid = s_gid, muid = s_muid, mode = sdir.mode, mtime = sdir.mtime, atime = sdir.atime, qid = { path = sdir.path, vers = sdir.vers, type = sdir.qtype }, length = sdir.length, type = sdir.dtype, dev = sdir.dev } ) s_wstat.s = s_path s_wstat.dir = s_kdir n9.sysreq(vp, n9.Sys_wstat) coroutine.yield() return s_wstat.ret end function S.fwstat(vp, s_fwstat, fd, sdir) -- (create local refs to prevent deallocation) local s_name = mkcstr(sdir.name); local s_uid = mkcstr(sdir.uid); local s_gid = mkcstr(sdir.gid); local s_muid = mkcstr(sdir.muid) -- translate to kernel dir local s_kdir = ffi.new("Dir", { name = s_name, uid = s_suid, gid = s_gid, muid = s_muid, mode = sdir.mode, mtime = sdir.mtime, atime = sdir.atime, qid = { path = sdir.path, vers = sdir.vers, type = sdir.qtype }, length = sdir.length, type = sdir.dtype, dev = sdir.dev } ) s_fwstat.fd = fd s_fwstat.dir = s_kdir n9.sysreq(vp, n9.Sys_fwstat) coroutine.yield() return s_fwstat.ret end function S.dirread(vp, s_dirread, fd) s_dirread.fd = fd n9.sysreq(vp, n9.Sys_dirread) coroutine.yield() return ffi.gc(s_dirread.ret, n9.free_dirpack) end function S.errstr() local estr = n9.sys_errstr(vp) if estr ~= nil then return ffi.string(estr) else return nil end end function S.werrstr(vp, errstr) local err = mkcstr(errstr) n9.sys_werrstr(vp, err) return 0 end --[[ function S.bind(vp, srq, name, old, flags) n9.sys_bind(vp, name, old, flags) local ret = coroutine.yield() return ret[0] end function S.mount(vp, srq, FD, AFD, oldstring, flags, anamestring) n9.sys_mount(vp, FD, AFD, oldstring, flags, anamestring) local ret = coroutine.yield() return ret[0] end function S.unmount(vp, srq, namestring, oldstring) n9.sys_unmount(vp, namestring, oldstring) local ret = coroutine.yield() return ret[0] end ]]-- function S.remove(vp, s_remove, path) local pth = mkcstr(path) s_remove.s = pth n9.sysreq(vp, n9.Sys_remove) coroutine.yield() return s_remove.ret end function S.chdir(vp, s_chdir, path) local pth = mkcstr(path) s_chdir.path = pth n9.sysreq(vp, n9.Sys_chdir) coroutine.yield() return s_chdir.ret end function S.fd2path(vp, s_fd2path, fd) s_fd2path.fd = fd n9.sysreq(vp, n9.Sys_fd2path) coroutine.yield() if s_fd2path.ret == nil then return "" end local pstring = ffi.string(s_fd2path.ret) -- kernel alloc'd, so let it go n9.free_cstring(s_fd2path.ret) return pstring end --[[ function S.pipe(vp, srq) n9.sys_pipe(pid) local ret = coroutine.yield() return ret end function S.dial(vp, srq, addrstring, localstring) n9.sys_dial(vp, addrstring, localstring) local ret = coroutine.yield() return ret end function S.announce(vp, srq, addrstring) n9.sys_announce(vp, addrstring) local ret = coroutine.yield() return ret end function S.listen(vp, srq, connection) n9.sys_listen(vp, connection) local ret = coroutine.yield() return ret end function S.file2chan(vp, srq, dirstring, filestring) n9.sys_chdir(vp, dirstring, filestring) local ret = coroutine.yield() return ret[0] end function S.export(vp, srq, FD, dirstring, flags) n9.sys_export(vp, FD, dirstring, flags) local ret = coroutine.yield() return ret[0] end --]] function S.millisec() return n9.sys_millisec() end function S.sleep(vp, s_sleep, millisecs) n9.sys_sleep(vp, millisecs) -- non-standard async req coroutine.yield() return s_sleep.ret end --[[ function S.fversion(vp, srq, FD, bufsize, versionstring) n9.sys_fversion(vp, FD, bufsize, versionstring) local ret = coroutine.yield() return ret end function S.fauth(vp, srq, FD, anamestring) n9.sys_fauth(vp, FD, anamestring) local ret = coroutine.yield() return ret[0] end function S.pctl(vp, srq, flags, movefd_list) n9.sys_pctl(vp, flags, movefd_list) local ret = coroutine.yield() return ret[0] end ]]-- -- create a new task, this is a little convoluted -- new_proc and make_ready are inherited from the kernel / scheduler function S.spawn(vp, p, s_spawn, fun, name, ...) local args = {...} -- create the kernel vproc n9.sysreq(vp, n9.Sys_spawn) coroutine.yield() local child_pid = s_spawn.ret local child_vproc = n9.procpid(child_pid) -- sync call -- specify the kernel finalizer for child_vproc -- free_vproc runs async, notifies proc group and doesn't block ffi.gc(child_vproc, n9.vproc_exit) -- create the lua task, run its initializer and make it ready -- (new_proc and make_ready are on loan from the kernel) local nproc = new_proc(fun, child_vproc) nproc.app = p.app nproc.name = name or p.name nproc.args = args -- startup value is arglist -- bind the new proc to the shared app global space setmetatable(nproc, {__index = nproc.app.env, __newindex = nproc.app.env}) -- redirect the start function global refs to coroutine global refs setfenv(fun, init_proxy) make_ready(nproc) end -- system constants S.const = const return S
mit
shahabsaf1/copy-infernal
plugins/Location.lua
185
1565
-- Implement a command !loc [area] which uses -- the static map API to get a location image -- Not sure if this is the proper way -- Intent: get_latlong is in time.lua, we need it here -- loadfile "time.lua" -- Globals -- If you have a google api key for the geocoding/timezone api do local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_staticmap(area) local api = base_api .. "/staticmap?" -- Get a sense of scale local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local receiver = get_receiver(msg) local lat,lng,url = get_staticmap(matches[1]) -- Send the actual location, is a google maps link send_location(receiver, lat, lng, ok_cb, false) -- Send a picture of the map, which takes scale into account send_photo_from_url(receiver, url) -- Return a link to the google maps stuff is now not needed anymore return nil end return { description = "Gets information about a location, maplink and overview", usage = "!loc (location): Gets information about a location, maplink and overview", patterns = {"^!loc (.*)$"}, run = run } end
gpl-2.0
koeppea/ettercap
src/lua/share/scripts/http_requests.lua
12
2720
--- -- -- Created by Ryan Linn and Mike Ryan -- Copyright (C) 2012 Trustwave Holdings, Inc. description = "Script to show HTTP requsts"; local http = require("http") local packet = require("packet") local bin = require("bit") hook_point = http.hook packetrule = function(packet_object) -- If this isn't a tcp packet, it's not really a HTTP request -- since we're hooked in the HTTP dissector, we can assume that this -- should never fail, but it's a good sanity check if packet.is_tcp(packet_object) == false then return false end return true end -- Here's your action. action = function(packet_object) local p = packet_object -- Parse the http data into an HTTP object local hobj = http.parse_http(p) -- If there's no http object, get out if hobj == nil then return end -- Get out session key for tracking req->reply pairs local session_id = http.session_id(p,hobj) -- If we can't track sessions, this won't work, get out if session_id == nil then return end -- We have a session, lets get our registry space local reg = ettercap.reg.create_namespace(session_id) -- If it's a request, save the request to the registry -- We'll need this for the response if hobj.request then reg.request = hobj -- we have a response object, let't put the log together elseif hobj.response then -- If we haven't seen the request, we don't have anything to share if not reg.request then return end -- Get the status code local code = hobj.status_code -- Build the request URL -- If we have a 2XX or 4XX or 5XX code, we won't need to log redirect -- so just log the request and code if code >= 200 and code < 300 or code >= 400 then ettercap.log("HTTP_REQ: %s:%d -> %s:%d %s %s %d (%s)\n", packet.dst_ip(p), packet.dst_port(p), packet.src_ip(p), packet.src_port(p), reg.request.verb ,reg.request.url , hobj.status_code, hobj.status_msg) -- These codes require redirect, so log the redirect as well elseif code >= 300 and code <= 303 then local redir = "" -- Get the redirect location if hobj.headers["Location"] then redir = hobj.headers["Location"] end -- Log the request/response with the redirect ettercap.log("HTTP_REQ: %s:%d -> %s:%d %s %s -> %s %d (%s)\n", packet.dst_ip(p), packet.dst_port(p), packet.src_ip(p), packet.src_port(p), reg.request.verb ,reg.request.url, redir, hobj.status_code, hobj.status_msg) end end end
gpl-2.0
AleksCore/Mr.Green-MTA-Resources
resources/[gameplay]/mapstop100/votestop100_c.lua
3
9181
welcomeText = "Welcome to the Mr.Green Maps top 100! Choose maps from the list on the left you want to vote for and add\nthem with the 'Add' button. If you made a mistake simply remove the vote with the 'remove' button. When\nyou carefully selected the maps press the 'Cast vote' button. You may vote up to a maximum of 5 maps." VotesList = {} CastList = {} VotesEditor = { tab = {}, tabpanel = {}, edit = {}, button = {}, window = {}, label = {}, gridlist = {}, image = {} } function votes100_buildGUI() local screenW, screenH = guiGetScreenSize() VotesEditor.window[1] = guiCreateWindow((screenW - 768) / 2, (screenH - 640) / 2, 768, 640, "Maps top 100", false) guiWindowSetSizable(VotesEditor.window[1], false) VotesEditor.button[1] = guiCreateButton(320, 608, 128, 24, "Close", false, VotesEditor.window[1]) addEventHandler("onClientGUIClick",VotesEditor.button[1],votes100_openCloseGUI,false) VotesEditor.image[1] = guiCreateStaticImage(192, 16, 384, 96, "mapstop100_logo.png", false, VotesEditor.window[1]) VotesEditor.gridlist[1] = guiCreateGridList(8, 208, 328, 344, false, VotesEditor.window[1]) guiGridListAddColumn(VotesEditor.gridlist[1], "Name", 0.7) guiGridListAddColumn(VotesEditor.gridlist[1], "Author", 0.4) guiGridListAddColumn(VotesEditor.gridlist[1], "Gamemode", 0.5) guiGridListAddColumn(VotesEditor.gridlist[1], "resname", 0.5) VotesEditor.gridlist[2] = guiCreateGridList(432, 208, 328, 256, false, VotesEditor.window[1]) guiGridListAddColumn(VotesEditor.gridlist[2], "Name", 0.7) guiGridListAddColumn(VotesEditor.gridlist[2], "Author", 0.4) guiGridListAddColumn(VotesEditor.gridlist[2], "Gamemode", 0.5) guiGridListAddColumn(VotesEditor.gridlist[2], "resname", 0.5) VotesEditor.label[1] = guiCreateLabel(8, 184, 328, 16, "Maps to choose from:", false, VotesEditor.window[1]) guiLabelSetHorizontalAlign(VotesEditor.label[1], "center", false) guiLabelSetVerticalAlign(VotesEditor.label[1], "center") VotesEditor.label[2] = guiCreateLabel(432, 184, 328, 16, "Maps you vote for:", false, VotesEditor.window[1]) guiLabelSetHorizontalAlign(VotesEditor.label[2], "center", false) guiLabelSetVerticalAlign(VotesEditor.label[2], "center") VotesEditor.label[3] = guiCreateLabel(8, 112, 752, 48, welcomeText, false, VotesEditor.window[1]) guiLabelSetHorizontalAlign(VotesEditor.label[3], "center", false) guiLabelSetVerticalAlign(VotesEditor.label[3], "center") VotesEditor.button[2] = guiCreateButton(352, 272, 64, 24, "Add", false, VotesEditor.window[1]) addEventHandler("onClientGUIClick",VotesEditor.button[2],votes100_voteMap,false) VotesEditor.button[3] = guiCreateButton(352, 304, 64, 24, "Remove", false, VotesEditor.window[1]) addEventHandler("onClientGUIClick",VotesEditor.button[3],votes100_removeMap,false) VotesEditor.button[4] = guiCreateButton(532, 480, 128, 24, "Cast vote!", false, VotesEditor.window[1]) addEventHandler("onClientGUIClick",VotesEditor.button[4],votes100_castVote,false) VotesEditor.edit[1] = guiCreateEdit(24, 568, 192, 24, "", false, VotesEditor.window[1]) VotesEditor.button[5] = guiCreateButton(224, 568, 96, 24, "Clear search", false, VotesEditor.window[1]) addEventHandler("onClientGUIClick",VotesEditor.button[5],votes100_clearSearch,false) guiSetVisible(VotesEditor.window[1],false) --if isTimer(maps100Timer) then killTimer(maps100Timer) end --setTimer(function() -- maps100Timer = setTimer(function() -- exports.messages:outputGameMessage("Vote now for the Mr.Green Maps top 100!", 3, 255, 255, 255) -- setTimer(function() -- exports.messages:outputGameMessage("Use /vote or press F1 to vote!", 2.4, 50, 205, 50) -- end, 1000, 1) -- end, 2700000, 0) --end, 1350000, 1) end addEventHandler("onClientResourceStart",resourceRoot,votes100_buildGUI) addEvent("votes100_openCloseGUI",true) function votes100_openCloseGUI() if guiGetVisible(VotesEditor.window[1]) then guiSetVisible(VotesEditor.window[1],false) showCursor(false) guiSetInputMode("allow_binds") else guiSetVisible(VotesEditor.window[1],true) showCursor(true) guiSetInputMode("no_binds_when_editing") end end addEventHandler("votes100_openCloseGUI",root,votes100_openCloseGUI) addEvent("votes100_receiveMap100",true) function votes100_receiveMapList(votesList, castList) VotesList = votesList CastList = castList votes100_rebuildGridLists() end addEventHandler("votes100_receiveMap100",root,votes100_receiveMapList) function votes100_rebuildGridLists() guiGridListClear(VotesEditor.gridlist[1]) guiGridListSetSortingEnabled(VotesEditor.gridlist[1], false) for _,map in ipairs(VotesList) do local author = map.author or "N/A" local name = map.name local resname = map.resname local gamemode = map.gamemode local row = guiGridListAddRow(VotesEditor.gridlist[1]) guiGridListSetItemText(VotesEditor.gridlist[1],row,1,tostring(name),false,false) guiGridListSetItemText(VotesEditor.gridlist[1],row,2,tostring(author),false,false) guiGridListSetItemText(VotesEditor.gridlist[1],row,3,tostring(gamemode),false,false) guiGridListSetItemText(VotesEditor.gridlist[1],row,4,tostring(resname),false,false) end guiGridListClear(VotesEditor.gridlist[2]) guiGridListSetSortingEnabled(VotesEditor.gridlist[2], false) for _,map in ipairs(CastList) do local author = map.author or "N/A" local name = map.name local resname = map.resname local gamemode = map.gamemode local row = guiGridListAddRow(VotesEditor.gridlist[2]) guiGridListSetItemText(VotesEditor.gridlist[2],row,1,tostring(name),false,false) guiGridListSetItemText(VotesEditor.gridlist[2],row,2,tostring(author),false,false) guiGridListSetItemText(VotesEditor.gridlist[2],row,3,tostring(gamemode),false,false) guiGridListSetItemText(VotesEditor.gridlist[2],row,4,tostring(resname),false,false) end end function votes100_voteMap(button, state) if state == "up" and button == "left" then if source == VotesEditor.button[2] then local resname = guiGridListGetItemText(VotesEditor.gridlist[1], guiGridListGetSelectedItem(VotesEditor.gridlist[1]), 4) if resname then triggerServerEvent("votes100_voteMap", resourceRoot, localPlayer, resname) else return false end end end end function votes100_removeMap(button, state) if state == "up" and button == "left" then if source == VotesEditor.button[3] then local resname = guiGridListGetItemText(VotesEditor.gridlist[2], guiGridListGetSelectedItem(VotesEditor.gridlist[2]), 4) if resname then triggerServerEvent("votes100_removeMap", resourceRoot, localPlayer, resname) else return false end end end end function votes100_castVote(button, state) if state == "up" and button == "left" then if source == VotesEditor.button[4] then end end end function votes100_clearSearch(button, state) if state == "up" and button == "left" then if source == VotesEditor.button[5] then guiSetText(VotesEditor.edit[1],"") end end end function votes100_handleSearches() if source == VotesEditor.edit[1] then if not VotesList or #VotesList == 0 then return end local searchQuery = guiGetText(VotesEditor.edit[1]) if #searchQuery == 0 then votes100_rebuildGridLists() else local resultsTable = votes100_searchTable(searchQuery,VotesList) votes100_populateSearchResults(resultsTable,VotesEditor.gridlist[1]) end end end addEventHandler("onClientGUIChanged",root,votes100_handleSearches) function votes100_searchTable(searchQuery,t) searchQuery = string.lower(tostring(searchQuery)) if #searchQuery == 0 then return t end local results = {} for _,map in ipairs(t) do local match = false local name = string.find(string.lower( tostring(map.name) ),searchQuery) local author = string.find(string.lower( tostring(map.author) ),searchQuery) local resname = string.find(string.lower( tostring(map.resname) ),searchQuery) if type(name) == "number" or type(author) == "number" or type(resname) == "number" then match = true end if match then table.insert(results,map) end end return results end function votes100_populateSearchResults(resultsTable,gridlist) if gridlist == VotesEditor.gridlist[1] then -- maplist guiGridListClear(gridlist) for _,map in ipairs(resultsTable) do local author = map.author or "N/A" local name = map.name local resname = map.resname local gamemode = map.gamemode local row = guiGridListAddRow(gridlist) guiGridListSetItemText(gridlist,row,1,tostring(name),false,false) guiGridListSetItemText(gridlist,row,2,tostring(author),false,false) guiGridListSetItemText(gridlist,row,3,tostring(gamemode),false,false) guiGridListSetItemText(gridlist,row,4,tostring(resname),false,false) end end end function votes100_sidebar() triggerServerEvent("votes100_sidebarServer", resourceRoot, localPlayer) end addEvent("sb_mapsTop100", true) addEventHandler("sb_mapsTop100", resourceRoot, votes100_sidebar)
mit
TheAncientGoat/GodheadLips
data/system/file.lua
1
1302
if not Los.program_load_extension("file") then error("loading extension `file' failed") end File = Class() File.class_name = "File" --- Reads the contents of a file. -- @param self File class. -- @param name File name relative to the mod root. -- @return String or nil. File.read = function(self, name) return Los.file_read(name) end --- Returns the contents of a directory. -- @param self File class. -- @param dir Directory name relative to the mod root. -- @return Table of file names or nil. File.scan_directory = function(self, dir) return Los.file_scan_directory(dir) end --- Writes the contents of a file. -- @param self File class. -- @param name File name relative to the mod root. -- @param data Data string. -- @return True on success. File.write = function(self, name, data) return Los.file_write(name, data) end File.unittest = function() -- Directory scanning. local r1 = File:scan_directory("/") assert(#r1 == 1) assert(r1[1] == "scripts") local r2 = File:scan_directory("..") assert(r2 == nil) local r3 = File:scan_directory("scripts") assert(#r3 == 1) assert(r3[1] == "main.lua") local r4 = File:scan_directory("/scripts") assert(#r4 == 1) assert(r4[1] == "main.lua") local r5 = File:scan_directory("/scripts/") assert(#r5 == 1) assert(r5[1] == "main.lua") end
gpl-3.0
shingenko/darkstar
scripts/zones/La_Theine_Plateau/npcs/Cermet_Headstone.lua
17
2685
----------------------------------- -- Area: La Theine Plateau -- NPC: Cermet Headstone -- Involved in Mission: ZM5 Headstone Pilgrimage (Water Fragment) -- @pos -170 39 -504 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/missions"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then if (player:hasKeyItem(WATER_FRAGMENT) == false) then player:startEvent(0x00C8,WATER_FRAGMENT); elseif (player:hasKeyItem(239) and player:hasKeyItem(240) and player:hasKeyItem(241) and player:hasKeyItem(242) and player:hasKeyItem(243) and player:hasKeyItem(244) and player:hasKeyItem(245) and player:hasKeyItem(246)) then player:messageSpecial(ALREADY_HAVE_ALL_FRAGS); elseif (player:hasKeyItem(WATER_FRAGMENT) == true) then player:messageSpecial(ALREADY_OBTAINED_FRAG,WATER_FRAGMENT); end elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then player:messageSpecial(ZILART_MONUMENT); else player:messageSpecial(CANNOT_REMOVE_FRAG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x00C8 and option == 1) then player:addKeyItem(WATER_FRAGMENT); -- Check and see if all fragments have been found (no need to check earth and dark frag) if (player:hasKeyItem(FIRE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(WIND_FRAGMENT) and player:hasKeyItem(LIGHTNING_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then player:messageSpecial(FOUND_ALL_FRAGS,WATER_FRAGMENT); player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS); player:completeMission(ZILART,HEADSTONE_PILGRIMAGE); player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES); else player:messageSpecial(KEYITEM_OBTAINED,WATER_FRAGMENT); end end end;
gpl-3.0
shingenko/darkstar
scripts/globals/spells/bluemagic/power_attack.lua
28
1761
----------------------------------------- -- Spell: Power Attack -- Deals critical damage. Chance of critical hit varies with TP -- Spell cost: 5 MP -- Monster Type: Vermin -- Spell Type: Physical (Blunt) -- Blue Magic Points: 1 -- Stat Bonus: MND+1 -- Level: 4 -- Casting Time: 0.5 seconds -- Recast Time: 7.25 seconds -- Skillchain property: Reverberation (Can open Impaction or Induration) -- Combos: Plantoid Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_REVERBERATION; params.numhits = 1; params.multiplier = 1.125; params.tp150 = 0.5; params.tp300 = 0.7; params.azuretp = 0.8; params.duppercap = 11; -- guesstimated crit %s for TP params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.3; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
simon-wh/PAYDAY-2-BeardLib
Modules/Utils/DependenciesModule.lua
2
4343
DependenciesModule = DependenciesModule or BeardLib:ModuleClass("Dependencies", ModuleBase) function DependenciesModule:Load(config) config = config or self._config local missing_dep = false for _, dep in ipairs(config) do if dep.name then local meta = dep._meta:lower() local type = dep.type and dep.type:lower() or "blt" if meta == "dependency" then if type == "mod_overrides" or type == "map" then local beardlib_check = BeardLib.Utils:ModExists(dep.name) if not beardlib_check then missing_dep = true self:CreateErrorDialog(dep) elseif dep.min_ver and beardlib_check then local beardlib_mod = BeardLib.Utils:FindMod(dep.name) --With the loading change (#502), Modules are not loaded yet, so need to get the version from the config. local mod_asset = beardlib_mod._config[ModAssetsModule.type_name] self:CompareVersion(dep, mod_asset and mod_asset.version) end elseif type == "blt" then local beardlib_check = BeardLib.Utils:ModExists(dep.name) local blt_check, blt_mod = self:CheckBLTMod(dep.name) if not beardlib_check and not blt_check then missing_dep = true self:CreateErrorDialog(dep) elseif dep.min_ver then if beardlib_check then local beardlib_mod = BeardLib.Utils:FindMod(dep.name) local mod_asset = beardlib_mod._config[ModAssetsModule.type_name] self:CompareVersion(dep, mod_asset and mod_asset.version) elseif blt_mod and blt_mod:GetVersion() then self:CompareVersion(dep, blt_mod:GetVersion()) end end else self:Err("Dependency for '%s' has an invalid type: '%s'", tostring(self._mod.mod), tostring(type)) end elseif meta == "dependencies" then self:Load(dep) end else self:Err("Dependency for '%s' has no name", tostring(self._mod.mod)) end end if missing_dep then return false end end function DependenciesModule:CheckBLTMod(name) for _, v in ipairs(BLT.Mods.mods) do if v:GetName() == name then return true, v end end end function DependenciesModule:CompareVersion(dep, mod) --Round to get correct versions for 1.1 instead of 1.000001234 if tonumber(dep.min_ver) then dep.min_ver = math.round_with_precision(dep.min_ver, 4) end if tonumber(mod) then mod = math.round_with_precision(mod, 4) end local dep_version = Version:new(dep.min_ver) local mod_version = Version:new(mod) if mod_version._value ~= "nil" and dep_version > mod_version then if dep.id and dep.provider then self:AddDepDownload(dep) end self._mod:ModError("The mod requires %s version %s or higher in order to run", tostring(dep.name), tostring(dep_version)) end end function DependenciesModule:CreateErrorDialog(dep) if dep.id and dep.provider then self:AddDepDownload(dep) self._mod:ModError("The mod is missing a dependency: '%s' \nYou can download it through the Beardlib Mods Manager.", tostring(dep.name)) else self._mod:ModError("The mod is missing a dependency: '%s'", tostring(dep.name)) end end function DependenciesModule:AddDepDownload(dep) --Default install directories for different mod types. local install_directory = { blt = "./mods/", mod_overrides = "./assets/mod_overrides/", map = "./maps/" } dep.type = dep.type and dep.type:lower() or "blt" local config = { _meta = "AssetUpdates", id = dep.id, provider = dep.provider, install_directory = dep.install_directory or install_directory[dep.type], custom_name = dep.name, dont_delete = true } self._mod:AddModule(config) end
mit
shingenko/darkstar
scripts/globals/spells/horde_lullaby_ii.lua
10
1265
----------------------------------------- -- Spell: Horde Lullaby ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 30; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistanceEffect(caster,spell,target,dCHR,SKILL_SNG,0,EFFECT_LULLABY); if (resm < 0.5) then spell:setMsg(85);--resist message return EFFECT_LULLABY; end if (target:hasImmunity(1) or 100 * math.random() < target:getMod(MOD_SLEEPRES)) then --No effect spell:setMsg(75); else local iBoost = caster:getMod(MOD_LULLABY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (target:addStatusEffect(EFFECT_LULLABY,1,0,duration)) then spell:setMsg(237); else spell:setMsg(75); end end return EFFECT_LULLABY; end;
gpl-3.0
jyggen/lua-parser
tests/Fixtures/cf/5e/bb/fc1de34220024fedb8c1afbb155a34706c59ff2e21bcd9fc066bd9d735.lua
1
56853
TRP3_Profiles = { ["0720161639zFLPT"] = { ["player"] = { ["characteristics"] = { ["RA"] = "Human", ["EC"] = "Blue", ["LN"] = "Claridge", ["MI"] = { }, ["FN"] = "Jett", ["PS"] = { }, ["AG"] = "Thirties", ["CL"] = "Commoner", ["IC"] = "Achievement_Character_Human_Male", ["BP"] = "Lakeshire", ["RE"] = "Ironforge", ["v"] = 10, ["FT"] = "VP of Transportation", ["HE"] = "Average", ["WE"] = "Could lose a pound or two", }, ["character"] = { ["CO"] = "", ["RP"] = 2, ["v"] = 41, ["XP"] = 2, ["CU"] = "", }, ["misc"] = { ["PE"] = { }, ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 3, ["5"] = 4, ["4"] = 1, ["6"] = 2, }, ["v"] = 13, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { }, ["PS"] = { }, ["HI"] = { }, }, ["TE"] = 1, ["T1"] = { }, ["v"] = 1, }, }, ["profileName"] = "Jett Claridge", }, ["0303204953EBSM8"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["LN"] = "Blau", ["EC"] = "Blue", ["FN"] = "Sophie", ["AG"] = "Early 30s", ["IC"] = "PetBattle_Health", ["EH"] = "1087ff", ["HE"] = "Average", ["CH"] = "1087ff", ["RA"] = "Human", ["BP"] = "Gilneas City", ["v"] = 27, ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Fi, Soph, Blauberry", }, -- [1] { ["IC"] = "inv_jewelry_ring_14", ["NA"] = "Piercings", ["VA"] = "(see in-game model)", }, -- [2] { ["IC"] = "INV_Inscription_inkblack01", ["NA"] = "Tattoos", ["VA"] = "Hummingbird on her right shoulder blade.", }, -- [3] }, ["PS"] = { }, ["RE"] = "Stormwind", ["FT"] = "Writer || Food Critic || Possibly Crazy", ["CL"] = "Person", ["WE"] = "Hour glass", }, ["character"] = { ["CO"] = "Always approachable!", ["RP"] = 1, ["v"] = 53, ["XP"] = 2, ["CU"] = "Her usual tipsy self.", }, ["misc"] = { ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Noticeable Fragrance", ["TX"] = "Sophie's fragrance would be a mix of her beloved Silverleaf tobacco and her alluring fruity perfume.", ["IC"] = "INV_ValentinePerfumeBottle", }, ["4"] = { ["IC"] = "INV_Misc_Food_Vendor_StripedMelon", ["TI"] = "Deep Cleavage", ["TX"] = "Sophie's bigger bosom would draw attention to itself in her usual outfits.", ["AC"] = true, }, ["3"] = { ["AC"] = true, ["TI"] = "Seductive Gaze", ["TX"] = "Sophie's gaze is usually of a more seductive kind.", ["IC"] = "Spell_Shadow_SummonSuccubus", }, ["2"] = { ["AC"] = true, ["TI"] = "Sly Smirk", ["TX"] = "Sophie would more often than not have a sly smirk plastered on her face.", ["IC"] = "Achievement_Halloween_Smiley_01", }, }, ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 3, ["5"] = 3, ["4"] = 3, ["6"] = 2, }, ["v"] = 46, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["BK"] = 1, }, ["PS"] = { ["BK"] = 1, }, ["HI"] = { ["BK"] = 1, }, }, ["TE"] = 1, ["T1"] = { ["TX"] = "Soon! <3\n\n{link*https://i.imgur.com/crX3Dy0.png*reference image}", }, ["BK"] = 1, ["v"] = 4, }, }, ["questlog"] = { }, ["relation"] = { ["[MSP]Ezohika-ArgentDawn"] = "FRIEND", ["0428004955TWz72"] = "FRIEND", ["0424131527SLkI7"] = "FRIEND", ["0709181608](n.N"] = "NEUTRAL", }, ["profileName"] = "Sophie Blau", }, ["0413201222f,qo5"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["RA"] = "Human", ["PS"] = { }, ["LN"] = "Dawson", ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Belle, Dawson", }, -- [1] }, ["FN"] = "Isabelle", ["EC"] = "Blue", ["v"] = 6, ["IC"] = "Achievement_Character_Human_Female", ["CL"] = "Blacksmith", ["BP"] = "Kul Tiras", ["RE"] = "Theramore", ["AG"] = "24", ["FT"] = "Blacksmith / Enchanter", ["HE"] = "166", ["WE"] = "Slim", }, ["character"] = { ["CO"] = "", ["RP"] = 1, ["CU"] = "", ["XP"] = 2, ["v"] = 14, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["TX"] = "Before you stands Isabelle, a young and rather simple human lady.\n\nBelle is blessed with a slim and feminine body and is with her 166 centimeters of average height. Her eyes are as blue as the ocean surrounding Kul Tiras and she's inherited her mother's cute petite nose.\n\nBelle's hair have a light brown color and is neatly tied in a bun on the back of her head, though still covering the upper half of her ears. She's more often than not seen with a smirk on her lips as she walks confidently down the streets.\n\nWhen it comes to her personality she's developed a \"tough lady\" facade over the years, which is more or less required in the male-dominated choice of profession, and this makes her seem more arrogant and smug than she probably is.", }, ["PS"] = { }, ["HI"] = { }, }, ["TE"] = 3, ["T1"] = { }, ["vote"] = { [3382999904] = 1, }, ["v"] = 1, }, ["misc"] = { ["PE"] = { }, ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 1, ["5"] = 3, ["4"] = 1, ["6"] = 1, }, ["v"] = 14, }, }, ["questlog"] = { }, ["profileName"] = "Isabelle Dawson", ["relation"] = { ["0123124849SiW/Z"] = "BUSINESS", }, }, ["0415211550m:2\\Q"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["RC"] = { 241, -- [1] 0.448840916156769, -- [2] 0.344393074512482, -- [3] "Moonglade - Nighthaven", -- [4] }, ["RA"] = "Kaldorei", ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Moonkin", }, -- [1] }, ["LN"] = "Nightsong", ["BP"] = "Moonglade - Nighthaven", ["PS"] = { { ["ID"] = 1, ["VA"] = 1, }, -- [1] { ["ID"] = 2, ["VA"] = 2, }, -- [2] { ["ID"] = 3, ["VA"] = 3, }, -- [3] { ["ID"] = 4, ["VA"] = 5, }, -- [4] { ["ID"] = 5, ["VA"] = 4, }, -- [5] { ["ID"] = 6, ["VA"] = 4, }, -- [6] { ["ID"] = 7, ["VA"] = 2, }, -- [7] { ["ID"] = 8, ["VA"] = 1, }, -- [8] { ["ID"] = 9, ["VA"] = 5, }, -- [9] { ["ID"] = 10, ["VA"] = 4, }, -- [10] { ["ID"] = 11, ["VA"] = 4, }, -- [11] }, ["FN"] = "Saelbes", ["v"] = 17, ["IC"] = "Achievement_Character_Nightelf_Female", ["EC"] = "Teal", ["CL"] = "Mender", ["AG"] = "Late middle age", ["RE"] = "Moonglade - Nighthaven", ["FT"] = "Wife / Mother / Mender", ["HE"] = "Average", ["WE"] = "Pear-shaped", }, ["character"] = { ["CO"] = "", ["RP"] = 1, ["v"] = 34, ["XP"] = 2, ["CU"] = "", }, ["misc"] = { ["ST"] = { ["1"] = 2, ["3"] = 2, ["2"] = 1, ["5"] = 3, ["4"] = 1, ["6"] = 1, }, ["PE"] = { }, ["v"] = 25, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["TX"] = "Saelbes Nightsong is a kaldorei female in her middle age. She walks graciously on her tiny feet with her pear-shaped curvy body, which would be of average height.\n\nHer ears would be long and straight, she'd have a petite nose and a cute little mouth. Her face would've started to reflect her age quite well, though there are still plenty of her youthful beauty left in it.", ["BK"] = 1, }, ["PS"] = { ["BK"] = 1, }, ["HI"] = { ["BK"] = 1, }, }, ["TE"] = 3, ["T1"] = { ["TX"] = "{h1:c}Saelbes Nightsong{/h1}\n\n{col:ffffff}Saelbes Nightsong is a kaldorei female who is, by the looks of it, in her middle age. She walks graciously on her tiny feet with her slim and slightly curvy body, which would be of average height.\n\nHer ears would be long and straight, she'd have a petite nose and a cute little mouth. Her face would've started to reflect her age quite well, though there are still plenty of her youthful beauty left in it.{/col}", }, ["BK"] = 1, ["v"] = 9, }, }, ["questlog"] = { }, ["profileName"] = "Saelbes Nightsong", ["relation"] = { ["[MSP]Draeguul-ArgentDawn"] = "LOVE", ["0123124849SiW/Z"] = "FAMILY", }, }, ["102100204324b7Z"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["RA"] = "Human", ["RE"] = "Stormwind City", ["LN"] = "Withers", ["BP"] = "Kul Tiras", ["PS"] = { }, ["MI"] = { }, ["v"] = 2, ["CL"] = "Lawyer", ["FN"] = "Robert", ["IC"] = "achievement_worganhead", ["EC"] = "Brown", ["AG"] = "30", ["FT"] = "Lawyer", ["HE"] = "185 cm", ["WE"] = "Fit", }, ["character"] = { ["CO"] = "", ["RP"] = 1, ["CU"] = "", ["XP"] = 2, ["v"] = 86, }, ["misc"] = { ["PE"] = { }, ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 1, ["5"] = 3, ["4"] = 1, ["6"] = 2, }, ["v"] = 14, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { }, ["PS"] = { }, ["HI"] = { }, }, ["TE"] = 1, ["T1"] = { }, ["v"] = 1, }, }, ["questlog"] = { }, ["profileName"] = "Robert Withers", ["relation"] = { ["[MSP]Pamelajill-ArgentDawn"] = "BUSINESS", ["[MSP]Ezohika-ArgentDawn"] = "BUSINESS", }, }, ["121119424970SoO"] = { ["player"] = { ["characteristics"] = { ["CH"] = "5495ff", ["RA"] = "Unknown", ["BP"] = "Unknown", ["LN"] = "Swiftheart", ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "\"Liquid\"", }, -- [1] }, ["PS"] = { }, ["IC"] = "Achievement_Character_Nightelf_Female", ["v"] = 14, ["CL"] = "Illusionist", ["FN"] = "Rhawen", ["RE"] = "Unknown", ["EC"] = "Unknown", ["AG"] = "Unknown", ["FT"] = "Unknown", ["HE"] = "Unknown", ["WE"] = "Unknown", }, ["character"] = { ["CO"] = "", ["RP"] = 1, ["CU"] = "", ["XP"] = 2, ["v"] = 12, }, ["misc"] = { ["PE"] = { }, ["ST"] = { ["1"] = 0, ["3"] = 0, ["2"] = 0, ["5"] = 0, ["4"] = 0, ["6"] = 0, }, ["v"] = 7, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { }, ["PS"] = { }, ["HI"] = { }, }, ["TE"] = 1, ["T1"] = { }, ["v"] = 1, }, }, ["relation"] = { }, ["profileName"] = "Rhawen Swiftheart", }, ["0502203503o+\"\\x"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["LN"] = "Helton", ["EC"] = "Brown", ["PS"] = { }, ["AG"] = "26", ["IC"] = "INV_Misc_Food_148_CupCake", ["EH"] = "583304", ["HE"] = "163cm (5' 4\")", ["CH"] = "ff143e", ["RA"] = "Human", ["RE"] = "The Dainty Damsel", ["v"] = 44, ["CL"] = "Privateer", ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Vella, Vel", }, -- [1] }, ["BP"] = "Stormwind", ["FT"] = "Chief Surgeon || Charity Worker", ["FN"] = "Velouria", ["WE"] = "Petite", }, ["character"] = { ["CO"] = "Curious about the Dainty Damsel? /w me!", ["RP"] = 1, ["v"] = 46, ["XP"] = 2, ["CU"] = "", }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["BK"] = 1, }, ["PS"] = { ["BK"] = 1, }, ["HI"] = { ["BK"] = 1, }, }, ["TE"] = 1, ["T1"] = { ["TX"] = "You've noticed Vella, a 5' 4\" petite ray of sunshine. The young, twenty-something woman rarely holds back her contagious smile and her warm and bright aura.\n\nUp close, the first thing to catch your attention are her gazing brown eyes looking back at you with genuine interest. Eyes that would be framed by shoulder-long hair, burgundy in colour. Continuing down to her body she'd be quietly feminine with wider hips and average bosom, giving the illusion of a pear-shape, and is usually dressed in practically-casual clothes such a pants, shirts and the like.\n\n{link*https://i.imgur.com/D8OCk63.png*reference image}\n\n{img:Interface\\ARCHEOLOGY\\ArchRare-HighborneNightElves:512:256}", }, ["BK"] = 1, ["v"] = 17, }, ["misc"] = { ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 3, ["5"] = 3, ["4"] = 3, ["6"] = 1, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Eyes", ["TX"] = "Attention would be drawn to her genuine and beautiful eyes.", ["IC"] = "INV_Jewelcrafting_DragonsEye03", }, ["3"] = { ["IC"] = "INV_belt_Mail_DraenorLFR_C_01", ["TI"] = "Toolbelt", ["TX"] = "While on duty she'd wear a broad belt with four deep pockets, containing various medical tools and supplies.", ["AC"] = true, }, ["2"] = { ["AC"] = true, ["TI"] = "Innocence", ["TX"] = "Her character would emit a sense of innocence and purity.", ["IC"] = "INV_Misc_Flower_01", }, }, ["v"] = 38, }, }, ["questlog"] = { }, ["relation"] = { ["07221845128iGk0"] = "BUSINESS", ["0121183457Jnc))"] = "BUSINESS", ["0316164715upCJ9"] = "FRIEND", ["0901224653LFf4m"] = "FRIEND", ["0322190731FQyRo"] = "FRIEND", ["0424005203aNsDX"] = "FRIEND", ["0709181608](n.N"] = "LOVE", ["0421105131B5RZn"] = "BUSINESS", ["0528144619fKpPr"] = "BUSINESS", ["[MSP]Ezohika-ArgentDawn"] = "FRIEND", ["1113191905YMDna"] = "BUSINESS", ["0407223306bzrtV"] = "LOVE", ["0413121102FE6OC"] = "BUSINESS", ["0228131910\"{%,s"] = "BUSINESS", ["0309215304mmTrt"] = "BUSINESS", ["0218122258Iljrx"] = "FRIEND", ["0226105709C3hOY"] = "BUSINESS", ["0430231253_&O/G"] = "BUSINESS", ["0313013453jy4a3"] = "BUSINESS", ["1102022135pYVXR"] = "BUSINESS", ["[MSP]Esimbi-ArgentDawn"] = "NEUTRAL", ["0424050241lZD4D"] = "BUSINESS", ["1226223527ZyDIb"] = "BUSINESS", ["0405172807ovJOp"] = "BUSINESS", ["0424210559xhH2L"] = "FRIEND", }, ["profileName"] = "Velouria Helton", }, ["0420004854*|c?`"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["LN"] = "Northrich", ["EC"] = "Blue", ["PS"] = { { ["ID"] = 1, ["VA"] = 2, }, -- [1] { ["ID"] = 2, ["VA"] = 4, }, -- [2] { ["ID"] = 3, ["VA"] = 4, }, -- [3] { ["ID"] = 4, ["VA"] = 2, }, -- [4] { ["ID"] = 5, ["VA"] = 4, }, -- [5] { ["ID"] = 7, ["VA"] = 1, }, -- [6] { ["ID"] = 8, ["VA"] = 2, }, -- [7] { ["ID"] = 9, ["VA"] = 2, }, -- [8] { ["ID"] = 10, ["VA"] = 5, }, -- [9] { ["ID"] = 11, ["VA"] = 2, }, -- [10] { ["ID"] = 6, ["VA"] = 4, }, -- [11] }, ["AG"] = "20", ["CL"] = "Noble", ["EH"] = "0070de", ["HE"] = "Average", ["CH"] = "69ccf0", ["RA"] = "Human", ["RE"] = "Stormwind", ["v"] = 16, ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Bella, Princess", }, -- [1] }, ["BP"] = "Stormwind", ["FT"] = "Noblewoman, Bookworm", ["IC"] = "Ability_Racial_Viciousness", ["TI"] = "Lady", ["FN"] = "Isabella", ["WE"] = "Slim with feminine curves", }, ["character"] = { ["CO"] = "Always approachable!", ["RP"] = 1, ["v"] = 53, ["XP"] = 2, ["CU"] = "", }, ["misc"] = { ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 1, ["5"] = 3, ["4"] = 1, ["6"] = 2, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Well-groomed Lady", ["IC"] = "INV_Misc_Head_Human_02", ["TX"] = "Isabella is clean, tidy and well dressed with a good posture.", }, ["2"] = { ["IC"] = "inv_jewelry_necklace_109", ["TI"] = "Gemstone Necklace", ["AC"] = true, ["TX"] = "Isabella wears a beautiful necklace with a red gemstone pendant.", }, }, ["v"] = 25, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["TX"] = "I'm working on it.. sort of! <3", ["BK"] = 1, }, ["PS"] = { ["BK"] = 1, }, ["HI"] = { ["TX"] = "Now that would be telling ~", ["BK"] = 1, }, }, ["TE"] = 3, ["T1"] = { ["TX"] = "", }, ["BK"] = 1, ["v"] = 3, }, }, ["questlog"] = { }, ["profileName"] = "Isabella Northrich", ["relation"] = { ["0902222504DclVN"] = "FRIEND", ["1009084158Bedfw"] = "NEUTRAL", ["[MSP]Pamelajill-ArgentDawn"] = "FRIEND", ["0720171200MzvCS"] = "BUSINESS", }, }, ["0601172141CngPU"] = { ["profileName"] = "Argent Dawn - Thure", ["player"] = { ["characteristics"] = { ["CL"] = "Monk", ["RA"] = "Human", ["FN"] = "Suresh", ["LN"] = "Songbird", ["MI"] = { }, ["PS"] = { }, ["IC"] = "Achievement_Character_Human_Male", ["v"] = 2, }, ["character"] = { ["RP"] = 1, ["XP"] = 2, ["v"] = 3, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { }, ["PS"] = { }, ["HI"] = { }, }, ["TE"] = 1, ["T1"] = { }, ["v"] = 1, }, ["misc"] = { ["ST"] = { }, ["PE"] = { }, ["v"] = 1, }, }, }, ["0927022943NY$y["] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["RA"] = "Worgen", ["RE"] = "Outskirts of Stormwind", ["LN"] = "Notleigh", ["BP"] = "Gilneas City", ["PS"] = { { ["ID"] = 1, ["VA"] = 4, }, -- [1] { ["ID"] = 2, ["VA"] = 1, }, -- [2] { ["ID"] = 3, ["VA"] = 2, }, -- [3] { ["ID"] = 4, ["VA"] = 3, }, -- [4] { ["ID"] = 5, ["VA"] = 3, }, -- [5] { ["ID"] = 6, ["VA"] = 2, }, -- [6] { ["ID"] = 7, ["VA"] = 1, }, -- [7] { ["ID"] = 8, ["VA"] = 4, }, -- [8] { ["ID"] = 9, ["VA"] = 2, }, -- [9] { ["ID"] = 10, ["VA"] = 2, }, -- [10] { ["ID"] = 11, ["VA"] = 4, }, -- [11] }, ["v"] = 20, ["AG"] = "Late 20s", ["IC"] = "achievement_worganhead", ["FN"] = "Remus", ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Remmy", }, -- [1] }, ["CL"] = "Chef", ["EC"] = "Green", ["FT"] = "Chef || Novice Hunter", ["HE"] = "5' 10", ["WE"] = "Muscular", }, ["character"] = { ["CO"] = "", ["RP"] = 1, ["CU"] = "", ["XP"] = 2, ["v"] = 5, }, ["misc"] = { ["PE"] = { }, ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 1, ["5"] = 3, ["4"] = 1, ["6"] = 2, }, ["v"] = 14, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["TX"] = "You've laid your eyes on Remus, like many men and women before; a 5' 10 long, muscular man in his late 20s.\n\nFrom afar; confidence. In his posture, body language and behind each and every step.\n\nUp close the first to catch your attention is his oblong and handsome face with a neatly kept beard and charming, green eyes - which, combined with the smirk usually visible on his lips, should make him quite desirable for weak-kneed ladies. His hair and eyebrows are, just like his beard, neatly kept which gives you the impression that he seems to care about his looks. His nose is nothing out of the ordinary, and thus seem quite bland compared to his other facial features. ", ["BK"] = 1, }, ["PS"] = { ["BK"] = 1, }, ["HI"] = { ["BK"] = 1, }, }, ["TE"] = 3, ["T1"] = { ["TX"] = "", }, ["BK"] = 1, ["v"] = 32, }, }, ["questlog"] = { }, ["relation"] = { ["[MSP]Pamelajill-ArgentDawn"] = "LOVE", ["[MSP]Ezohika-ArgentDawn"] = "FRIEND", }, ["profileName"] = "Remus Notleigh", }, ["0218142314u87Vb"] = { ["player"] = { ["characteristics"] = { ["CL"] = "Monk", ["RA"] = "Human", ["PS"] = { }, ["MI"] = { }, ["FN"] = "Rochbert", ["IC"] = "Achievement_Character_Human_Male", ["v"] = 1, }, ["character"] = { ["RP"] = 1, ["XP"] = 2, ["v"] = 3, }, ["misc"] = { ["PE"] = { }, ["ST"] = { }, ["v"] = 1, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { }, ["PS"] = { }, ["HI"] = { }, }, ["TE"] = 1, ["T1"] = { }, ["v"] = 1, }, }, ["profileName"] = "Argent Dawn - Rochbert", }, ["0503204036AEJh7"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["LN"] = "Bennett", ["EC"] = "Brown", ["FN"] = "Hannah", ["AG"] = "26", ["CL"] = "Privateer", ["EH"] = "583304", ["HE"] = "163cm (5' 4\")", ["CH"] = "ff143e", ["RA"] = "Human", ["RE"] = "The Dainty Damsel", ["v"] = 43, ["IC"] = "INV_Misc_Food_148_CupCake", ["BP"] = "Stormwind", ["PS"] = { }, ["FT"] = "Barmaid", ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Vella, Vel", }, -- [1] }, ["WE"] = "Petite", }, ["character"] = { ["CO"] = "", ["RP"] = 1, ["CU"] = "Wearing a white napkin in her breastpocket.", ["XP"] = 2, ["v"] = 92, }, ["misc"] = { ["ST"] = { ["1"] = 2, ["3"] = 3, ["2"] = 3, ["5"] = 3, ["4"] = 3, ["6"] = 1, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Eyes", ["IC"] = "INV_Jewelcrafting_DragonsEye03", ["TX"] = "Attention would be drawn to her genuine and beautiful eyes.", }, ["3"] = { ["IC"] = "INV_belt_Mail_DraenorLFR_C_01", ["TI"] = "Toolbelt", ["AC"] = true, ["TX"] = "While on duty she'd wear a broad belt with four deep pockets, containing various medical tools and supplies.", }, ["2"] = { ["AC"] = true, ["TI"] = "Innocence", ["IC"] = "INV_Misc_Flower_01", ["TX"] = "Her character would emit a sense of innocence and purity.", }, }, ["v"] = 38, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["BK"] = 1, }, ["PS"] = { ["BK"] = 1, }, ["HI"] = { ["BK"] = 1, }, }, ["TE"] = 1, ["T1"] = { ["TX"] = "You've noticed Vella, a 5' 4\" petite ray of sunshine. The young, twenty-something woman rarely holds back her contagious smile and her warm and bright aura.\n\nUp close, the first thing to catch your attention are her gazing brown eyes looking back at you with genuine interest. Eyes that would be framed by shoulder-long hair, burgundy in colour. Continuing down to her body she'd be quietly feminine with wider hips and average bosom, giving the illusion of a pear-shape, and is usually dressed in practically-casual clothes such a pants, shirts and the like.\n\n{link*https://i.imgur.com/D8OCk63.png*reference image}\n\n{img:Interface\\ARCHEOLOGY\\ArchRare-HighborneNightElves:512:256}", }, ["BK"] = 1, ["v"] = 17, }, }, ["questlog"] = { }, ["profileName"] = "Hannah Bennet", ["relation"] = { ["0121183457Jnc))"] = "BUSINESS", ["0218122258Iljrx"] = "FRIEND", ["0901224653LFf4m"] = "FRIEND", ["0322190731FQyRo"] = "FRIEND", ["0424005203aNsDX"] = "FRIEND", ["0709181608](n.N"] = "LOVE", ["0421105131B5RZn"] = "BUSINESS", ["0422122431F3Pnh"] = "NONE", ["[MSP]Ezohika-ArgentDawn"] = "FRIEND", ["1113191905YMDna"] = "BUSINESS", ["0407223306bzrtV"] = "LOVE", ["0309215304mmTrt"] = "BUSINESS", ["0226105709C3hOY"] = "BUSINESS", ["1102022135pYVXR"] = "BUSINESS", ["0313013453jy4a3"] = "BUSINESS", ["0430231253_&O/G"] = "BUSINESS", ["0316164715upCJ9"] = "FRIEND", ["[MSP]Esimbi-ArgentDawn"] = "NEUTRAL", ["0424050241lZD4D"] = "BUSINESS", ["1226223527ZyDIb"] = "BUSINESS", ["0405172807ovJOp"] = "BUSINESS", ["0228131910\"{%,s"] = "BUSINESS", }, }, ["0412013735of5N<"] = { ["inventory"] = { ["init"] = true, ["id"] = "main", ["totalWeight"] = 500, ["content"] = { ["17"] = { ["id"] = "bag", ["totalWeight"] = 500, ["content"] = { }, ["totalValue"] = 0, }, }, ["totalValue"] = 0, }, ["player"] = { ["characteristics"] = { ["RA"] = "Kaldorei", ["LN"] = "Amberbranch", ["MI"] = { { ["IC"] = "Ability_Hunter_BeastCall", ["NA"] = "Nickname", ["VA"] = "Boo", }, -- [1] }, ["FN"] = "Pica", ["PS"] = { { ["ID"] = 1, ["VA"] = 2, }, -- [1] { ["ID"] = 2, ["VA"] = 1, }, -- [2] { ["ID"] = 3, ["VA"] = 2, }, -- [3] { ["ID"] = 4, ["VA"] = 2, }, -- [4] { ["ID"] = 5, ["VA"] = 3, }, -- [5] { ["ID"] = 6, ["VA"] = 2, }, -- [6] { ["ID"] = 7, ["VA"] = 3, }, -- [7] { ["ID"] = 8, ["VA"] = 4, }, -- [8] { ["ID"] = 9, ["VA"] = 2, }, -- [9] { ["ID"] = 10, ["VA"] = 1, }, -- [10] { ["ID"] = 11, ["VA"] = 3, }, -- [11] }, ["v"] = 14, ["IC"] = "Achievement_Character_Nightelf_Female", ["EC"] = "White-like blue", ["CL"] = "Courier", ["AG"] = "Young", ["RE"] = "Ironforge", ["FT"] = "Senior Courier, Mother", ["HE"] = "Short", ["WE"] = "Feminine", }, ["character"] = { ["CO"] = "", ["RP"] = 1, ["v"] = 19, ["XP"] = 2, ["CU"] = "", }, ["misc"] = { ["ST"] = { ["1"] = 2, ["3"] = 2, ["2"] = 3, ["5"] = 4, ["4"] = 1, ["6"] = 1, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Attractive", ["TX"] = "People usually find this elf attractive.", ["IC"] = "Achievement_Leader_Tyrande_Whisperwind", }, ["2"] = { ["AC"] = true, ["TI"] = "Courier Bag", ["TX"] = "This elf would be carrying a green courier bag when she's in her work outfit.", ["IC"] = "INV_Misc_Bag_35", }, }, ["v"] = 26, }, ["about"] = { ["T2"] = { }, ["T3"] = { ["PH"] = { ["TX"] = "Let's rewrite this old mess.. one day! <3", ["BK"] = 1, }, ["PS"] = { ["BK"] = 1, }, ["HI"] = { ["BK"] = 1, }, }, ["TE"] = 1, ["T1"] = { ["TX"] = "Let's rewrite this old mess.. someday! <3\n\n{link*https://i.imgur.com/dEyUupY.jpg*reference image}\n", }, ["BK"] = 1, ["v"] = 11, }, }, ["questlog"] = { }, ["profileName"] = "Pica Amberbranch", ["relation"] = { ["[MSP]Alincial-ArgentDawn"] = "BUSINESS", ["1227201734ZXySc"] = "LOVE", ["0123124134HD&&U"] = "FRIEND", ["0731135945\\aok7"] = "LOVE", ["[MSP]Ezohika-ArgentDawn"] = "FRIEND", ["1124193718tQGPR"] = "BUSINESS", ["0801041710AstnI"] = "BUSINESS", ["1124135708O2FHS"] = "BUSINESS", ["1024184529Nvof7"] = "FRIEND", ["0327185223f2BaW"] = "LOVE", ["0403231051QgInI"] = "LOVE", }, }, } TRP3_Characters = { ["Saelbes-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 164, ["DE"] = 165, ["AE"] = 162, ["GC"] = 157, ["FC"] = 163, ["IC"] = 157, ["AH"] = 162, ["CO"] = 7, ["GF"] = 157, ["NA"] = 161, ["TT"] = 558, ["RA"] = 160, ["RC"] = 164, ["HB"] = 71, ["VA"] = 157, ["NT"] = 162, ["VP"] = 157, ["AG"] = 165, ["GU"] = 157, ["GS"] = 157, ["GR"] = 157, ["FR"] = 161, ["NI"] = 72, ["AW"] = 164, ["CU"] = 325, }, ["profileID"] = "0415211550m:2\\Q", }, ["Isabèllé-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 183, ["HI"] = 4, ["DE"] = 115, ["AE"] = 188, ["GC"] = 177, ["FC"] = 182, ["IC"] = 182, ["AH"] = 183, ["CO"] = 97, ["GF"] = 177, ["NA"] = 188, ["TT"] = 754, ["RA"] = 177, ["PX"] = 4, ["RC"] = 189, ["NT"] = 187, ["VA"] = 177, ["AW"] = 184, ["HB"] = 184, ["NI"] = 176, ["GS"] = 177, ["FR"] = 180, ["GU"] = 177, ["GR"] = 177, ["AG"] = 186, ["VP"] = 177, ["CU"] = 386, }, ["profileID"] = "0303204953EBSM8", }, ["Flöyd-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 47, ["DE"] = 11, ["NT"] = 55, ["GC"] = 41, ["FC"] = 50, ["IC"] = 44, ["AH"] = 30, ["CO"] = 5, ["GF"] = 41, ["NA"] = 54, ["TT"] = 246, ["VP"] = 41, ["RA"] = 45, ["AG"] = 51, ["RC"] = 49, ["AW"] = 32, ["VA"] = 41, ["GU"] = 41, ["GR"] = 41, ["FR"] = 44, ["PX"] = 8, ["GS"] = 41, ["NI"] = 4, ["HB"] = 29, ["MO"] = 1, ["AE"] = 30, ["CU"] = 141, }, ["profileID"] = "102100204324b7Z", }, ["Tillylilly-Draenor"] = { ["mspver"] = { ["RA"] = 2, ["RC"] = 2, ["IC"] = 2, ["VA"] = 2, ["GC"] = 2, ["FC"] = 3, ["VP"] = 2, ["GU"] = 2, ["FR"] = 3, ["GR"] = 2, ["GF"] = 2, ["NA"] = 2, ["GS"] = 2, ["TT"] = 5, }, ["profileID"] = "0926014530!p\"]7", }, ["Keestra-ArgentDawn"] = { ["chat_last_language_used"] = 1, ["mspver"] = { ["RA"] = 5, ["RC"] = 5, ["IC"] = 5, ["VA"] = 5, ["GC"] = 5, ["FC"] = 7, ["VP"] = 5, ["GU"] = 5, ["FR"] = 7, ["GR"] = 5, ["GF"] = 5, ["NA"] = 5, ["GS"] = 5, ["TT"] = 12, }, ["profileID"] = "010314162168wUk", }, ["Jyggen-Stormscale"] = { ["mspver"] = { ["RA"] = 2, ["RC"] = 2, ["VP"] = 2, ["VA"] = 2, ["GC"] = 2, ["FC"] = 3, ["IC"] = 2, ["FR"] = 3, ["GS"] = 2, ["GR"] = 2, ["GF"] = 2, ["NA"] = 2, ["GU"] = 2, ["TT"] = 5, }, ["profileID"] = "0720125453CO4PK", }, ["Jyggen-Draenor"] = { ["mspver"] = { ["RA"] = 2, ["RC"] = 2, ["IC"] = 2, ["VA"] = 2, ["GC"] = 2, ["FC"] = 3, ["VP"] = 2, ["GR"] = 2, ["GS"] = 2, ["GU"] = 2, ["GF"] = 2, ["NA"] = 2, ["FR"] = 3, ["TT"] = 5, }, ["profileID"] = "09261422054GA.+", }, ["Jyggis-Draenor"] = { ["mspver"] = { ["RA"] = 3, ["RC"] = 3, ["IC"] = 3, ["VA"] = 3, ["GC"] = 3, ["FC"] = 4, ["VP"] = 3, ["GR"] = 3, ["GS"] = 3, ["GU"] = 3, ["GF"] = 3, ["NA"] = 3, ["FR"] = 4, ["TT"] = 7, }, ["profileID"] = "0926014720t)?4Y", }, ["Velouría-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 292, ["AE"] = 289, ["GC"] = 289, ["FC"] = 294, ["VP"] = 289, ["AH"] = 200, ["CO"] = 301, ["GF"] = 289, ["NA"] = 295, ["TT"] = 1882, ["RA"] = 289, ["RC"] = 296, ["AW"] = 197, ["VA"] = 289, ["IC"] = 290, ["NI"] = 289, ["GS"] = 289, ["GR"] = 289, ["FR"] = 290, ["GU"] = 289, ["AG"] = 290, ["NT"] = 307, ["HB"] = 197, ["CU"] = 1127, }, ["profileID"] = "0502203503o+\"\\x", }, ["Rëmus-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 119, ["HI"] = 30, ["DE"] = 99, ["AE"] = 238, ["GC"] = 202, ["FC"] = 211, ["VP"] = 202, ["AH"] = 240, ["CO"] = 9, ["GF"] = 202, ["NA"] = 232, ["TT"] = 1039, ["RA"] = 229, ["PX"] = 41, ["RC"] = 231, ["AG"] = 236, ["VA"] = 202, ["NT"] = 238, ["AW"] = 235, ["GR"] = 202, ["GS"] = 202, ["FR"] = 205, ["GU"] = 202, ["NI"] = 115, ["HB"] = 241, ["IC"] = 217, ["CU"] = 623, }, ["profileID"] = "0927022943NY$y[", }, ["Rochbert-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 3, ["HI"] = 3, ["DE"] = 3, ["NT"] = 3, ["GC"] = 2, ["FC"] = 3, ["VP"] = 2, ["AH"] = 3, ["CO"] = 2, ["GF"] = 2, ["NA"] = 5, ["TT"] = 10, ["RA"] = 2, ["PX"] = 3, ["RC"] = 5, ["AG"] = 3, ["VA"] = 2, ["AE"] = 3, ["AW"] = 3, ["NI"] = 1, ["FR"] = 3, ["GS"] = 2, ["GU"] = 2, ["GR"] = 2, ["HB"] = 3, ["IC"] = 5, ["CU"] = 2, }, ["profileID"] = "102100204324b7Z", }, ["Trädform-Auchindoun"] = { ["mspver"] = { ["RA"] = 1, ["RC"] = 1, ["VP"] = 1, ["VA"] = 1, ["GC"] = 1, ["FC"] = 2, ["IC"] = 1, ["FR"] = 2, ["GS"] = 1, ["GR"] = 1, ["GF"] = 1, ["NA"] = 1, ["GU"] = 1, ["TT"] = 3, }, ["profileID"] = "1227161328S\"d[e", }, ["Isabèllá-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 316, ["HI"] = 202, ["DE"] = 202, ["AE"] = 429, ["GC"] = 291, ["FC"] = 295, ["IC"] = 305, ["AH"] = 318, ["CO"] = 177, ["GF"] = 291, ["NA"] = 322, ["TT"] = 1521, ["PX"] = 172, ["RA"] = 317, ["VP"] = 291, ["RC"] = 320, ["NT"] = 324, ["VA"] = 291, ["GR"] = 291, ["GU"] = 291, ["GS"] = 291, ["HB"] = 317, ["FR"] = 295, ["NI"] = 250, ["AW"] = 306, ["MO"] = 40, ["AG"] = 318, ["CU"] = 977, }, ["profileID"] = "0420004854*|c?`", }, ["Thure-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["RA"] = 3, ["RC"] = 3, ["VP"] = 3, ["VA"] = 3, ["GC"] = 3, ["FC"] = 4, ["IC"] = 3, ["FR"] = 4, ["GS"] = 3, ["GR"] = 3, ["GF"] = 3, ["NA"] = 4, ["GU"] = 3, ["TT"] = 8, }, ["profileID"] = "0601172141CngPU", }, ["Picaboo-ArgentDawn"] = { ["chat_last_language_used"] = 7, ["mspver"] = { ["HH"] = 413, ["HI"] = 257, ["DE"] = 415, ["AE"] = 412, ["GC"] = 413, ["AG"] = 412, ["IC"] = 415, ["AH"] = 412, ["CO"] = 21, ["GF"] = 413, ["NA"] = 419, ["TT"] = 1352, ["RA"] = 415, ["RC"] = 420, ["HB"] = 5, ["VA"] = 413, ["AW"] = 420, ["NT"] = 421, ["VP"] = 413, ["NI"] = 419, ["GS"] = 413, ["GU"] = 413, ["FR"] = 413, ["GR"] = 413, ["FC"] = 419, ["CU"] = 660, }, ["profileID"] = "0412013735of5N<", }, ["Jyggen-Auchindoun"] = { ["mspver"] = { ["RA"] = 12, ["RC"] = 12, ["VP"] = 12, ["VA"] = 12, ["GC"] = 12, ["FC"] = 13, ["IC"] = 12, ["GS"] = 12, ["FR"] = 13, ["GU"] = 12, ["GF"] = 12, ["NA"] = 12, ["GR"] = 12, ["TT"] = 25, }, ["profileID"] = "0624195800I*oz/", }, ["Sîd-ArgentDawn"] = { ["mspver"] = { ["HH"] = 32, ["NT"] = 28, ["GC"] = 36, ["FC"] = 39, ["VP"] = 36, ["CO"] = 2, ["GF"] = 36, ["NA"] = 40, ["TT"] = 117, ["RA"] = 39, ["RC"] = 39, ["VA"] = 36, ["HB"] = 32, ["GU"] = 36, ["FR"] = 39, ["GR"] = 36, ["IC"] = 39, ["AG"] = 32, ["GS"] = 36, ["CU"] = 59, }, ["profileID"] = "0122204452Tv0~=", }, } TRP3_Configuration = { ["toolbar_content_bb_extended_drop"] = true, ["register_mature_filter"] = false, ["CONFIG_GLANCE_PARENT"] = "TRP3_TargetFrame", ["target_content_aa_player_b_music"] = true, ["toolbar_icon_size"] = 25, ["tooltip_char_target"] = true, ["chat_ooc"] = true, ["tooltip_pets_icons"] = true, ["register_map_location_ooc"] = true, ["chat_name"] = 3, ["chat_use_CHAT_MSG_SAY"] = true, ["target_icon_size"] = 30, ["toolbar_show_on_login"] = false, ["CONFIG_TARGET_POS_Y"] = 186.499969482422, ["nameplates_hide_non_roleplay"] = false, ["minimap_show"] = true, ["target_content_quest_action_LISTEN"] = true, ["chat_use_CHAT_MSG_WHISPER"] = true, ["tooltip_char_ooc"] = true, ["tooltip_pets_owner"] = true, ["tooltip_char_icons"] = true, ["target_use"] = 1, ["chat_yell_no_emote"] = false, ["comm_broad_chan"] = "xtensionxtooltip2", ["chat_ooc_color"] = "aaaaaa", ["target_content_bb_companion_profile_mount"] = true, ["comm_broad_use"] = true, ["nameplates_only_in_character"] = true, ["extended_music_method"] = "a", ["chat_ooc_pattern"] = "(%(.-%))", ["tooltip_char_spacing"] = true, ["tooltip_char_realm"] = true, ["tooltip_pets_notif"] = true, ["CONFIG_TOOLTIP_SIZE"] = 11, ["register_map_location_pvp"] = false, ["chat_use_CHAT_MSG_YELL"] = true, ["chat_insert_full_rp_name"] = true, ["CONFIG_GLANCE_ANCHOR_X"] = 24, ["extended_sounds_method"] = "p", ["tooltip_char_terSize"] = 10, ["chat_use_CHAT_MSG_OFFICER"] = true, ["tooltip_char_color"] = true, ["extended_weight_unit"] = "g", ["register_auto_purge_mode"] = 864000, ["chat_emote"] = true, ["tooltip_char_contrast"] = false, ["tooltip_char_relation"] = true, ["tooltip_char_mainSize"] = 16, ["CONFIG_TARGET_POS_A"] = "BOTTOM", ["CONFIG_TOOLBAR_POS_A"] = "TOPLEFT", ["toolbar_content_bb_extended_tools"] = true, ["minimap_icon_position"] = { ["hide"] = false, }, ["nameplates_pet_names"] = true, ["tooltip_no_fade_out"] = false, ["tooltip_pets_info"] = true, ["CONFIG_GLANCE_TT_ANCHOR"] = "LEFT", ["target_content_aa_player_e_inspect"] = true, ["chat_emote_pattern"] = "(%*.-%*)", ["nameplates_enable"] = true, ["tooltip_char_rc"] = true, ["tooltip_char_guild"] = true, ["tooltip_char_ft"] = true, ["remove_realm"] = true, ["toolbar_content_aa_trp3_c"] = true, ["extended_sounds_active"] = true, ["CONFIG_TARGET_POS_X"] = -1.99981796741486, ["extended_sounds_maxrange"] = 100, ["target_content_aa_player_w_mature_flag"] = true, ["toolbar_content_aa_trp3_rpstatus"] = true, ["register_auto_add"] = true, ["tooltip_char_combat"] = false, ["tooltip_char_Anchor"] = "ANCHOR_TOPRIGHT", ["tooltip_in_character_only"] = false, ["tooltip_profile_only"] = true, ["chat_use_CHAT_MSG_RAID_LEADER"] = true, ["chat_use_CHAT_MSG_GUILD"] = true, ["tooltip_char_AnchoredFrame"] = "GameTooltip", ["AddonLocale"] = "enUS", ["tooltip_char_current_size"] = 140, ["ui_animations"] = true, ["chat_npc_talk_p"] = "|| ", ["msp_t3"] = true, ["CONFIG_TOOLBAR_POS_Y"] = -42.9997940063477, ["target_content_quest_action_ACTION"] = true, ["tooltip_char_subSize"] = 12, ["toolbar_content_aa_trp3_a"] = true, ["extended_music_active"] = true, ["toolbar_content_hh_player_e_quest"] = true, ["target_content_aa_player_w_mature_white_list"] = true, ["chat_use_CHAT_MSG_WHISPER_INFORM"] = true, ["target_content_bb_companion_profile"] = true, ["new_version_alert"] = true, ["april_fools"] = true, ["chat_use_CHAT_MSG_PARTY"] = true, ["target_content_aa_player_z_ignore"] = true, ["target_content_aa_player_c_glance_presets"] = true, ["CONFIG_TOOLBAR_POS_X"] = 143.99934387207, ["register_about_use_vote"] = false, ["chat_show_icon"] = false, ["toolbar_content_ww_trp3_languages"] = true, ["chat_use_CHAT_MSG_EMOTE"] = true, ["chat_use_CHAT_MSG_RAID"] = true, ["chat_use_CHAT_MSG_PARTY_LEADER"] = true, ["MODULE_ACTIVATION"] = { ["trp3_chatframes"] = true, ["trp3_tool_bar"] = true, ["trp3_prat"] = true, ["trp3_tooltips"] = true, ["trp3_kuinameplates"] = true, ["trp3_extended"] = true, ["trp3_glance_bar"] = true, ["trp3_wim"] = true, ["trp3_extended_tools"] = true, ["trp3_target_bar"] = true, ["trp3_databroker"] = true, ["trp3_mature_filter"] = true, ["trp3_tiptac"] = true, ["trp3_msp"] = true, }, ["target_content_quest_action_LOOK"] = true, ["toolbar_content_bb_extended_sounds"] = true, ["CONFIG_GLANCE_ANCHOR_Y"] = -14, ["heavy_profile_alert"] = true, ["chat_use_CHAT_MSG_TEXT_EMOTE"] = true, ["MAP_BUTTON_POSITION"] = "BOTTOMLEFT", ["target_content_quest_action_TALK"] = true, ["chat_npc_talk"] = true, ["toolbar_content_bb_trp3_npctalk"] = true, ["tooltip_char_current"] = true, ["toolbar_content_aa_trp3_b"] = true, ["notification_add_character"] = 1, ["target_content_aa_player_d_relation"] = true, ["tooltip_char_HideOriginal"] = true, ["tooltip_crop_text"] = true, ["ui_sounds"] = true, ["tooltip_char_title"] = true, ["chat_color_contrast"] = false, ["CONFIG_GLANCE_LOCK"] = true, ["register_map_location"] = true, ["target_content_aa_player_w_mature_remove_white_list"] = true, ["target_content_aa_player_a_page"] = true, ["nameplates_use_custom_color"] = true, ["chat_color"] = true, ["toolbar_max_per_line"] = 7, ["nameplates_show_titles"] = false, ["tooltip_char_notif"] = true, ["tooltip_pets_title"] = true, ["register_sanitization"] = true, ["toolbar_content_hh_player_d_inventory"] = true, } TRP3_Flyway = { ["currentBuild"] = 5, ["log"] = "Patch applied from 5 to 5 on 29/03/17 13:36:50", } TRP3_Presets = { ["peek"] = { }, ["peekBar"] = { }, ["peekCategory"] = { }, } TRP3_Companions = { ["register"] = { ["0218194241>*w2W"] = { ["data"] = { ["TX"] = "A round stone disc with cloud markings. Mihu sometimes carries it around with him on his journeys.", ["read"] = false, ["IC"] = "Ability_Mount_CloudMount", ["TI"] = "Mihu's Cloud Disc", ["NA"] = "Cloud Disc", ["BK"] = 19, ["v"] = 4, }, ["PE"] = { ["1"] = { ["AC"] = false, ["TI"] = "A", ["IC"] = "6BF_Blackrock_Nova", }, ["v"] = 6, }, ["links"] = { ["Mihu-ArgentDawn_130092"] = 1, }, }, ["04181823245do@P"] = { ["data"] = { ["IC"] = "Spell_Holy_CrusaderAura", ["read"] = true, ["NH"] = "30faff", ["NA"] = "Hewitt", ["BK"] = 1, ["TI"] = "Grand Steed of The Argent Crusade", ["v"] = 3, }, ["PE"] = { ["v"] = 1, }, ["links"] = { ["Preas-ArgentDawn_65640"] = 1, }, }, ["0430112221:16=V"] = { ["PE"] = { ["v"] = 1, }, ["data"] = { ["IC"] = "INV_RavenLordPet", ["read"] = true, ["NH"] = "f6ff40", ["NA"] = "Sooty 'The Swift' Raven", ["BK"] = 1, ["TI"] = "Has a small band attached to his foot.", ["v"] = 3, }, ["links"] = { ["Constancé-ArgentDawn_Sooty"] = 1, }, }, ["0119064920`+@sd"] = { ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["read"] = true, ["NA"] = "Bones", ["BK"] = 1, ["v"] = 2, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Winged Undead", ["TX"] = "This creation of bones and armor has the capabillity of flight.", ["IC"] = "Ability_Mount_EbonBlade", }, ["v"] = 2, }, ["links"] = { ["Nirkan-ArgentDawn_54729"] = 1, }, }, ["0530224829#|='g"] = { ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["read"] = true, ["NA"] = "Bop", ["TI"] = "Podling friend", ["BK"] = 1, ["v"] = 4, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Friendly", ["TX"] = "Friendlier than your usual murderous podling, usually smiling. ", ["IC"] = "Spell_Misc_EmotionHappy", }, ["v"] = 1, }, ["links"] = { ["Araad-ArgentDawn_Bop"] = 1, }, }, ["0428201125sl~z?"] = { ["PE"] = { ["v"] = 1, }, ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["read"] = true, ["NA"] = "Shi-Huo", ["BK"] = 1, ["v"] = 2, }, ["links"] = { ["Blazingkeg-ArgentDawn_113199"] = 1, }, }, ["0416153634#IPA."] = { ["PE"] = { ["v"] = 1, }, ["data"] = { ["IC"] = "INV_PandarenSerpentMount_Blue", ["read"] = true, ["NH"] = "4460ff", ["NA"] = "Tangfei-Xi", ["BK"] = 1, ["TI"] = "The Elder Cloud Serpent", ["v"] = 2, }, ["links"] = { ["Xiaojían-ArgentDawn_123992"] = 1, }, }, ["0428095606\"?k'c"] = { ["PE"] = { ["v"] = 1, }, ["data"] = { ["IC"] = "INV_Pet_Cats_SilverTabbyCat", ["read"] = false, ["NH"] = "686868", ["BK"] = 1, ["NA"] = "Tobias", ["TX"] = "Though Tobias may very well once have been the prettiest cat around, that was some time ago; his once black and sleek mane has turned ruffled with age, despite how hard Melanie tries to brush him neat again. A tiny scar has split the tip of his left ear from a scrap in the past, but otherwise her old friend looks as sagely as a wizard - albeit quite a lot cuter.", ["v"] = 4, }, ["links"] = { ["Melanie-ArgentDawn_Tobias"] = 1, }, }, ["0419163157H#<jS"] = { ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Skulls", ["IC"] = "INV_MISC_BONE_HUMANSKULL_02", ["TX"] = "Adorned with many skulls in a fashion that would be displaying victories of the rider in combat", }, ["v"] = 2, }, ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["read"] = true, ["TI"] = "The Red Terror - Faithful Rylak of Mariel Dawnsong", ["BK"] = 1, ["NA"] = "Thal'renar", ["v"] = 2, }, ["links"] = { ["Thyandria-ArgentDawn_153489"] = 1, }, }, ["0420154210z1FyD"] = { ["data"] = { ["TX"] = "Barbary is a Ram that hails from the Blasted Lands. Sheln saved him from perishing at the jaws of a Basilisk and has befriended, and 'trained' the beast since. He is cross-eyed, and has two almost disfigured horns that have curled at odd angles, not inwards. His fur is grey, and unkempt, and his hooves slightly overgrown, chipped in many places.\n\nDespite his best attempts, he often struggles to comprehend commands. His saving trait however, is his speed. This Ram can sprint with the best of them.", ["read"] = false, ["NA"] = "Barbary", ["BK"] = 10, ["IC"] = "INV_Box_PetCarrier_01", ["v"] = 4, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Disfigured.", ["TX"] = "This Ram's horns aren't like the norm - the curl out in odd angles, not inwards. It also appears to be cross-eyed...", ["IC"] = "Ability_Mount_MountainRam", }, ["v"] = 2, }, ["links"] = { ["Sheln-ArgentDawn_6777"] = 1, }, }, ["0523201259+*),:"] = { ["data"] = { ["IC"] = "INV_Pet_Cats_SilverTabbyCat", ["read"] = false, ["NH"] = "a1934b", ["TX"] = "Bought by Sam while he was insanely high.", ["BK"] = 1, ["TI"] = "Loyal Feline", ["NA"] = "Cat", ["v"] = 6, }, ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Cat", ["TX"] = "Cat is a cat and not a spider, no matter what you may think, it is a cat.", ["IC"] = "Ability_Hunter_CatlikeReflexes", }, ["2"] = { ["AC"] = true, ["TI"] = "Spidery Legs.", ["TX"] = "Cat has eight spidery little legs.", ["IC"] = "INV_Misc_MonsterSpiderCarapace_01", }, ["3"] = { ["AC"] = true, ["TI"] = "Spidery Eyes", ["TX"] = "Cat also has eight lovely little spidery eyes.", ["IC"] = "INV_Fishing_Innards_Eye", }, ["v"] = 1, }, ["links"] = { ["Holstaed-ArgentDawn_Cat"] = 1, }, }, ["0119064203&t!&I"] = { ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Unholy Presence", ["IC"] = "Spell_DeathKnight_SummonDeathCharger", ["TX"] = "This steed carries an unnatural, eerie presence with it.", }, ["v"] = 3, ["2"] = { ["AC"] = true, ["TI"] = "Armor", ["IC"] = "INV_Misc_ArmorKit_31", ["TX"] = "This steed carries Purified saronite plating.", }, }, ["data"] = { ["TX"] = "The creature before you seems to be made of somewhat sturdy, Dark flesh. it stands a bit above a nornal warhorse, and a bit broader too. Even if that improves nothing, given it's undead nature.", ["read"] = false, ["BK"] = 1, ["NA"] = "Deathcharger", ["IC"] = "INV_Box_PetCarrier_01", ["v"] = 2, }, ["links"] = { ["Nirkan-ArgentDawn_48778"] = 1, }, }, ["0504204702rhNbs"] = { ["PE"] = { ["v"] = 1, }, ["data"] = { ["TX"] = "Paguri befriended minion from douged's childhood", ["read"] = false, ["BK"] = 1, ["NA"] = "Paguri", ["IC"] = "Ability_Warlock_EmpoweredImp", ["v"] = 5, }, ["links"] = { ["Douged-ArgentDawn_Paguri"] = 1, }, }, ["05242253016By$^"] = { ["PE"] = { ["v"] = 1, }, ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["read"] = true, ["NH"] = "870009", ["BK"] = 1, ["NA"] = "Shadow The Wolf", ["TI"] = "The War-Wolf", ["v"] = 2, }, ["links"] = { ["Trílax-ArgentDawn_Shadow"] = 1, }, }, ["0510162621Jj#rU"] = { ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Cat", ["IC"] = "INV_Pet_Cats_BombayCat", ["TX"] = "It's a damn cat!", }, ["v"] = 1, }, ["data"] = { ["TX"] = "A black Bombay Cat!", ["read"] = false, ["IC"] = "INV_Pet_Cats_BombayCat", ["NA"] = "Vilynn", ["BK"] = 1, ["TI"] = "Danielus' Assistant", ["v"] = 4, }, ["links"] = { ["Danielus-ArgentDawn_Feline Vilynn"] = 1, }, }, ["04152319090s^ke"] = { ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["NA"] = "Uva", ["read"] = true, ["v"] = 1, }, ["PE"] = { ["v"] = 1, }, ["links"] = { ["Nevaaria-ArgentDawn_Uva"] = 1, }, }, ["1020142351\\Qz=L"] = { ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Daggers", ["IC"] = "INV_Sword_12", ["TX"] = "Carries two daggers in fitting scabbards around the waist.", }, ["v"] = 14, ["2"] = { ["AC"] = true, ["TI"] = "Sarong", ["IC"] = "INV_Kilt_Cloth_01", ["TX"] = "Wears an exotic sarong around the waist as well as a belt with two scabbard.", }, }, ["data"] = { ["TX"] = "Vilynn is by appearance a standard succubus with a soft-pink skin and scarlet-red marking on her arms and legs. She has long thin brown hair and deep cyan-blue eyes to finish her alluring appearance.\n\nHowever unlike most succubi she seems to wear a short sarong around her waist and a belt with two scabbards attached, each containing a dagger.\n{img:Interface\\ARCHEOLOGY\\ArchRare-ZinRokhDestroyer:512:256}", ["read"] = false, ["IC"] = "Spell_Shadow_SummonSuccubus", ["TI"] = "Danielus' Assistant", ["NA"] = "Vilynn", ["BK"] = 1, ["v"] = 9, }, ["links"] = { ["Danielus-ArgentDawn_Vilynn"] = 1, }, }, ["0426015053=Y3RN"] = { ["PE"] = { ["v"] = 1, }, ["data"] = { ["TX"] = "Aatu is a fairly large animal. Quite often people mistake him for a wolf, to which Randulf fervently states that he is a dog. Whether he is a dog or not, it is quite clear by his size and looks that there is at least some wolf in that mix, and quite a lot at that. \n\nMost of his fur is black, with dark grey variations around, and it is both thickest and darkest around Aatu's neck. Here and there scars are visible, where the fur has not grown out again. The most prominent one is across his muzzle.", ["read"] = false, ["IC"] = "Ability_Hunter_Pet_Wolf", ["NA"] = "Aatu", ["BK"] = 1, ["TI"] = "Wolfdog", ["v"] = 6, }, ["links"] = { ["Randulf-ArgentDawn_Aatu"] = 1, }, }, ["0504005051,B)[%"] = { ["PE"] = { ["1"] = { ["AC"] = true, ["TI"] = "Smell of Chicken", ["IC"] = "Spell_Magic_PolymorphChicken", ["TX"] = "Smells tasty.", }, ["v"] = 3, ["2"] = { ["AC"] = true, ["TI"] = "Fire fighting equipment", ["IC"] = "Spell_Misc_WateringCan", ["TX"] = "Spray bottle attached.", }, }, ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["read"] = false, ["NH"] = "ff2026", ["TX"] = "This Chicken smells awesome. He's the best chicken around, he carries a water bottle spray gun with him to help fight fires. Aw yeah.", ["BK"] = 1, ["NA"] = "Henry The Firefightin' chicken!", ["TI"] = "Best finger lickin' chicken!", ["v"] = 3, }, ["links"] = { ["Varqnite-ArgentDawn_Henry"] = 1, }, }, }, ["player"] = { ["0412020548,Lk^("] = { ["profileName"] = "Beaky", ["PE"] = { ["v"] = 1, }, ["data"] = { ["IC"] = "INV_Box_PetCarrier_01", ["BK"] = 1, ["NA"] = "Beaky", ["v"] = 2, }, ["links"] = { }, }, }, } TRP3_MatureFilter = { ["whitelist"] = { }, ["dictionary"] = { ["incest"] = 1, ["vaginal"] = 1, ["penis"] = 1, ["cock"] = 1, ["tits"] = 1, ["rape"] = 1, ["ass"] = 1, ["dick"] = 1, ["futa"] = 1, ["f%-list"] = 1, ["cum"] = 1, ["scat"] = 1, ["gore"] = 1, ["bulge"] = 1, ["anal"] = 1, ["cunt"] = 1, }, } TRP3_StashedData = nil
mit
clemty/OpenRA
mods/cnc/maps/gdi05a/gdi05a.lua
4
6649
RepairThreshold = { Easy = 0.3, Normal = 0.6, Hard = 0.9 } ActorRemovals = { Easy = { Actor167, Actor168, Actor190, Actor191, Actor193, Actor194, Actor196, Actor198, Actor200 }, Normal = { Actor167, Actor194, Actor196, Actor197 }, Hard = { }, } GdiTanks = { "mtnk", "mtnk" } GdiApc = { "apc" } GdiInfantry = { "e1", "e1", "e1", "e1", "e1", "e2", "e2", "e2", "e2", "e2" } GdiBase = { GdiNuke1, GdiNuke2, GdiProc, GdiSilo1, GdiSilo2, GdiPyle, GdiWeap, GdiHarv } NodSams = { Sam1, Sam2, Sam3, Sam4 } CoreNodBase = { NodConYard, NodRefinery, HandOfNod, Airfield } Grd1UnitTypes = { "bggy" } Grd1Path = { waypoint4.Location, waypoint5.Location, waypoint10.Location } Grd1Delay = { Easy = DateTime.Minutes(2), Normal = DateTime.Minutes(1), Hard = DateTime.Seconds(30) } Grd2UnitTypes = { "bggy" } Grd2Path = { waypoint0.Location, waypoint1.Location, waypoint2.Location } Grd3Units = { GuardTank1, GuardTank2 } Grd3Path = { waypoint4.Location, waypoint5.Location, waypoint9.Location } AttackDelayMin = { Easy = DateTime.Minutes(1), Normal = DateTime.Seconds(45), Hard = DateTime.Seconds(30) } AttackDelayMax = { Easy = DateTime.Minutes(2), Normal = DateTime.Seconds(90), Hard = DateTime.Minutes(1) } AttackUnitTypes = { Easy = { { HandOfNod, { "e1", "e1" } }, { HandOfNod, { "e1", "e3" } }, { HandOfNod, { "e1", "e1", "e3" } }, { HandOfNod, { "e1", "e3", "e3" } }, }, Normal = { { HandOfNod, { "e1", "e1", "e3" } }, { HandOfNod, { "e1", "e3", "e3" } }, { HandOfNod, { "e1", "e1", "e3", "e3" } }, { Airfield, { "bggy" } }, }, Hard = { { HandOfNod, { "e1", "e1", "e3", "e3" } }, { HandOfNod, { "e1", "e1", "e1", "e3", "e3" } }, { HandOfNod, { "e1", "e1", "e3", "e3", "e3" } }, { Airfield, { "bggy" } }, { Airfield, { "ltnk" } }, } } AttackPaths = { { waypoint0.Location, waypoint1.Location, waypoint2.Location, waypoint3.Location }, { waypoint4.Location, waypoint9.Location, waypoint7.Location, waypoint8.Location }, } Build = function(factory, units, action) if factory.IsDead or factory.Owner ~= nod then return end if not factory.Build(units, action) then Trigger.AfterDelay(DateTime.Seconds(5), function() Build(factory, units, action) end) end end Attack = function() local types = Utils.Random(AttackUnitTypes[Map.Difficulty]) local path = Utils.Random(AttackPaths) Build(types[1], types[2], function(units) Utils.Do(units, function(unit) if unit.Owner ~= nod then return end unit.Patrol(path, false) Trigger.OnIdle(unit, unit.Hunt) end) end) Trigger.AfterDelay(Utils.RandomInteger(AttackDelayMin[Map.Difficulty], AttackDelayMax[Map.Difficulty]), Attack) end Grd1Action = function() Build(Airfield, Grd1UnitTypes, function(units) Utils.Do(units, function(unit) if unit.Owner ~= nod then return end Trigger.OnKilled(unit, function() Trigger.AfterDelay(Grd1Delay[Map.Difficulty], Grd1Action) end) unit.Patrol(Grd1Path, true, DateTime.Seconds(7)) end) end) end Grd2Action = function() Build(Airfield, Grd2UnitTypes, function(units) Utils.Do(units, function(unit) if unit.Owner ~= nod then return end unit.Patrol(Grd2Path, true, DateTime.Seconds(5)) end) end) end Grd3Action = function() local unit for i, u in ipairs(Grd3Units) do if not u.IsDead then unit = u break end end if unit ~= nil then Trigger.OnKilled(unit, function() Grd3Action() end) unit.Patrol(Grd3Path, true, DateTime.Seconds(11)) end end DiscoverGdiBase = function(actor, discoverer) if baseDiscovered or not discoverer == gdi then return end Utils.Do(GdiBase, function(actor) actor.Owner = gdi end) GdiHarv.FindResources() baseDiscovered = true gdiObjective3 = gdi.AddPrimaryObjective("Eliminate all Nod forces in the area") gdi.MarkCompletedObjective(gdiObjective1) Attack() end SetupWorld = function() Utils.Do(ActorRemovals[Map.Difficulty], function(unit) unit.Destroy() end) Reinforcements.Reinforce(gdi, GdiTanks, { GdiTankEntry.Location, GdiTankRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end) Reinforcements.Reinforce(gdi, GdiApc, { GdiApcEntry.Location, GdiApcRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end) Reinforcements.Reinforce(gdi, GdiInfantry, { GdiInfantryEntry.Location, GdiInfantryRallyPoint.Location }, 15, function(actor) actor.Stance = "Defend" end) Trigger.OnPlayerDiscovered(gdiBase, DiscoverGdiBase) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == nod and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == nod and building.Health < RepairThreshold[Map.Difficulty] * building.MaxHealth then building.StartBuildingRepairs() end end) end end) Trigger.OnAllKilled(NodSams, function() gdi.MarkCompletedObjective(gdiObjective2) Actor.Create("airstrike.proxy", true, { Owner = gdi }) end) GdiHarv.Stop() NodHarv.FindResources() if Map.Difficulty ~= "Easy" then Trigger.OnDamaged(NodHarv, function() Utils.Do(nod.GetGroundAttackers(), function(unit) unit.AttackMove(NodHarv.Location) if Map.Difficulty == "Hard" then unit.Hunt() end end) end) end Trigger.AfterDelay(DateTime.Seconds(45), Grd1Action) Trigger.AfterDelay(DateTime.Minutes(3), Grd2Action) Grd3Action() end WorldLoaded = function() gdiBase = Player.GetPlayer("AbandonedBase") gdi = Player.GetPlayer("GDI") nod = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(gdi, function() Media.PlaySpeechNotification(player, "Lose") end) Trigger.OnPlayerWon(gdi, function() Media.PlaySpeechNotification(player, "Win") end) nodObjective = nod.AddPrimaryObjective("Destroy all GDI troops") gdiObjective1 = gdi.AddPrimaryObjective("Find the GDI base") gdiObjective2 = gdi.AddSecondaryObjective("Destroy all SAM sites to receive air support") SetupWorld() Camera.Position = GdiTankRallyPoint.CenterPosition Media.PlayMusic() end Tick = function() if gdi.HasNoRequiredUnits() then if DateTime.GameTime > 2 then nod.MarkCompletedObjective(nodObjective) end end if baseDiscovered and nod.HasNoRequiredUnits() then gdi.MarkCompletedObjective(gdiObjective3) end end
gpl-3.0
wagonrepairer/Zero-K
LuaUI/Widgets/chili_new/controls/multiprogressbar.lua
7
4265
--//============================================================================= --- Multiprogressbar module --- Multiprogressbar fields. -- Inherits from Control. -- @see control.Control -- @table Multiprogressbar -- @bool[opt=false] drawBorder should the border be drawn? -- @tparam {r,g,b,a} borderColor specifies the border color (default: {1,0,0,1}) -- @string[opt="horizontal"] orientation orientation of the progress bar -- @bool[opt=false] reverse reverse drawing orientation -- @tparam fnc scaleFunction scaling function that takes 0-1 and must return 0-1 Multiprogressbar = Control:Inherit{ classname = "multiprogressbar", defaultWidth = 90, defaultHeight = 20, padding = {0,0,0,0}, fillPadding = {0, 0, 0, 0}, drawBorder = false, borderColor = {1,0,0,1}, orientation = "horizontal", reverse = false, -- draw in reversed orientation scaleFunction = nil, --- function that can be used to rescale graph - takes 0-1 and must return 0-1 -- list of bar components to display bars = { { color1 = {1,0,1,1}, color2 = {0.7,0,0.7,1}, percent = 0.2, texture = nil, -- texture file name s = 1, -- tex coords t = 1, tileSize = nil, -- if set then main axis texture coord = width / tileSize }, } } local this = Multiprogressbar local inherited = this.inherited --//============================================================================= local glVertex = gl.Vertex local glColor = gl.Color local glBeginEnd = gl.BeginEnd local function drawBox(x,y,w,h) glVertex(x,y) glVertex(x+w,y) glVertex(x+w,y+h) glVertex(x,y+h) end local function drawBarH(x,y,w,h,color1, color2) glColor(color1) glVertex(x,y) glVertex(x+w,y) glColor(color2) glVertex(x+w,y+h) glVertex(x,y+h) end local function drawBarV(x,y,w,h,color1, color2) glColor(color1) glVertex(x,y) glVertex(x,y+h) glColor(color2) glVertex(x+w,y+h) glVertex(x+w,y) end function Multiprogressbar:DrawControl() local percentDone = 0 local efp local fillPadding = self.fillPadding local x,y,w,h = fillPadding[1], fillPadding[2] self.width - fillPadding[1] - fillPadding[3], self.height - fillPadding[2] - fillPadding[4] if (self.scaleFunction ~= nil) then -- if using non linear scale fix the bar local totalPercent = 0 for _,b in ipairs(self.bars) do totalPercent = totalPercent + (b.percent or 0) end local resize = self.scaleFunction(totalPercent) / totalPercent for _,b in ipairs(self.bars) do b._drawPercent = b.percent * resize end else for _,b in ipairs(self.bars) do b._drawPercent = b.percent end end if (self.orientation=="horizontal") then for _,b in ipairs(self.bars) do if b._drawPercent > 0 then if (self.reverse) then efp = 1 - percentDone - b._drawPercent else efp = percentDone end if (b.color1 ~= nil) then glBeginEnd(GL.QUADS, drawBarH, x + efp * w, y, w * b._drawPercent, h, b.color1, b.color2) end percentDone = percentDone + b._drawPercent if b.texture then TextureHandler.LoadTexture(b.texture,self) glColor(1,1,1,1) local bs = b.s if (b.tileSize) then bs = w * b._drawPercent / b.tileSize end gl.TexRect(x + efp * w, y, (efp + b._drawPercent) * w, h, 0,0,bs,b.t) gl.Texture(false) end end end else for _,b in ipairs(self.bars) do if b._drawPercent > 0 then if (self.reverse) then efp = 1 - percentDone - b._drawPercent else efp = percentDone end if (b.color1 ~= nil) then glBeginEnd(GL.QUADS, drawBarV, x, y + efp * h, w, h * b._drawPercent, b.color1, b.color2) end percentDone = percentDone + b._drawPercent if b.texture then TextureHandler.LoadTexture(b.texture,self) glColor(1,1,1,1) local bt = b.t if (b.tileSize) then bt = h * b._drawPercent / b.tileSize end gl.TexRect(x, y + efp * h, w, (efp + b._drawPercent) * h, 0,0,b.s,bt) gl.Texture(false) end end end end if self.drawBorder then glColor(self.borderColor) glBeginEnd(GL.LINE_LOOP, drawBox, x, y, w, h) end end --//============================================================================= function Multiprogressbar:HitTest() return self end --//=============================================================================
gpl-2.0
wagonrepairer/Zero-K
scripts/dynsupport.lua
3
16082
include "constants.lua" dyncomm = include('dynamicCommander.lua') local spSetUnitShieldState = Spring.SetUnitShieldState -- pieces local base = piece 'base' local pelvis = piece 'pelvis' local turret = piece 'turret' local torso = piece 'torso' local head = piece 'head' local armhold = piece 'armhold' local ruparm = piece 'ruparm' local rarm = piece 'rarm' local rloarm = piece 'rloarm' local luparm = piece 'luparm' local larm = piece 'larm' local lloarm = piece 'lloarm' local rupleg = piece 'rupleg' local lupleg = piece 'lupleg' local lloleg = piece 'lloleg' local rloleg = piece 'rloleg' local rfoot = piece 'rfoot' local lfoot = piece 'lfoot' local gun = piece 'gun' local flare = piece 'flare' local rhand = piece 'rhand' local lhand = piece 'lhand' local gunpod = piece 'gunpod' local ac1 = piece 'ac1' local ac2 = piece 'ac2' local nanospray = piece 'nanospray' local smokePiece = {torso} local nanoPieces = {nanospray} -------------------------------------------------------------------------------- -- constants -------------------------------------------------------------------------------- local SIG_BUILD = 32 local SIG_RESTORE = 16 local SIG_AIM = 2 local SIG_AIM_2 = 4 local SIG_WALK = 1 --local SIG_AIM_3 = 8 --step on -------------------------------------------------------------------------------- -- vars -------------------------------------------------------------------------------- local restoreHeading, restorePitch = 0, 0 local canDgun = UnitDefs[unitDefID].canDgun local dead = false local bMoving = false local bAiming = false local armsFree = true local inBuildAnim = false local dgunning = false -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function BuildDecloakThread() Signal(SIG_BUILD) SetSignalMask(SIG_BUILD) while true do GG.PokeDecloakUnit(unitID, 50) Sleep(1000) end end local function BuildPose(heading, pitch) inBuildAnim = true Turn(luparm, x_axis, math.rad(-60), math.rad(250)) Turn(luparm, y_axis, math.rad(-15), math.rad(250)) Turn(luparm, z_axis, math.rad(-10), math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) Turn(larm, y_axis, math.rad(30), math.rad(250)) Turn(larm, z_axis, math.rad(-5), math.rad(250)) Turn(lloarm, y_axis, math.rad(-37), math.rad(250)) Turn(lloarm, z_axis, math.rad(-75), math.rad(450)) Turn(gunpod, y_axis, math.rad(90), math.rad(350)) Turn(turret, y_axis, heading, math.rad(350)) Turn(lloarm, x_axis, -pitch, math.rad(250)) end local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(6000) if not dead then if GetUnitValue(COB.INBUILDSTANCE) == 1 then BuildPose(restoreHeading, restorePitch) else Turn(turret, x_axis, 0, math.rad(150)) Turn(turret, y_axis, 0, math.rad(150)) --torso Turn(torso, x_axis, 0, math.rad(250)) Turn(torso, y_axis, 0, math.rad(250)) Turn(torso, z_axis, 0, math.rad(250)) --head Turn(head, x_axis, 0, math.rad(250)) Turn(head, y_axis, 0, math.rad(250)) Turn(head, z_axis, 0, math.rad(250)) -- at ease pose Turn(armhold, x_axis, math.rad(-45), math.rad(250)) --upspring at -45 Turn(ruparm, x_axis, 0, math.rad(250)) Turn(ruparm, y_axis, 0, math.rad(250)) Turn(ruparm, z_axis, 0, math.rad(250)) Turn(rarm, x_axis, math.rad(2), math.rad(250)) --up 2 Turn(rarm, y_axis, 0, math.rad(250)) Turn(rarm, z_axis, math.rad(12), math.rad(250)) --up -12 Turn(rloarm, x_axis, math.rad(47), math.rad(250)) --up 47 Turn(rloarm, y_axis, math.rad(76), math.rad(250)) --up 76 Turn(rloarm, z_axis, math.rad(47), math.rad(250)) --up -47 --left Turn(luparm, x_axis, math.rad(12), math.rad(250)) --up -9 Turn(luparm, y_axis, 0, math.rad(250)) Turn(luparm, z_axis, 0, math.rad(250)) Turn(larm, x_axis, math.rad(-35), math.rad(250)) --up 5 Turn(larm, y_axis, math.rad(-3), math.rad(250)) --up -3 Turn(larm, z_axis, math.rad(-(22)), math.rad(250)) --up 22 Turn(lloarm, x_axis, math.rad(92), math.rad(250)) -- up 82 Turn(lloarm, y_axis, 0, math.rad(250)) Turn(lloarm, z_axis, math.rad(-94), math.rad(250)) --upspring 94 Turn(gun, x_axis, 0, math.rad(250)) Turn(gun, y_axis, 0, math.rad(250)) Turn(gun, z_axis, 0, math.rad(250)) -- done at ease Sleep(100) end bAiming = false end end local function Walk() if not bAiming then Turn(torso, x_axis, math.rad(12)) --tilt forward Turn(torso, y_axis, math.rad(3.335165)) end Move(pelvis, y_axis, 0) Turn(rupleg, x_axis, math.rad(5.670330), math.rad(75)) Turn(lupleg, x_axis, math.rad(-26.467033), math.rad(75)) Turn(lloleg, x_axis, math.rad(26.967033), math.rad(75)) Turn(rloleg, x_axis, math.rad(26.967033), math.rad(75)) Turn(rfoot, x_axis, math.rad(-19.824176), math.rad(75)) Sleep(180) --had to + 20 to all sleeps in walk if not bAiming then Turn(torso, y_axis, math.rad(1.681319)) end Turn(rupleg, x_axis, math.rad(-5.269231), math.rad(75)) Turn(lupleg, x_axis, math.rad(-20.989011), math.rad(75)) Turn(lloleg, x_axis, math.rad(20.945055), math.rad(75)) Turn(rloleg, x_axis, math.rad(41.368132), math.rad(75)) Turn(rfoot, x_axis, math.rad(-15.747253)) Sleep(160) if not bAiming then Turn(torso, y_axis, 0) end Turn(rupleg, x_axis, math.rad(-9.071429), math.rad(75)) Turn(lupleg, x_axis, math.rad(-12.670330), math.rad(75)) Turn(lloleg, x_axis, math.rad(12.670330), math.rad(75)) Turn(rloleg, x_axis, math.rad(43.571429), math.rad(75)) Turn(rfoot, x_axis, math.rad(-12.016484), math.rad(75)) Sleep(140) if not bAiming then Turn(torso, y_axis, math.rad(-1.77)) end Turn(rupleg, x_axis, math.rad(-21.357143), math.rad(75)) Turn(lupleg, x_axis, math.rad(2.824176), math.rad(75)) Turn(lloleg, x_axis, math.rad(3.560440), math.rad(75)) Turn(lfoot, x_axis, math.rad(-4.527473), math.rad(75)) Turn(rloleg, x_axis, math.rad(52.505495), math.rad(75)) Turn(rfoot, x_axis, 0) Sleep(140) if not bAiming then Turn(torso, y_axis, math.rad(3.15)) end Turn(rupleg, x_axis, math.rad(-35.923077), math.rad(75)) Turn(lupleg, x_axis, math.rad(7.780220), math.rad(75)) Turn(lloleg, x_axis, math.rad(8.203297), math.rad(75)) Turn(lfoot, x_axis, math.rad(-12.571429), math.rad(75)) Turn(rloleg, x_axis, math.rad(54.390110), math.rad(75)) Sleep(140) if not bAiming then Turn(torso, y_axis, math.rad(-4.21)) end Turn(rupleg, x_axis, math.rad(-37.780220), math.rad(75)) Turn(lupleg, x_axis, math.rad(10.137363), math.rad(75)) Turn(lloleg, x_axis, math.rad(13.302198), math.rad(75)) Turn(lfoot, x_axis, math.rad(-16.714286), math.rad(75)) Turn(rloleg, x_axis, math.rad(32.582418), math.rad(75)) Sleep(140) if not bAiming then Turn(torso, y_axis, math.rad(-3.15)) end Turn(rupleg, x_axis, math.rad(-28.758242), math.rad(75)) Turn(lupleg, x_axis, math.rad(12.247253), math.rad(75)) Turn(lloleg, x_axis, math.rad(19.659341), math.rad(75)) Turn(lfoot, x_axis, math.rad(-19.659341), math.rad(75)) Turn(rloleg, x_axis, math.rad(28.758242), math.rad(75)) Sleep(160) if not bAiming then Turn(torso, y_axis, math.rad(-1.88)) end Turn(rupleg, x_axis, math.rad(-22.824176), math.rad(75)) Turn(lupleg, x_axis, math.rad(2.824176), math.rad(75)) Turn(lloleg, x_axis, math.rad(34.060440), math.rad(75)) Turn(rfoot, x_axis, math.rad(-6.313187), math.rad(75)) Sleep(160) if not bAiming then Turn(torso, y_axis, 0) end Turn(rupleg, x_axis, math.rad(-11.604396), math.rad(75)) Turn(lupleg, x_axis, math.rad(-6.725275), math.rad(75)) Turn(lloleg, x_axis, math.rad(39.401099), math.rad(75)) Turn(lfoot, x_axis, math.rad(-13.956044), math.rad(75)) Turn(rloleg, x_axis, math.rad(19.005495), math.rad(75)) Turn(rfoot, x_axis, math.rad(-7.615385), math.rad(75)) Sleep(140) if not bAiming then Turn(torso, y_axis, math.rad(1.88)) end Turn(rupleg, x_axis, math.rad(1.857143), math.rad(75)) Turn(lupleg, x_axis, math.rad(-24.357143), math.rad(75)) Turn(lloleg, x_axis, math.rad(45.093407), math.rad(75)) Turn(lfoot, x_axis, math.rad(-7.703297), math.rad(75)) Turn(rloleg, x_axis, math.rad(3.560440), math.rad(75)) Turn(rfoot, x_axis, math.rad(-4.934066), math.rad(75)) Sleep(140) if not bAiming then Turn(torso, y_axis, math.rad(3.15)) end Turn(rupleg, x_axis, math.rad(7.148352), math.rad(75)) Turn(lupleg, x_axis, math.rad(-28.181319), math.rad(75)) Sleep(140) if not bAiming then Turn(torso, y_axis, math.rad(4.20)) end Turn(rupleg, x_axis, math.rad(8.423077), math.rad(75)) Turn(lupleg, x_axis, math.rad(-32.060440), math.rad(75)) Turn(lloleg, x_axis, math.rad(27.527473), math.rad(75)) Turn(lfoot, x_axis, math.rad(-2.857143), math.rad(75)) Turn(rloleg, x_axis, math.rad(24.670330), math.rad(75)) Turn(rfoot, x_axis, math.rad(-33.313187), math.rad(75)) Sleep(160) end local function MotionControl(moving, aiming, justmoved) justmoved = true while true do moving = bMoving aiming = bAiming if moving then if aiming then armsFree = true else armsFree = false end Walk() justmoved = true else armsFree = true if justmoved then Turn(rupleg, x_axis, 0, math.rad(200.071429)) Turn(rloleg, x_axis, 0, math.rad(200.071429)) Turn(rfoot, x_axis, 0, math.rad(200.071429)) Turn(lupleg, x_axis, 0, math.rad(200.071429)) Turn(lloleg, x_axis, 0, math.rad(200.071429)) Turn(lfoot, x_axis, 0, math.rad(200.071429)) if not (aiming or inBuildAnim) then Turn(torso, x_axis, 0) --untilt forward Turn(torso, y_axis, 0, math.rad(90.027473)) Turn(ruparm, x_axis, 0, math.rad(200.071429)) -- Turn(luparm, x_axis, 0, math.rad(200.071429)) end justmoved = false end Sleep(100) end end end function script.Create() dyncomm.Create() --alert to dirt Turn(armhold, x_axis, math.rad(-45), math.rad(250)) --upspring Turn(ruparm, x_axis, 0, math.rad(250)) Turn(ruparm, y_axis, 0, math.rad(250)) Turn(ruparm, z_axis, 0, math.rad(250)) Turn(rarm, x_axis, math.rad(2), math.rad(250)) -- Turn(rarm, y_axis, 0, math.rad(250)) Turn(rarm, z_axis, math.rad(-(-12)), math.rad(250)) --up Turn(rloarm, x_axis, math.rad(47), math.rad(250)) --up Turn(rloarm, y_axis, math.rad(76), math.rad(250)) --up Turn(rloarm, z_axis, math.rad(-(-47)), math.rad(250)) --up Turn(luparm, x_axis, math.rad(12), math.rad(250)) --up Turn(luparm, y_axis, 0, math.rad(250)) Turn(luparm, z_axis, 0, math.rad(250)) Turn(larm, x_axis, math.rad(-35), math.rad(250)) --up Turn(larm, y_axis, math.rad(-3), math.rad(250)) --up Turn(larm, z_axis, math.rad(-(22)), math.rad(250)) --up Turn(lloarm, x_axis, math.rad(92), math.rad(250)) -- up Turn(lloarm, y_axis, 0, math.rad(250)) Turn(lloarm, z_axis, math.rad(-(94)), math.rad(250)) --upspring Hide(flare) Hide(ac1) Hide(ac2) StartThread(MotionControl) StartThread(RestoreAfterDelay) StartThread(SmokeUnit, smokePiece) Spring.SetUnitNanoPieces(unitID, nanoPieces) end function script.StartMoving() bMoving = true end function script.StopMoving() --Signal(SIG_WALK) bMoving = false end function script.AimFromWeapon(num) return head end function script.QueryWeapon(num) if dyncomm.GetWeapon(num) == 1 or dyncomm.GetWeapon(num) == 2 then return flare end return pelvis end local function AimRifle(heading, pitch, isDgun) if isDgun then dgunning = true end --[[ if dgunning and not isDgun then return false end ]]-- --torso Turn(torso, x_axis, math.rad(5), math.rad(250)) Turn(torso, y_axis, 0, math.rad(250)) Turn(torso, z_axis, 0, math.rad(250)) --head Turn(head, x_axis, 0, math.rad(250)) Turn(head, y_axis, 0, math.rad(250)) Turn(head, z_axis, 0, math.rad(250)) --rarm Turn(ruparm, x_axis, math.rad(-55), math.rad(250)) Turn(ruparm, y_axis, 0, math.rad(250)) Turn(ruparm, z_axis, 0, math.rad(250)) Turn(rarm, x_axis, math.rad(13), math.rad(250)) Turn(rarm, y_axis, math.rad(46), math.rad(250)) Turn(rarm, z_axis, math.rad(9), math.rad(250)) Turn(rloarm, x_axis, math.rad(16), math.rad(250)) Turn(rloarm, y_axis, math.rad(-23), math.rad(250)) Turn(rloarm, z_axis, math.rad(11), math.rad(250)) Turn(gun, x_axis, math.rad(17.0), math.rad(250)) Turn(gun, y_axis, math.rad(-19.8), math.rad(250)) ---20 is dead straight Turn(gun, z_axis, math.rad(2.0), math.rad(250)) --larm Turn(luparm, x_axis, math.rad(-70), math.rad(250)) Turn(luparm, y_axis, math.rad(-20), math.rad(250)) Turn(luparm, z_axis, math.rad(-10), math.rad(250)) Turn(larm, x_axis, math.rad(-13), math.rad(250)) Turn(larm, y_axis, math.rad(-60), math.rad(250)) Turn(larm, z_axis, math.rad(9), math.rad(250)) Turn(lloarm, x_axis, math.rad(73), math.rad(250)) Turn(lloarm, y_axis, math.rad(19), math.rad(250)) Turn(lloarm, z_axis, math.rad(58), math.rad(250)) --aim Turn(turret, y_axis, heading, math.rad(350)) Turn(armhold, x_axis, -pitch, math.rad(250)) WaitForTurn(turret, y_axis) WaitForTurn(armhold, x_axis) --need to make sure not WaitForTurn(lloarm, x_axis) --stil setting up StartThread(RestoreAfterDelay) if isDgun then dgunning = false end return true end function script.AimWeapon(num, heading, pitch) local weaponNum = dyncomm.GetWeapon(num) inBuildAnim = false if weaponNum == 1 then Signal(SIG_AIM) SetSignalMask(SIG_AIM) bAiming = true return AimRifle(heading, pitch) elseif weaponNum == 2 then Signal(SIG_AIM) Signal(SIG_AIM_2) SetSignalMask(SIG_AIM_2) bAiming = true return AimRifle(heading, pitch, canDgun) elseif weaponNum == 3 then return true end return false end function script.Activate() --spSetUnitShieldState(unitID, true) end function script.Deactivate() --spSetUnitShieldState(unitID, false) end function script.FireWeapon(num) dyncomm.EmitWeaponFireSfx(flare, num) end function script.Shot(num) dyncomm.EmitWeaponShotSfx(flare, num) end function script.QueryNanoPiece() GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),nanospray) return nanospray end function script.StopBuilding() Signal(SIG_BUILD) inBuildAnim = false SetUnitValue(COB.INBUILDSTANCE, 0) if not bAiming then StartThread(RestoreAfterDelay) end end function script.StartBuilding(heading, pitch) StartThread(BuildDecloakThread) restoreHeading, restorePitch = heading, pitch BuildPose(heading, pitch) SetUnitValue(COB.INBUILDSTANCE, 1) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth dead = 1 --Turn(turret, y_axis, 0, math.rad(500)) if severity <= 0.5 then dyncomm.SpawnModuleWrecks(1) Turn(base, x_axis, math.rad(79), math.rad(80)) Turn(rloleg, x_axis, math.rad(25), math.rad(250)) Turn(lupleg, x_axis, math.rad(7), math.rad(250)) Turn(lupleg, y_axis, math.rad(34), math.rad(250)) Turn(lupleg, z_axis, math.rad(-(-9)), math.rad(250)) InitializeDeathAnimation() Sleep(200) --give time to fall Turn(luparm, y_axis, math.rad(18), math.rad(350)) Turn(luparm, z_axis, math.rad(-(-45)), math.rad(350)) Sleep(650) --EmitSfx(turret, 1026) --impact Sleep(100) --[[ Explode(gun) Explode(head) Explode(pelvis) Explode(lloarm) Explode(luparm) Explode(lloleg) Explode(lupleg) Explode(rloarm) Explode(rloleg) Explode(ruparm) Explode(rupleg) Explode(torso) ]]-- dyncomm.SpawnWreck(1) else Explode(gun, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(head, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(pelvis, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(lloarm, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(luparm, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(lloleg, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(lupleg, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(rloarm, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(rloleg, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(ruparm, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(rupleg, sfxFall + sfxFire + sfxSmoke + sfxExplode) Explode(torso, sfxShatter + sfxExplode) dyncomm.SpawnModuleWrecks(2) dyncomm.SpawnWreck(2) end end
gpl-2.0
shingenko/darkstar
scripts/globals/mobskills/Cyclone_Wing.lua
18
1140
--------------------------------------------- -- Tebbad Wing -- -- Description: Deals darkness damage to enemies within a very wide area of effect. Additional effect: Sleep -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Vrtra and Azdaja --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:AnimationSub() == 1) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_SLEEP_I; MobStatusEffectMove(mob, target, typeEffect, 1, 0, 60); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_DARK,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
Illarion-eV/Illarion-Content
quest/gorgophone_520_wilderness.lua
1
35759
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (520, 'quest.gorgophone_520_wilderness'); local common = require("base.common") local monsterQuests = require("monster.base.quests") local M = {} local GERMAN = Player.german local ENGLISH = Player.english -- Insert the quest title here, in both languages local Title = {} Title[GERMAN] = "Das Nest der Gorgophone" Title[ENGLISH] = "Gorgophone's Nest" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do local Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 25 erledigen." Description[ENGLISH][1] = "Kill small spiders for Gorgophone. You still need 25." Description[GERMAN][2] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 24 erledigen." Description[ENGLISH][2] = "Kill small spiders for Gorgophone. You still need 24." Description[GERMAN][3] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 23 erledigen." Description[ENGLISH][3] = "Kill small spiders for Gorgophone. You still need 23." Description[GERMAN][4] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 22 erledigen." Description[ENGLISH][4] = "Kill small spiders for Gorgophone. You still need 22." Description[GERMAN][5] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 21 erledigen." Description[ENGLISH][5] = "Kill small spiders for Gorgophone. You still need 21." Description[GERMAN][6] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 20 erledigen." Description[ENGLISH][6] = "Kill small spiders for Gorgophone. You still need 20." Description[GERMAN][7] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 19 erledigen." Description[ENGLISH][7] = "Kill small spiders for Gorgophone. You still need 19." Description[GERMAN][8] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 18 erledigen." Description[ENGLISH][8] = "Kill small spiders for Gorgophone. You still need 18." Description[GERMAN][9] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 17 erledigen." Description[ENGLISH][9] = "Kill small spiders for Gorgophone. You still need 17." Description[GERMAN][10] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 16 erledigen." Description[ENGLISH][10] = "Kill small spiders for Gorgophone. You still need 16." Description[GERMAN][11] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 15 erledigen." Description[ENGLISH][11] = "Kill small spiders for Gorgophone. You still need 15." Description[GERMAN][12] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 14 erledigen." Description[ENGLISH][12] = "Kill small spiders for Gorgophone. You still need 14." Description[GERMAN][13] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 13 erledigen." Description[ENGLISH][13] = "Kill small spiders for Gorgophone. You still need 13." Description[GERMAN][14] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 12 erledigen." Description[ENGLISH][14] = "Kill small spiders for Gorgophone. You still need 12." Description[GERMAN][15] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 11 erledigen." Description[ENGLISH][15] = "Kill small spiders for Gorgophone. You still need 11." Description[GERMAN][16] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 10 erledigen." Description[ENGLISH][16] = "Kill small spiders for Gorgophone. You still need 10." Description[GERMAN][17] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 9 erledigen." Description[ENGLISH][17] = "Kill small spiders for Gorgophone. You still need 9." Description[GERMAN][18] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 8 erledigen." Description[ENGLISH][18] = "Kill small spiders for Gorgophone. You still need 8." Description[GERMAN][19] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 7 erledigen." Description[ENGLISH][19] = "Kill small spiders for Gorgophone. You still need 7." Description[GERMAN][20] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 6 erledigen." Description[ENGLISH][20] = "Kill small spiders for Gorgophone. You still need 6." Description[GERMAN][21] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 5 erledigen." Description[ENGLISH][21] = "Kill small spiders for Gorgophone. You still need 5." Description[GERMAN][22] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 4 erledigen." Description[ENGLISH][22] = "Kill small spiders for Gorgophone. You still need 4." Description[GERMAN][23] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 3 erledigen." Description[ENGLISH][23] = "Kill small spiders for Gorgophone. You still need 3." Description[GERMAN][24] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 2 erledigen." Description[ENGLISH][24] = "Kill small spiders for Gorgophone. You still need 2." Description[GERMAN][25] = "Töte Kleine Spinnen für Gorgophone. Du musst noch 1 erledigen." Description[ENGLISH][25] = "Kill small spiders for Gorgophone. You still need 1." Description[GERMAN][26] = "Kehre zu Gorgophone zurück, du hast ihre Aufgabe erledigt." Description[ENGLISH][26] = "Return to Gorgophone, you have finished her task." Description[GERMAN][27] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][27] = "Check with Gorgophone, she may have another task for you." Description[GERMAN][28] = "Bring 5 Wasserflaschen zu Gorgophone." Description[ENGLISH][28] = "Collect five bottles of water for Gorgophone." Description[GERMAN][29] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][29] = "Check with Gorgophone, she may have another task for you." Description[GERMAN][30] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 20 erledigen." Description[ENGLISH][30] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 20." Description[GERMAN][31] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 19 erledigen." Description[ENGLISH][31] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 19." Description[GERMAN][32] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 18 erledigen." Description[ENGLISH][32] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 18." Description[GERMAN][33] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 17 erledigen." Description[ENGLISH][33] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 17." Description[GERMAN][34] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 16 erledigen." Description[ENGLISH][34] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 16." Description[GERMAN][35] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 15 erledigen." Description[ENGLISH][35] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 15." Description[GERMAN][36] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 14 erledigen." Description[ENGLISH][36] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 14." Description[GERMAN][37] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 13 erledigen." Description[ENGLISH][37] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 13." Description[GERMAN][38] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 12 erledigen." Description[ENGLISH][38] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 12." Description[GERMAN][39] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 11 erledigen." Description[ENGLISH][39] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 11." Description[GERMAN][40] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 10 erledigen." Description[ENGLISH][40] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 10." Description[GERMAN][41] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 9 erledigen." Description[ENGLISH][41] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 9." Description[GERMAN][42] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 8 erledigen." Description[ENGLISH][42] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 8." Description[GERMAN][43] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 7 erledigen." Description[ENGLISH][43] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 7." Description[GERMAN][44] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 6 erledigen." Description[ENGLISH][44] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 6." Description[GERMAN][45] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 5 erledigen." Description[ENGLISH][45] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 5." Description[GERMAN][46] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 4 erledigen." Description[ENGLISH][46] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 4." Description[GERMAN][47] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 3 erledigen." Description[ENGLISH][47] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 3." Description[GERMAN][48] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 2 erledigen." Description[ENGLISH][48] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 2." Description[GERMAN][49] = "Töte Schreckensspinne, Grubendiener, oder Feuerspinne Spinnen für Gorgophone. Du musst noch 1 erledigen." Description[ENGLISH][49] = "Kill Dread Spider, Pit Servants, or Fire Spiders spiders for Gorgophone. You still need 1." Description[GERMAN][50] = "Kehre zu Gorgophone zurück, du hast ihre Aufgabe erledigt." Description[ENGLISH][50] = "Return to Gorgophone, you have finished her task." Description[GERMAN][51] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][51] = "Check with Gorgophone, she may have another task for you." Description[GERMAN][52] = "Töte Taranteln für Gorgophone. Du musst noch 15 erledigen." Description[ENGLISH][52] = "Kill tarantulas for Gorgophone. You still need 15." Description[GERMAN][53] = "Töte Taranteln für Gorgophone. Du musst noch 14 erledigen." Description[ENGLISH][53] = "Kill tarantulas for Gorgophone. You still need 14." Description[GERMAN][54] = "Töte Taranteln für Gorgophone. Du musst noch 13 erledigen." Description[ENGLISH][54] = "Kill tarantulas for Gorgophone. You still need 13." Description[GERMAN][55] = "Töte Taranteln für Gorgophone. Du musst noch 12 erledigen." Description[ENGLISH][55] = "Kill tarantulas for Gorgophone. You still need 12." Description[GERMAN][56] = "Töte Taranteln für Gorgophone. Du musst noch 11 erledigen." Description[ENGLISH][56] = "Kill tarantulas for Gorgophone. You still need 11." Description[GERMAN][57] = "Töte Taranteln für Gorgophone. Du musst noch 10 erledigen." Description[ENGLISH][57] = "Kill tarantulas for Gorgophone. You still need 10." Description[GERMAN][58] = "Töte Taranteln für Gorgophone. Du musst noch 9 erledigen." Description[ENGLISH][58] = "Kill tarantulas for Gorgophone. You still need 9." Description[GERMAN][59] = "Töte Taranteln für Gorgophone. Du musst noch 8 erledigen." Description[ENGLISH][59] = "Kill tarantulas for Gorgophone. You still need 8." Description[GERMAN][60] = "Töte Taranteln für Gorgophone. Du musst noch 7 erledigen." Description[ENGLISH][60] = "Kill tarantulas for Gorgophone. You still need 7." Description[GERMAN][61] = "Töte Taranteln für Gorgophone. Du musst noch 6 erledigen." Description[ENGLISH][61] = "Kill tarantulas for Gorgophone. You still need 6." Description[GERMAN][62] = "Töte Taranteln für Gorgophone. Du musst noch 5 erledigen." Description[ENGLISH][62] = "Kill tarantulas for Gorgophone. You still need 5." Description[GERMAN][63] = "Töte Taranteln für Gorgophone. Du musst noch 4 erledigen." Description[ENGLISH][63] = "Kill tarantulas for Gorgophone. You still need 4." Description[GERMAN][64] = "Töte Taranteln für Gorgophone. Du musst noch 3 erledigen." Description[ENGLISH][64] = "Kill tarantulas for Gorgophone. You still need 3." Description[GERMAN][65] = "Töte Taranteln für Gorgophone. Du musst noch 2 erledigen." Description[ENGLISH][65] = "Kill tarantulas for Gorgophone. You still need 2." Description[GERMAN][66] = "Töte Taranteln für Gorgophone. Du musst noch 1 erledigen." Description[ENGLISH][66] = "Kill tarantulas for Gorgophone. You still need 1." Description[GERMAN][67] = "Kehre zu Gorgophone zurück, du hast ihre Aufgabe erledigt." Description[ENGLISH][67] = "Return to Gorgophone, you have finished her task." Description[GERMAN][68] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][68] = "Check with Gorgophone, she may have another task for you." Description[GERMAN][69] = "Bringe 60 Getreidebündel zu Gorgophone." Description[ENGLISH][69] = "Collect sixty grain bundles for Gorgophone." Description[GERMAN][70] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][70] = "Check with Gorgophone she may have another task for you." Description[GERMAN][71] = "Gorgophone braucht 75 Spindeln Garn von dir." Description[ENGLISH][71] = "Collect 75 spools of thread for Gorgophone." Description[GERMAN][72] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][72] = "Check with Gorgophone she may have another task for you." Description[GERMAN][73] = "Besorge eine mindestens sehr gute heilige Voulge und bring diese zu Gorgophone." Description[ENGLISH][73] = "Collect a divine voulge spear, of very good quality or better, for Gorgophone." Description[GERMAN][74] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][74] = "Check with Gorgophone she may have another task for you." Description[GERMAN][75] = "Töte Spinnenköniginnen für Gorgophone. Du musst noch 5 erledigen." Description[ENGLISH][75] = "Kill spider queens for Gorgophone. You still need 5." Description[GERMAN][76] = "Töte Spinnenköniginnen für Gorgophone. Du musst noch 4 erledigen." Description[ENGLISH][76] = "Kill spider queens for Gorgophone. You still need 4." Description[GERMAN][77] = "Töte Spinnenköniginnen für Gorgophone. Du musst noch 3 erledigen." Description[ENGLISH][77] = "Kill spider queens for Gorgophone. You still need 3." Description[GERMAN][78] = "Töte Spinnenköniginnen für Gorgophone. Du musst noch 2 erledigen." Description[ENGLISH][78] = "Kill spider queens for Gorgophone. You still need 2." Description[GERMAN][79] = "Töte Spinnenköniginnen für Gorgophone. Du musst noch 1 erledigen." Description[ENGLISH][79] = "Kill spider queens for Gorgophone. You still need 1." Description[GERMAN][80] = "Kehre zu Gorgophone zurück, du hast ihre Aufgabe erledigt." Description[ENGLISH][80] = "Return to Gorgophone, you have finished her task." Description[GERMAN][81] = "Rede mit Gorgophone, sie hat villeicht eine weitere Aufgabe für dich." Description[ENGLISH][81] = "Check with Gorgophone, she may have another task for you." Description[GERMAN][82] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 50 erledigen." Description[ENGLISH][82] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 50." Description[GERMAN][83] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 49 erledigen." Description[ENGLISH][83] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 49." Description[GERMAN][84] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 48 erledigen." Description[ENGLISH][84] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 48." Description[GERMAN][85] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 47 erledigen." Description[ENGLISH][85] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 47." Description[GERMAN][86] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 46 erledigen." Description[ENGLISH][86] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 46." Description[GERMAN][87] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 45 erledigen." Description[ENGLISH][87] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 45." Description[GERMAN][88] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 44 erledigen." Description[ENGLISH][88] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 44." Description[GERMAN][89] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 43 erledigen." Description[ENGLISH][89] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 43." Description[GERMAN][90] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 42 erledigen." Description[ENGLISH][90] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 42." Description[GERMAN][91] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 41 erledigen." Description[ENGLISH][91] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 41." Description[GERMAN][92] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 40 erledigen." Description[ENGLISH][92] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 40." Description[GERMAN][93] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 39 erledigen." Description[ENGLISH][93] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 39." Description[GERMAN][94] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 38 erledigen." Description[ENGLISH][94] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 38." Description[GERMAN][95] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 37 erledigen." Description[ENGLISH][95] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 37." Description[GERMAN][96] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 36 erledigen." Description[ENGLISH][96] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 36." Description[GERMAN][97] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 35 erledigen." Description[ENGLISH][97] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 35." Description[GERMAN][98] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 34 erledigen." Description[ENGLISH][98] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 34." Description[GERMAN][99] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 33 erledigen." Description[ENGLISH][99] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 33." Description[GERMAN][100] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 32 erledigen." Description[ENGLISH][100] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 32." Description[GERMAN][101] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 31 erledigen." Description[ENGLISH][101] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 31." Description[GERMAN][102] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 30 erledigen." Description[ENGLISH][102] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 30." Description[GERMAN][103] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 29 erledigen." Description[ENGLISH][103] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 29." Description[GERMAN][104] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 28 erledigen." Description[ENGLISH][104] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 28." Description[GERMAN][105] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 27 erledigen." Description[ENGLISH][105] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 27." Description[GERMAN][106] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 26 erledigen." Description[ENGLISH][106] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 26." Description[GERMAN][107] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 25 erledigen." Description[ENGLISH][107] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 25." Description[GERMAN][108] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 24 erledigen." Description[ENGLISH][108] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 24." Description[GERMAN][109] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 23 erledigen." Description[ENGLISH][109] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 23." Description[GERMAN][110] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 22 erledigen." Description[ENGLISH][110] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 22." Description[GERMAN][111] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 21 erledigen." Description[ENGLISH][111] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 21." Description[GERMAN][112] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 20 erledigen." Description[ENGLISH][112] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 20." Description[GERMAN][113] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 19 erledigen." Description[ENGLISH][113] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 19." Description[GERMAN][114] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 18 erledigen." Description[ENGLISH][114] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 18." Description[GERMAN][115] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 17 erledigen." Description[ENGLISH][115] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 17." Description[GERMAN][116] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 16 erledigen." Description[ENGLISH][116] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 16." Description[GERMAN][117] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 15 erledigen." Description[ENGLISH][117] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 15." Description[GERMAN][118] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 14 erledigen." Description[ENGLISH][118] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 14." Description[GERMAN][119] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 13 erledigen." Description[ENGLISH][119] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 13." Description[GERMAN][120] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 12 erledigen." Description[ENGLISH][120] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 12." Description[GERMAN][121] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 11 erledigen." Description[ENGLISH][121] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 11." Description[GERMAN][122] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 10 erledigen." Description[ENGLISH][122] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 10." Description[GERMAN][123] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 9 erledigen." Description[ENGLISH][123] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 9." Description[GERMAN][124] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 8 erledigen." Description[ENGLISH][124] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 8." Description[GERMAN][125] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 7 erledigen." Description[ENGLISH][125] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 7." Description[GERMAN][126] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 6 erledigen." Description[ENGLISH][126] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 6." Description[GERMAN][127] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 5 erledigen." Description[ENGLISH][127] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 5." Description[GERMAN][128] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 4 erledigen." Description[ENGLISH][128] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 4." Description[GERMAN][129] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 3 erledigen." Description[ENGLISH][129] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 3." Description[GERMAN][130] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 2 erledigen." Description[ENGLISH][130] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 2." Description[GERMAN][131] = "Töte Schattenmampfer, Tarantel, Spinnenkönigin, Ritterfurcht, oder Gynkesische Witwe Spinnen für Gorgophone. Du musst noch 1 erledigen." Description[ENGLISH][131] = "Kill Shadow Muncher, Tarantula, Spider Queen, Kings Fright, or Gynkese Widow for Gorgophone. You still need 1." Description[GERMAN][132] = "Kehre zu Gorgophone zurück, du hast ihre Aufgabe erledigt." Description[ENGLISH][132] = "Return to Gorgophone, you have completed her task." Description[GERMAN][133] = "Du hast alle Aufgaben der Gorgophone erledigt." Description[ENGLISH][133] = "You have completed all tasks of Gorgophone." local npcPos = position(852, 497, -6); -- Insert the position of the quest start here (probably the position of an NPC or item) local Start = npcPos; -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there local QuestTarget = {} for i = 1, 132 do QuestTarget[i] = {npcPos}; end -- Insert the quest status which is reached at the end of the quest local FINAL_QUEST_STATUS = 133 -- Register the monster kill parts of the quest. monsterQuests.addQuest{ questId = 520, location = {position = npcPos, radius = 200}, queststatus = {from = 1, to = 26}, questTitle = {german = "Das Nest der Gorgophone", english = "Gorgophone's Nest"}, monsterName = {german = "kleine Spinnen", english = "small spiders"}, npcName = "Gorgophone", monsterIds = {196} -- small spider } monsterQuests.addQuest{ questId = 520, location = {position = npcPos, radius = 200}, queststatus = {from = 30, to = 50}, questTitle = {german = "Das Nest der Gorgophone", english = "Gorgophone's Nest"}, monsterName = {german = "Schreckensspinne", english = "Dread Spider, Pit Servant and Fire Spider spiders"}, npcName = "Gorgophone", monsterIds = {191, 192, 211} -- Dread Spider, Pit Servant, Fire Spider } monsterQuests.addQuest{ questId = 520, location = {position = npcPos, radius = 200}, queststatus = {from = 52, to = 67}, questTitle = {german = "Das Nest der Gorgophone", english = "Gorgophone's Nest"}, monsterName = {german = "Taranteln", english = "tarantulas"}, npcName = "Gorgophone", monsterIds = {193} -- Tarantula } monsterQuests.addQuest{ questId = 520, location = {position = npcPos, radius = 200}, queststatus = {from = 75, to = 80}, questTitle = {german = "Das Nest der Gorgophone", english = "Gorgophone's Nest"}, monsterName = {german = "Spinnenköniginnen", english = "Spider Queens"}, npcName = "Gorgophone", monsterIds = {195} -- Spider queen } monsterQuests.addQuest{ questId = 520, location = {position = npcPos, radius = 200}, queststatus = {from = 82, to = 132}, questTitle = {german = "Das Nest der Gorgophone", english = "Gorgophone's Nest"}, monsterName = {german = "Groß Spinnen", english = "Large spiders"}, npcName = "Gorgophone", monsterIds = {193, 195, 221, 231, 232, 261} -- Tarantula, Spider Queen, Gynkese Widow, Kings Fright, Shadow Muncher,Nightmare spider } function M.QuestTitle(user) return common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function M.QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return common.GetNLS(user, german, english) end function M.QuestStart() return Start end function M.QuestTargets(user, status) return QuestTarget[status] end function M.QuestFinalStatus() return FINAL_QUEST_STATUS end function M.QuestAvailability(user, status) if status == 0 then return Player.questAvailable else return Player.questNotAvailable end end return M
agpl-3.0
shingenko/darkstar
scripts/zones/Crawlers_Nest/npcs/qm12.lua
57
2120
----------------------------------- -- Area: Crawlers' Nest -- NPC: qm12 (??? - Exoray Mold Crumbs) -- Involved in Quest: In Defiant Challenge -- @pos 99.326 -0.126 -188.869 197 ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Crawlers_Nest/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB3) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(EXORAY_MOLD_CRUMB3); player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB3); end if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1089, 1); player:messageSpecial(ITEM_OBTAINED, 1089); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089); end end if (player:hasItem(1089)) then player:delKeyItem(EXORAY_MOLD_CRUMB1); player:delKeyItem(EXORAY_MOLD_CRUMB2); player:delKeyItem(EXORAY_MOLD_CRUMB3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
shingenko/darkstar
scripts/zones/Palborough_Mines/Zone.lua
27
1673
----------------------------------- -- -- Zone: Palborough_Mines (143) -- ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Palborough_Mines/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) UpdateTreasureSpawnPoint(17363366); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(114.483,-42,-140,96); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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
obsy/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/startup.lua
74
2567
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2010-2012 Jo-Philipp Wich <jow@openwrt.org> -- Copyright 2010 Manuel Munz <freifunk at somakoma dot de> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local sys = require "luci.sys" local inits = { } for _, name in ipairs(sys.init.names()) do local index = sys.init.index(name) local enabled = sys.init.enabled(name) if index < 255 then inits["%02i.%s" % { index, name }] = { name = name, index = tostring(index), enabled = enabled } end end m = SimpleForm("initmgr", translate("Initscripts"), translate("You can enable or disable installed init scripts here. Changes will applied after a device reboot.<br /><strong>Warning: If you disable essential init scripts like \"network\", your device might become inaccessible!</strong>")) m.reset = false m.submit = false s = m:section(Table, inits) i = s:option(DummyValue, "index", translate("Start priority")) n = s:option(DummyValue, "name", translate("Initscript")) e = s:option(Button, "endisable", translate("Enable/Disable")) e.render = function(self, section, scope) if inits[section].enabled then self.title = translate("Enabled") self.inputstyle = "save" else self.title = translate("Disabled") self.inputstyle = "reset" end Button.render(self, section, scope) end e.write = function(self, section) if inits[section].enabled then inits[section].enabled = false return sys.init.disable(inits[section].name) else inits[section].enabled = true return sys.init.enable(inits[section].name) end end start = s:option(Button, "start", translate("Start")) start.inputstyle = "apply" start.write = function(self, section) sys.call("/etc/init.d/%s %s >/dev/null" %{ inits[section].name, self.option }) end restart = s:option(Button, "restart", translate("Restart")) restart.inputstyle = "reload" restart.write = start.write stop = s:option(Button, "stop", translate("Stop")) stop.inputstyle = "remove" stop.write = start.write f = SimpleForm("rc", translate("Local Startup"), translate("This is the content of /etc/rc.local. Insert your own commands here (in front of 'exit 0') to execute them at the end of the boot process.")) t = f:field(TextValue, "rcs") t.rmempty = true t.rows = 20 function t.cfgvalue() return fs.readfile("/etc/rc.local") or "" end function f.handle(self, state, data) if state == FORM_VALID then if data.rcs then fs.writefile("/etc/rc.local", data.rcs:gsub("\r\n", "\n")) end end return true end return m, f
apache-2.0
openwayne/chaos_theory
mods/animals_modpack/animal_wolf/init.lua
1
6820
------------------------------------------------------------------------------- -- Mob Framework Mod by Sapier -- -- You may copy, use, modify or do nearly anything except removing this -- copyright notice. -- And of course you are NOT allowed to pretend you have written it. -- --! @file init.lua --! @brief wolf implementation --! @copyright Sapier --! @author Sapier --! @date 2013-01-27 -- -- Contact sapier a t gmx net ------------------------------------------------------------------------------- -- Boilerplate to support localized strings if intllib mod is installed. local S if (minetest.get_modpath("intllib")) then dofile(minetest.get_modpath("intllib").."/intllib.lua") S = intllib.Getter(minetest.get_current_modname()) else S = function ( s ) return s end end minetest.log("action","MOD: mob_wolf loading ...") local version = "0.2.1" local wolf_groups = { not_in_creative_inventory=1 } local selectionbox_wolf = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5} wolf_prototype = { name="wolf", modname="animal_wolf", factions = { member = { "animals", "forrest_animals", "wolfs" } }, generic = { description= S("Wolf"), base_health=10, kill_result="animalmaterials:fur 1", armor_groups= { fleshy=90, }, groups = wolf_groups, addoncatch = "animal_wolf:tamed_wolf", envid="on_ground_2", population_density=800, }, movement = { canfly=false, guardspawnpoint = true, teleportdelay = 60, min_accel=0.5, max_accel=0.9, max_speed=1.5, follow_speedup=10, }, catching = { tool="animalmaterials:net", consumed=true, }, combat = { starts_attack=true, sun_sensitive=false, melee = { maxdamage=5, range=2, speed=1, }, distance = nil, self_destruct = nil, }, sound = { random = nil, melee = { name="animal_wolf_melee", gain = 0.8, max_hear_distance = 10 }, hit = { name="animal_wolf_hit", gain = 0.8, max_hear_distance = 5 }, start_attack = { name="animal_wolf_attack", gain = 0.8, max_hear_distance = 20 }, }, animation = { stand = { start_frame = 0, end_frame = 60, }, walk = { start_frame = 61, end_frame = 120, }, sleep = { start_frame = 121, end_frame = 180, }, }, attention = { hear_distance = 5, hear_distance_value = 20, view_angle = math.pi/2, own_view_value = 0.2, remote_view = false, remote_view_value = 0, attention_distance_value = 0.2, watch_threshold = 10, attack_threshold = 20, attention_distance = 10, attention_max = 25, }, states = { { name = "default", movgen = "follow_mov_gen", typical_state_time = 30, chance = 0, animation = "stand", graphics_3d = { visual = "mesh", mesh = "animal_wolf.b3d", textures = {"animal_wolf_mesh.png"}, collisionbox = selectionbox_wolf, visual_size= {x=1,y=1,z=1}, }, }, { name = "sleeping", --TODO replace by check for night custom_preconhandler = nil, movgen = "none", typical_state_time = 300, chance = 0.10, animation = "sleep", }, { name = "combat", typical_state_time = 9999, chance = 0.0, animation = "walk", movgen = "follow_mov_gen" }, } } tamed_wolf_prototype = { name="tamed_wolf", modname="animal_wolf", generic = { description= S("Tamed Wolf"), base_health=10, kill_result="animalmaterials:fur 1", armor_groups= { fleshy=90, }, groups = wolf_groups, envid="on_ground_2", --this needs to be done by animal as first on_activate handler is called --before placer is known to entity custom_on_place_handler = function(entity, placer, pointed_thing) if placer:is_player(placer) then if not entity:set_movement_target(placer, { max_target_distance=2, stop=true }) then print("ANIMAL tamed wolf: unable to set owner maybe wolf has been already deleted") end end end, custom_on_activate_handler = function(entity) local spawner = entity.dynamic_data.spawning.spawner if spawner ~= nil then local player = minetest.get_player_by_name(spawner) if player ~= nil then entity:set_movement_target(player, { max_target_distance=2, stop=true }) end end end, custom_on_step_handler = function(entity,now,dstep) if entity.dynamic_data.spawning.spawner == nil and now - entity.dynamic_data.spawning.original_spawntime > 30 then spawning.remove(entity) end end }, movement = { canfly=false, guardspawnpoint = false, teleportdelay = 20, min_accel=0.3, max_accel=0.9, max_speed=1.5, max_distance=2, follow_speedup=5, }, catching = { tool="animalmaterials:net", consumed=true, }, sound = { random = nil, }, animation = { stand = { start_frame = 0, end_frame = 60, }, walk = { start_frame = 61, end_frame = 120, }, }, states = { { name = "default", movgen = "follow_mov_gen", typical_state_time = 60, chance = 0, animation = "stand", graphics_3d = { visual = "mesh", mesh = "animal_wolf.b3d", textures = {"animal_wolf_tamed_mesh.png"}, collisionbox = selectionbox_wolf, visual_size= {x=1,y=1,z=1}, }, }, } } local wolf_name = wolf_prototype.modname .. ":" .. wolf_prototype.name local wolf_env = mobf_environment_by_name(wolf_prototype.generic.envid) mobf_spawner_register("wolf_spawner_1",wolf_name, { spawnee = wolf_name, spawn_interval = 300, spawn_inside = wolf_env.media, entities_around = { { type="MAX",distance=1,threshold=0 }, { type="MAX",entityname=wolf_name, distance=wolf_prototype.generic.population_density,threshold=1 }, }, nodes_around = { { type="MIN", name = { "default:leaves","default:tree"},distance=3,threshold=4} }, absolute_height = { min = -10, }, mapgen = { enabled = true, retries = 5, spawntotal = 1, }, surfaces = wolf_env.surfaces.good, collisionbox = selectionbox_wolf }) if factions~= nil and type(factions.set_base_reputation) == "function" then factions.set_base_reputation("wolfs","players",-25) end minetest.log("action","\tadding mob "..wolf_prototype.name) mobf_add_mob(wolf_prototype) minetest.log("action","\tadding mob "..tamed_wolf_prototype.name) mobf_add_mob(tamed_wolf_prototype) minetest.log("action","MOD: animal_wolf mod version " .. version .. " loaded")
lgpl-2.1
wagonrepairer/Zero-K
units/turrettorp.lua
7
5270
unitDef = { unitname = [[turrettorp]], name = [[Urchin]], description = [[Torpedo Launcher]], acceleration = 0, activateWhenBuilt = true, brakeRate = 0, buildAngle = 16384, buildCostEnergy = 120, buildCostMetal = 120, builder = false, buildPic = [[CORTL.png]], buildTime = 120, canAttack = true, canstop = [[1]], category = [[FLOAT]], collisionVolumeOffsets = [[0 -5 0]], collisionVolumeScales = [[42 50 42]], collisionVolumeTest = 1, collisionVolumeType = [[CylY]], corpse = [[DEAD]], customParams = { description_fr = [[Lance Torpille]], description_de = [[Torpedowerfer]], description_pl = [[Wyrzutnia torped]], -- commented out: mentions of exterior sonar (now torp has its own) helptext = [[This Torpedo Launcher provides defense against both surface and submerged vessels.]], -- Remember to build sonar so that the Torpedo Launcher can hit submerged targets. helptext_fr = [[Ce lance torpille permet de torpiller les unites flottantes ou immergees.]], -- Construisez un sonar afin de d?tecter le plus t?t possible les cibles potentielles du Harpoon. helptext_de = [[Dieser Torpedowerfer dient zur Verteidigung gegen Schiffe und U-Boote..]], -- Achte darauf, dass du ein Sonar baust, damit der Torpedowerfer U-Boote lokalisieren kann. helptext_pl = [[Torpedy sa w stanie trafic zarowno cele plywajace po powierzchni jak i pod woda.]], -- Pamietaj, ze do atakowania zanurzonych celow potrzebny jest sonar. aimposoffset = [[0 15 0]], midposoffset = [[0 15 0]], }, explodeAs = [[MEDIUM_BUILDINGEX]], footprintX = 3, footprintZ = 3, iconType = [[defensetorp]], idleAutoHeal = 5, idleTime = 1800, mass = 215, maxDamage = 1000, maxSlope = 18, maxVelocity = 0, minCloakDistance = 150, noAutoFire = false, noChaseCategory = [[FIXEDWING LAND SHIP SATELLITE SWIM GUNSHIP SUB HOVER]], objectName = [[torpedo launcher.s3o]], script = [[turrettorp.lua]], seismicSignature = 4, selfDestructAs = [[MEDIUM_BUILDINGEX]], side = [[CORE]], sightDistance = 660, sonarDistance = 550, turnRate = 0, waterline = 1, workerTime = 0, yardMap = [[wwwwwwwww]], weapons = { { def = [[TORPEDO]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[SWIM FIXEDWING LAND SUB SINK TURRET FLOAT SHIP GUNSHIP HOVER]], }, }, weaponDefs = { TORPEDO = { name = [[Torpedo Launcher]], areaOfEffect = 64, avoidFriendly = false, bouncerebound = 0.5, bounceslip = 0.5, burnblow = true, collideFriendly = false, craterBoost = 0, craterMult = 0, damage = { default = 190, }, explosionGenerator = [[custom:TORPEDO_HIT]], groundbounce = 1, edgeEffectiveness = 0.6, impulseBoost = 0, impulseFactor = 0.2, interceptedByShieldType = 1, model = [[wep_t_longbolt.s3o]], numbounce = 4, range = 590, reloadtime = 3.2, soundHit = [[explosion/wet/ex_underwater]], --soundStart = [[weapon/torpedo]], startVelocity = 150, tracks = true, turnRate = 22000, turret = true, waterWeapon = true, weaponAcceleration = 22, weaponTimer = 3, weaponType = [[TorpedoLauncher]], weaponVelocity = 320, }, }, featureDefs = { DEAD = { description = [[Wreckage - Urchin]], blocking = false, category = [[corpses]], damage = 1000, energy = 0, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, height = [[4]], hitdensity = [[100]], metal = 48, object = [[torpedo launcher_dead.s3o]], reclaimable = true, reclaimTime = 48, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Urchin]], blocking = false, category = [[heaps]], damage = 1000, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 3, footprintZ = 3, hitdensity = [[100]], metal = 24, object = [[debris3x3c.s3o]], reclaimable = true, reclaimTime = 24, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ turrettorp = unitDef })
gpl-2.0
wagonrepairer/Zero-K
units/striderhub.lua
3
5213
unitDef = { unitname = [[striderhub]], name = [[Strider Hub]], description = [[Constructs Striders, Builds at 10 m/s]], acceleration = 0, brakeRate = 1.5, buildCostEnergy = 600, buildCostMetal = 600, buildDistance = 300, builder = true, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 5, buildingGroundDecalSizeY = 5, buildingGroundDecalType = [[armnanotc_aoplane.dds]], buildoptions = { [[dynhub_support_base]], [[dynhub_recon_base]], [[dynhub_assault_base]], [[dynhub_strike_base]], [[armcomdgun]], [[scorpion]], [[dante]], [[armraven]], [[funnelweb]], [[armbanth]], [[armorco]], [[cornukesub]], [[reef]], [[corbats]], }, buildPic = [[striderhub.png]], buildTime = 600, canGuard = true, canMove = false, canPatrol = true, canreclamate = [[1]], canstop = [[1]], cantBeTransported = true, category = [[FLOAT UNARMED]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[70 70 70]], collisionVolumeTest = 1, collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { description_de = [[Erzeugt Strider, Baut mit 10 M/s]], description_pl = [[Buduje ciezkie roboty, moc 10 m/s]], helptext = [[The Strider Hub deploys striders, the "humongous mecha" that inspire awe and fear on the battlefield. Unlike a normal factory, the hub is only required to start a project, not to finish it.]], helptext_de = [[Das Strider Hub erzeugt Strider, welche sehr gefürchtet sind auf dem Schlachtfeld. Anders als normale Fabriken, wird dieser Hub nur benötigt, um ein Projekt zu starten, nicht, um es zu vollenden.]], helptext_pl = [[Tutaj budowane sa "wielkie roboty", ktore sieja strach i zniszczenie na polu walki. W przeciwienstwie do innych fabryk, ten budynek jest wymagany jedynie do rozpoczecia budowy ciezkiego robota; nie jest wymagany, by uczestniczyl w samej budowie.]], aimposoffset = [[0 0 0]], midposoffset = [[0 -10 0]], modelradius = [[35]], }, defaultmissiontype = [[Standby]], energyMake = 0.3, explodeAs = [[ESTOR_BUILDINGEX]], floater = true, footprintX = 4, footprintZ = 4, iconType = [[t3hub]], idleAutoHeal = 5, idleTime = 1800, levelGround = false, maneuverleashlength = [[380]], mass = 100000, maxDamage = 2000, maxSlope = 15, maxVelocity = 0, metalMake = 0.3, minCloakDistance = 150, movementClass = [[KBOT4]], noAutoFire = false, objectName = [[striderhub.s3o]], script = [[striderhub.lua]], seismicSignature = 4, selfDestructAs = [[ESTOR_BUILDINGEX]], showNanoSpray = false, side = [[ARM]], sightDistance = 380, smoothAnim = true, steeringmode = [[1]], TEDClass = [[CNSTR]], terraformSpeed = 600, turnRate = 1, upright = true, useBuildingGroundDecal = true, workerTime = 10, featureDefs = { DEAD = { description = [[Wreckage - Strider Hub]], blocking = false, category = [[heaps]], damage = 2000, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 4, footprintZ = 4, height = [[4]], hitdensity = [[100]], metal = 240, object = [[striderhub_dead.s3o]], reclaimable = true, reclaimTime = 240, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Strider Hub]], blocking = false, category = [[heaps]], damage = 2000, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 4, footprintZ = 4, height = [[4]], hitdensity = [[100]], metal = 120, object = [[debris4x4a.s3o]], reclaimable = true, reclaimTime = 120, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ striderhub = unitDef })
gpl-2.0
obsy/luci
modules/luci-base/luasrc/tools/webadmin.lua
59
2301
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.tools.webadmin", package.seeall) local util = require "luci.util" local uci = require "luci.model.uci" local ip = require "luci.ip" function byte_format(byte) local suff = {"B", "KB", "MB", "GB", "TB"} for i=1, 5 do if byte > 1024 and i < 5 then byte = byte / 1024 else return string.format("%.2f %s", byte, suff[i]) end end end function date_format(secs) local suff = {"min", "h", "d"} local mins = 0 local hour = 0 local days = 0 secs = math.floor(secs) if secs > 60 then mins = math.floor(secs / 60) secs = secs % 60 end if mins > 60 then hour = math.floor(mins / 60) mins = mins % 60 end if hour > 24 then days = math.floor(hour / 24) hour = hour % 24 end if days > 0 then return string.format("%.0fd %02.0fh %02.0fmin %02.0fs", days, hour, mins, secs) else return string.format("%02.0fh %02.0fmin %02.0fs", hour, mins, secs) end end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function cbi_add_knownips(field) local _, n for _, n in ipairs(ip.neighbors({ family = 4 })) do if n.dest then field:value(n.dest:string()) end end end function firewall_find_zone(name) local find luci.model.uci.cursor():foreach("firewall", "zone", function (section) if section.name == name then find = section[".name"] end end ) return find end function iface_get_network(iface) local link = ip.link(tostring(iface)) if link.master then iface = link.master end local cur = uci.cursor() local dump = util.ubus("network.interface", "dump", { }) if dump then local _, net for _, net in ipairs(dump.interface) do if net.l3_device == iface or net.device == iface then -- cross check with uci to filter out @name style aliases local uciname = cur:get("network", net.interface, "ifname") if not uciname or uciname:sub(1, 1) ~= "@" then return net.interface end end end end end
apache-2.0
redstormbot/zrdb
plugins/dictionary.lua
58
1663
--[[ -- Translate text using Google Translate. -- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello --]] do function translate(source_lang, target_lang, text) local path = "http://translate.google.com/translate_a/single" -- URL query parameters local params = { client = "t", ie = "UTF-8", oe = "UTF-8", hl = "en", dt = "t", tl = target_lang or "fa", sl = source_lang or "auto", text = URL.escape(text) } local query = format_http_params(params, true) local url = path..query local res, code = https.request(url) -- Return nil if error if code > 200 then return nil end local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "") return trans end function run(msg, matches) -- Third pattern if #matches == 1 then print("First") local text = matches[1] return translate(nil, nil, text) end -- Second pattern if #matches == 2 then print("Second") local target = matches[1] local text = matches[2] return translate(nil, target, text) end -- First pattern if #matches == 3 then print("Third") local source = matches[1] local target = matches[2] local text = matches[3] return translate(source, target, text) end end return { description = "Translate Text, Default Persian", usage = { "/dic (txt) : translate txt en to fa", "/dic (lang) (txt) : translate en to other", "/dic (lang1,lang2) (txt) : translate lang1 to lang2", }, patterns = { "^[!/]dic ([%w]+),([%a]+) (.+)", "^[!/]dic ([%w]+) (.+)", "^[!/]dic (.+)", }, run = run } end
gpl-2.0
cuberite/CuberitePluginChecker
Simulator.lua
2
52490
-- Simulator.lua -- Implements the Cuberite simulator --[[ Usage: local sim = require("Simulator").create() -- Possibly use sim as an upvalue in special API function implementations -- Extend the simulator's sandbox etc. sim:run(options, api) The simulator keeps a sandbox for the plugin files, lists of registered objects (hooks, command handlers, simulated players and worlds etc.) and a queue of requests to call the plugin's methods. It can also directly call any callback in the plugin. The Scenario uses this functionality to implement the various actions. Use the processCallbackRequest() function to call into the plugin. Use the queueCallbackRequest() function to add a call into the plugin into a queue. Use the processAllQueuedCallbackRequests() function to process the callback queue until it is empty. The callback request is a table containing the following members: - Function - function in the plugin to call - ParamValues - array of values that get passed as parameters. If not present, ParamTypes is used instead. - ParamTypes - array of type descriptions (tables with {Type = <>}) from which the parameters are synthesized. Only used if ParamValues not present. - Notes - string description of the callback (used for logging) - AllowsStore - optional dictionary of index -> true, parameters at specified indices may be stored by the callback --]] --- Compatibility with both Lua 5.1 and LuaJit -- (generates a LuaCheck 143 warning - Accessing undefined field of a table) -- luacheck: push ignore 143 local unpack = unpack or table.unpack -- luacheck: pop --- Use the Scenario loading library: local Scenario = dofile("Scenario.lua") --- The protocol number to use for things that report client protocol local PROTOCOL_NUMBER = 210 -- client version 1.10.0 --- The class (metatable) to be used for all simulators local Simulator = {} Simulator["__index"] = Simulator --- Adds a new callback request to the queue to be processed -- a_ParamTypes is an array of strings describing the param types -- a_Notes is a description of the request for logging purposes -- a_ParamValues is an optional array of params' values function Simulator:addCallbackRequest(a_FnToCall, a_ParamTypes, a_Notes, a_ParamValues) -- Check params: assert(self) assert(type(a_FnToCall) == "function") local paramTypes = a_ParamTypes or {} assert(type(paramTypes) == "table") -- Add the request to the queue: local n = self.callbackRequests.n + 1 self.callbackRequests[n] = { Function = a_FnToCall, ParamTypes = paramTypes, ParamValues = a_ParamValues, Notes = a_Notes } self.callbackRequests.n = n -- Call the notification callback: self:callHooks(self.hooks.onAddedRequest) end --- Adds a CallbackRequest to call the specified command with the specified CommandSplit -- a_Handler is the command's registered callback function -- a_CommandSplit is an array-table of strings used as the splitted command -- a_PlayerInstance is an optional cPlayer instance representing the player. If not given, a dummy one is created function Simulator:addCommandCallbackRequest(a_Handler, a_CommandSplit, a_PlayerInstance) local player = a_PlayerInstance or self:createInstance({Type = "cPlayer"}) local entireCmd = table.concat(a_CommandSplit, " ") self:addCallbackRequest(a_Handler, nil, string.format("command \"%s\"", entireCmd), { a_CommandSplit, player, entireCmd }) end --- Adds the hooks to the simulator, based on the options specified by the user function Simulator:addHooks(a_Options) if (a_Options.shouldClearObjects) then table.insert(self.hooks.onBeforeCallCallback, Simulator.beforeCallClearObjects) table.insert(self.hooks.onAfterCallCallback, Simulator.afterCallClearObjects) end if (a_Options.shouldGCObjects) then table.insert(self.hooks.onBeforeCallCallback, Simulator.beforeCallGCObjects) table.insert(self.hooks.onAfterCallCallback, Simulator.afterCallGCObjects) end end --- Adds the specified file / folder redirections -- The previous redirects are kept function Simulator:addRedirects(a_Redirects) -- Check params: assert(self) assert(type(a_Redirects) == "table") -- Add the redirects: for orig, new in pairs(a_Redirects) do self.redirects[orig] = new end end --- Called by the simulator after calling the callback, when the ClearObjects is specified in the options -- a_Params is an array-table of the params that were given to the callback -- a_Returns is an array-table of the return values that the callback returned function Simulator:afterCallClearObjects(a_Request, a_Params, a_Returns) -- Check params: assert(self) assert(a_Params) -- Change the objects in parameters so that any access to them results in an error: local requestNotes = a_Request.Notes for idx, param in ipairs(a_Params) do if ((type(param) == "userdata") and not(a_Request.AllowsStore[idx])) then getmetatable(param).__index = function() self.logger:error(3, "Attempting to use an object that has been stored from a callback %q.", requestNotes) end end end end --- Called by the simulator after calling the callback, when the GCObjects is specified in the options -- a_Params is an array-table of the params that were given to the callback -- a_Returns is an array-table of the return values that the callback returned function Simulator:afterCallGCObjects(a_Request, a_Params, a_Returns) -- Check params: assert(self) assert(a_Params) -- Remove the references to the parameters: for idx, param in ipairs(a_Params) do if (type(param) == "userdata") then a_Params[idx] = nil end end -- Collect garbage, check if all the parameter references have been cleared: collectgarbage() for idx, t in pairs(a_Request.uncollectedParams) do local info = debug.getinfo(a_Request.Function, "S") if (info.source and string.sub(info.source, 1, 1) == "@") then self.logger:error(1, "Plugin has stored an instance of param #%d (%s) from callback %q for later reuse. Function defined in %s, lines %s - %s", idx, t, a_Request.Notes, string.sub(info.source, 2), info.linedefined or "<unknown>", info.lastlinedefined or "<unknown>" ) else self.logger:error(1, "Plugin has stored an instance of param #%d (%s) from callback %q for later reuse. Function definition not found.", idx, t, a_Request.Notes ) end end end --- Called by the simulator after calling the callback, when the ClearObjects is specified in the options -- a_Request is a table describing the entire callback request -- a_Params is an array-table of the params that are to be given to the callback function Simulator:beforeCallClearObjects(a_Request, a_Params) -- Nothing needed end --- Called by the simulator before calling the callback, when the GCObjects is specified in the options -- a_Params is an array-table of the params that are to be given to the callback function Simulator:beforeCallGCObjects(a_Request, a_Params) -- We need to create a duplicate of the parameters, because they might still be stored somewhere below on the stack -- which would interfere with the GC a_Request.ParamValues = self:duplicateInstances(a_Params) a_Params = a_Request.ParamValues -- Make note of all the parameters and whether they are GCed: a_Request.uncollectedParams = {} for idx, param in ipairs(a_Params) do local t = type(param) if ((t == "userdata") and not (a_Request.AllowsStore[idx])) then local paramType = self:typeOf(param) a_Request.uncollectedParams[idx] = paramType local mt = getmetatable(param) local oldGC = mt.__gc mt.__gc = function(...) self.logger:trace("GCing param #%d (%s) of request %p", idx, paramType, a_Request.Notes) a_Request.uncollectedParams[idx] = nil if (oldGC) then oldGC(...) end end end end end --- Calls all the hooks in the specified table with any params function Simulator:callHooks(a_Hooks, ...) -- Check params: assert(type(a_Hooks) == "table") -- Call the hooks: for _, hook in ipairs(a_Hooks) do hook(self, ...) end end --- Checks whether the given parameters match the given function signature -- Assumes that the parameter counts are the same (checked by the caller) -- a_FnSignature is an array-table of params, as given by the API description -- a_Params is an array-table of parameters received from the plugin -- a_NumParams is the number of parameters in a_Params (specified separately due to possible nil parameters) -- a_ClassName is the name of the class in which the function resides, or nil if the function is a global -- Returns true if the signature matches, false and optional error message on mismatch function Simulator:checkClassFunctionSignature(a_FnSignature, a_Params, a_NumParams, a_ClassName) -- Check params: assert(type(a_FnSignature) == "table") assert(type(a_Params) == "table") assert(type(a_NumParams) == "number") -- If the function is in a class, check the "self" param: local paramOffset = 0 if (a_ClassName) then paramOffset = 1 if (a_FnSignature.IsStatic) then -- For a static function, the first param should be the class itself: if (type(a_Params[1]) ~= "table") then return false, "The \"self\" parameter is not a class (table)" end local mt = getmetatable(a_Params[1]) if not(mt) then return false, "The \"self\" parameter is not a class (metatable)" end if not(rawget(a_Params[1], "simulatorInternal_ClassName")) then return false, "The \"self\" parameter is not a Cuberite class" end if not(self:classInheritsFrom(a_Params[1].simulatorInternal_ClassName, a_ClassName)) then return false, string.format( "The \"self\" parameter is a different class. Expected %s, got %s.", a_ClassName, a_Params[1].simulatorInternal_ClassName ) end else -- For a non-static function, the first param should be an instance of the class: if (type(a_Params[1]) ~= "userdata") then return false, "The \"self\" parameter is not a class (userdatum)" end local classMT = getmetatable(a_Params[1]) if not(classMT) then return false, "The \"self\" parameter is not a class instance (class metatable)" end if not(rawget(classMT.__index, "simulatorInternal_ClassName")) then return false, "The \"self\" parameter is not a Cuberite class instance" end if not(self:classInheritsFrom(classMT.__index.simulatorInternal_ClassName, a_ClassName)) then return false, string.format( "The \"self\" parameter is a different class instance. Expected %s, got %s.", a_ClassName, classMT.__index.simulatorInternal_ClassName ) end end end -- Check the type of each plugin parameter: for idx = paramOffset + 1, a_NumParams do local signatureParam = a_FnSignature.Params[idx - paramOffset] if not(signatureParam) then return false, string.format("There are more parameters (%d) than in the signature (%d)", a_NumParams - paramOffset, idx - paramOffset - 1) end local param = a_Params[idx] if ((param ~= nil) or not(signatureParam.IsOptional)) then -- Optional param always matches a nil local paramType = self:typeOf(param) if not(self:paramTypesMatch(paramType, signatureParam.Type)) then return false, string.format("Param #%d doesn't match, expected %s, got %s", idx - paramOffset, signatureParam.Type, paramType ) end end end -- All given params have matched, now check that all the leftover params in the signature are optional: local idx = a_NumParams + 1 while (a_FnSignature.Params[idx]) do if not(a_FnSignature.Params[idx].IsOptional) then return false, string.format("Param #d (%s) is missing.", idx, a_FnSignature.Params[idx].Type) end idx = idx + 1 end -- All params have matched return true end --- Checks the inheritance tree -- Returns true if class "a_ChildName" inherits from class "a_ParentName" (or they are the same) function Simulator:classInheritsFrom(a_ChildName, a_ParentName) -- Check params: assert(self) assert(type(a_ChildName) == "string") assert(type(a_ParentName) == "string") -- If they are the same class, consider them inheriting: if (a_ChildName == a_ParentName) then return true end -- Check the inheritance using the child class API: local childClass = self.sandbox[a_ChildName] if not(childClass) then self.logger:warning("Attempting to check inheritance for non-existent class \"%s\".\n%s", a_ChildName, debug.traceback()) return false end local childApi = childClass.simulatorInternal_ClassApi or {} for _, parent in ipairs(childApi.Inherits or {}) do if (self:classInheritsFrom(parent, a_ParentName)) then return true end end -- None of the inherited classes matched return false end --- Removes all state information previously added through a scenario -- Removes worlds, players function Simulator:clearState() -- Check params: assert(self) self.worlds = {} self.players = {} end --- Collapses the relative parts of the path, such as "folder/../" function Simulator:collapseRelativePath(a_Path) -- Check params: assert(type(a_Path) == "string") -- Split the path on each "/" and rebuild without the relativeness: local res = {} local idx = 0 while (idx) do local lastIdx = idx + 1 idx = a_Path:find("/", lastIdx) local part if not(idx) then part = a_Path:sub(lastIdx) else part = a_Path:sub(lastIdx, idx - 1) end if (part == "..") then if ((#res > 0) and (res[#res - 1] ~= "..")) then -- The previous part is not relative table.remove(res) else table.insert(res, part) end else table.insert(res, part) end end return table.concat(res, "/") end --- Simulates a player joining the game -- a_PlayerDesc is a dictionary-table describing the player (name, worldName, gameMode, ip) -- "name" is compulsory, the rest is optional -- Calls all the hooks that are normally triggered for a joining player -- If any of the hooks refuse the join, doesn't add the player and returns false -- Returns true if the player was added successfully function Simulator:connectPlayer(a_PlayerDesc) -- Check params: assert(self) assert(type(a_PlayerDesc) == "table") local playerName = a_PlayerDesc.name assert(type(playerName) == "string") assert(self.defaultWorldName, "No world in the simulator") -- Create the player, with some reasonable defaults: a_PlayerDesc.worldName = a_PlayerDesc.worldName or self.defaultWorldName a_PlayerDesc.uniqueID = self:getNextUniqueID() self.players[playerName] = a_PlayerDesc -- Call the hooks to simulate the player joining: local client = self:createInstance({Type = "cClientHandle"}) getmetatable(client).simulatorInternal_PlayerName = playerName if (self:executeHookCallback("HOOK_LOGIN", client, PROTOCOL_NUMBER, playerName)) then self.logger:trace("Plugin refused player \"%s\" to connect.", playerName) self.players[playerName] = nil -- Remove the player return false end self:executeHookCallback("HOOK_PLAYER_JOINED", self:getPlayerByName(playerName)) -- If the plugin kicked the player, abort: if not(self.players[playerName]) then self.logger:trace("Plugin kicked player \"%s\" while they were joining.", playerName) return false end -- Spawn the player: self:executeHookCallback("HOOK_PLAYER_SPAWNED", self:getPlayerByName(playerName)) if not(self.players[playerName]) then self.logger:trace("Plugin kicked player \"%s\" while they were spawning.", playerName) return false end return true end --- Creates an API endpoint (function, constant or variable) dynamically -- a_ClassApi is the API description of the class or the Globals -- a_SymbolName is the name of the symbol that is requested -- a_ClassName is the name of the class (or "Globals") where the function resides; for logging purposes only function Simulator:createApiEndpoint(a_ClassApi, a_SymbolName, a_ClassName) -- CheckParams: assert(self) assert(type(a_ClassApi) == "table") assert(a_ClassApi.Functions) assert(a_ClassApi.Constants) assert(a_ClassApi.Variables) assert(type(a_SymbolName) == "string") assert(type(a_ClassName) == "string") -- Create the endpoint: local res if (a_ClassApi.Functions[a_SymbolName]) then res = self:createClassFunction(a_ClassApi.Functions[a_SymbolName], a_SymbolName, a_ClassName) elseif (a_ClassApi.Constants[a_SymbolName]) then res = self:createClassConstant(a_ClassApi.Constants[a_SymbolName], a_SymbolName, a_ClassName) elseif (a_ClassApi.Variables[a_SymbolName]) then res = self:createClassVariable(a_ClassApi.Variables[a_SymbolName], a_SymbolName, a_ClassName) end if (res) then return res end -- If not found, try to create it in the class parents: for _, className in ipairs(a_ClassApi.Inherits or {}) do res = self.sandbox[className][a_SymbolName] if (res) then return res end end -- Endpoint not found: return nil end --- Definitions for operators -- This table pairs operators' APIDoc names with their Lua Meta-method names and names used for logging local g_Operators = { { docName = "operator_div", metaName = "__div", logName = "operator div" }, { docName = "operator_eq", metaName = "__eq", logName = "operator eq" }, { docName = "operator_minus", metaName = "__sub", logName = "operator minus" }, { docName = "operator_minus", metaName = "__unm", logName = "operator unary-minus" }, { docName = "operator_mul", metaName = "__mul", logName = "operator mul" }, { docName = "operator_plus", metaName = "__add", logName = "operator plus" }, } --- Creates a sandbox implementation of the specified API class -- a_ClassName is the name of the class (used for error-reporting) -- a_ClassApi is the class' API description -- Returns a table that is to be stored in the sandbox under the class' name function Simulator:createClass(a_ClassName, a_ClassApi) -- Check params: assert(self) assert(type(a_ClassName) == "string") assert(type(a_ClassApi) == "table") assert(a_ClassApi.Functions) assert(a_ClassApi.Constants) assert(a_ClassApi.Variables) self.logger:trace("Creating class \"%s\".", a_ClassName) -- Create a metatable that dynamically creates the API endpoints, and stores info about the class: local mt = { __index = function(a_Table, a_SymbolName) if ((a_SymbolName == "__tostring") or (a_SymbolName == "__serialize")) then -- Used by debuggers all the time, spamming the log. Bail out early. return nil end self.logger:trace("Creating an API endpoint \"%s.%s\".", a_ClassName, a_SymbolName) local endpoint = self:createApiEndpoint(a_ClassApi, a_SymbolName, a_ClassName) if not(endpoint) then self.logger:error(3, "Attempting to use a non-existent API: \"%s.%s\".", a_ClassName, a_SymbolName) end return endpoint end, } -- If the class has a constructor, add it to the meta-table, because it doesn't go through the __index meta-method: if (a_ClassApi.Functions.new) then mt.__call = function (...) self.logger:trace("Creating constructor for class %s.", a_ClassName) local endpoint = self:createApiEndpoint(a_ClassApi, "new", a_ClassName) if not(endpoint) then self.logger:error(3, "Attempting to use a constructor for class %s that doesn't have one.", a_ClassName) end return endpoint(...) end end if (a_ClassApi.Functions.constructor) then mt.__call = function (...) self.logger:trace("Creating constructor for class %s.", a_ClassName) local endpoint = self:createApiEndpoint(a_ClassApi, "constructor", a_ClassName) if not(endpoint) then self.logger:error(3, "Attempting to use a constructor for class %s that doesn't have one.", a_ClassName) end return endpoint(...) end end -- Add any operators to the class-table, because they don't go through the __index meta-method: -- Also they apparently don't go through meta-table nesting, so need to create them directly in the class-table local res = {} res.__index = res for _, op in ipairs(g_Operators) do if (a_ClassApi.Functions[op.docName]) then res[op.metaName] = function (...) self.logger:trace("Creating %s for class %s", op.logName, a_ClassName) local endpoint = self:createApiEndpoint(a_ClassApi, op.docName, a_ClassName) if not(endpoint) then self.logger:error(3, "Attempting to use %s for class %s that doesn't have one.", op.logName, a_ClassName) end return endpoint(...) end end end setmetatable(res, mt) self.sandbox[a_ClassName] = res -- Store the class for the next time (needed at least for operator_eq) res.simulatorInternal_ClassName = a_ClassName res.simulatorInternal_ClassApi = a_ClassApi return res end --- Creates a constant based on its API description -- Provides a dummy value if no value is given function Simulator:createClassConstant(a_ConstDesc, a_ConstName, a_ClassName) -- Check params: assert(self) assert(type(a_ConstDesc) == "table") assert(type(a_ConstName) == "string") assert(type(a_ClassName) == "string") -- If the value is specified, return it directly: if (a_ConstDesc.Value) then return a_ConstDesc.Value end -- Synthesize a dummy value of the proper type: if not(a_ConstDesc.Type) then self.logger:error(1, "Simulator error: API description for constant %s.%s doesn't provide value nor type", a_ClassName, a_ConstName) end return self:createInstance(a_ConstDesc) end --- Creates a variable based on its API description function Simulator:createClassVariable(a_VarDesc, a_VarName, a_ClassName) -- Check params: assert(self) assert(type(a_VarDesc) == "table") assert(type(a_VarName) == "string") assert(type(a_ClassName) == "string") -- If the value is specified, return it directly: if (a_VarDesc.Value) then return a_VarDesc.Value end -- Synthesize a dummy value of the proper type: return self:createInstance(a_VarDesc) end --- Creates a dummy API function implementation based on its API description: function Simulator:createClassFunction(a_FnDesc, a_FnName, a_ClassName) -- Check params: assert(self) assert(type(a_FnDesc) == "table") assert(type(a_FnName) == "string") assert(type(a_ClassName) == "string") return function(...) self.logger:trace("Calling function %s.%s.", a_ClassName, a_FnName) local params = { ... } self:callHooks(self.hooks.onApiFunctionCall, a_ClassName, a_FnName, params) local signature, msgs = self:findClassFunctionSignatureFromParams(a_FnDesc, params, a_ClassName) if not(signature) then self.logger:error(3, "Function %s.%s used with wrong parameters, there is no overload that can take these:\n\t%s\nMatcher messages:\n\t%s", a_ClassName, a_FnName, table.concat(self:listParamTypes(params), "\n\t"), table.concat(msgs, "\n\t") ) end if (signature.Implementation) then -- This function has a specific implementation, call it: return signature.Implementation(self, ...) else -- Provide a default implementation by default-constructing the return values: return unpack(self:createInstances(signature.Returns, params[1])) end end end --- Creates a single instance of a type - for a callback request or as an API function return value function Simulator:createInstance(a_TypeDef) -- Check params: assert(self) assert(type(a_TypeDef) == "table") local t = a_TypeDef.Type assert(t) -- Remove modifiers: t = t:gsub("const ", "") -- If it is a built-in type, create it directly: if (t == "string") then self.testStringIndex = (self.testStringIndex + 1) % 5 -- Repeat the same string every 5 calls return "TestString" .. self.testStringIndex elseif (t == "number") then self.testNumber = (self.testNumber + 1) % 5 -- Repeat the same number every 5 calls return self.testNumber elseif (t == "boolean") then return true elseif (t == "table") then return { "testTable", testTable = "testTable" } end -- If it is a known enum, return a number: local enumDef = self.enums[t] if (enumDef) then -- TODO: Choose a proper value for the enum return 1 end -- If it is a class param, create a class instance: local classTable = self.sandbox[t] if not(classTable) then self.logger:error(2, "Requested an unknown param type for callback request: \"%s\".", t) end self.logger:trace("Created a new instance of %s", t) local res = newproxy(true) getmetatable(res).__index = classTable assert(classTable.__index == classTable, string.format("Class %s is not properly injected", t)) return res end --- Creates all object instances required for a callback request -- a_TypeDefList is an array of type descriptions ({Type = "string"}) -- a_Self is the value that should be returned whenever the type specifies "self" (used by chaining functions) -- Returns the instances as an array-table function Simulator:createInstances(a_TypeDefList, a_Self) -- Check params: assert(type(a_TypeDefList) == "table") -- Create the instances: local res = {} for idx, td in ipairs(a_TypeDefList) do if (td.Type == "self") then res[idx] = a_Self else res[idx] = self:createInstance(td) end end return res end --- Creates a new world with the specified parameters -- a_WorldDesc is a dictionary-table containing the world description - name, dimension, default gamemode etc. -- Only the name member is compulsory, the rest are optional -- After creating the world, the world creation hooks are executed function Simulator:createNewWorld(a_WorldDesc) -- Check params: assert(self) assert(type(a_WorldDesc) == "table") assert(type(a_WorldDesc.name) == "string") -- Check if such a world already present: local worldName = a_WorldDesc.name if (self.worlds[worldName]) then self.logger:error(2, "Cannot create world, a world with name \"%s\" already exists.", worldName) end -- Create the world: self.logger:trace("Creating new world \"%s\".", worldName) a_WorldDesc.dimension = a_WorldDesc.dimension or 0 a_WorldDesc.defaultGameMode = a_WorldDesc.defaultGameMode or 0 self.worlds[worldName] = a_WorldDesc if not(self.defaultWorldName) then self.defaultWorldName = worldName end -- Call the hooks for the world creation: local world = self:createInstance({Type = "cWorld"}) getmetatable(world).simulatorInternal_worldName = worldName self:executeHookCallback("HOOK_WORLD_STARTED", world) end --- Replacement for the sandbox's dofile function -- Needs to apply the sandbox to the loaded code function Simulator:dofile(a_FileName) -- Check params: assert(self) assert(type(self.sandbox) == "table") self.logger:trace("Executing file \"%s\".", a_FileName) local res, msg = loadfile(a_FileName) if not(res) then self.logger:error(3, "Error while executing file \"%s\": %s", a_FileName, msg) end setfenv(res, self.sandbox) return res() end --- Creates a duplicate of each given instance -- a_Instance is any instance -- Returns a copy of a_Instance -- Note that tables are not duplicated, they are returned as-is instead function Simulator:duplicateInstance(a_Instance) local t = type(a_Instance) if (t == "table") then -- Do NOT duplicate tables return a_Instance elseif (t == "userdata") then local res = newproxy(true) local mt = getmetatable(res) for k, v in pairs(getmetatable(a_Instance) or {}) do mt[k] = v end return res else -- All the other types are value-types, no need to duplicate return a_Instance end end --- Creates a duplicate of each given instance -- a_Instances is an array-table of any instances -- Returns an array-table of copies of a_Instances function Simulator:duplicateInstances(a_Instances) local res = {} for k, v in pairs(a_Instances) do res[k] = self:duplicateInstance(v) end return res end --- Executes a callback request simulating the admin executing the specified console command -- Calls the command execution hooks and if they allow, the command handler itself -- Returns true if the command was executed, false if not. function Simulator:executeConsoleCommand(a_CommandString) -- Check params: assert(self) assert(type(a_CommandString) == "string") -- Call the command execution hook: local split = self:splitCommandString(a_CommandString) if (self:executeHookCallback("HOOK_EXECUTE_COMMAND", nil, split, a_CommandString)) then self.logger:trace("Plugin hook refused to execute console command \"%s\".", a_CommandString) return false end -- Call the command handler: split = self:splitCommandString(a_CommandString) -- Re-split, in case the hooks changed it local cmdReg = self.registeredConsoleCommandHandlers[split[1]] if not(cmdReg) then self.logger:warning("Trying to execute console command \"%s\" for which there's no registered handler.", split[1]) return false end local res = self:processCallbackRequest( { Function = cmdReg.callback, ParamValues = { split, a_CommandString }, Notes = "Console command " .. a_CommandString, } ) if ((type(res) == "table") and (type(res[2]) == "string")) then self.logger:info("Console command \"%s\" returned string \"%s\".", a_CommandString, res[2]) end return true end --- Executes a callback request simulating the specified hook type -- a_HookTypeStr is the string name of the hook ("HOOK_PLAYER_DISCONNECTING" etc.) -- All the rest of the params are given to the hook as-is -- If a hook returns true (abort), stops processing the hooks and returns false -- Otherwise returns false and the rest of the values returned by the hook function Simulator:executeHookCallback(a_HookTypeStr, ...) -- Check params: assert(self) assert(type(a_HookTypeStr) == "string") local hookType = self.sandbox.cPluginManager[a_HookTypeStr] assert(hookType) -- Call all hook handlers: self.logger:trace("Triggering hook handlers for %s", a_HookTypeStr) local params = {...} local hooks = self.registeredHooks[hookType] or {} local res for idx, callback in ipairs(hooks) do res = self:processCallbackRequest( { Function = callback, ParamValues = params, Notes = a_HookTypeStr, } ) if (res[1]) then -- The hook asked for an abort self.logger:trace("Hook handler #%d for hook %s aborted the hook chain.", idx, a_HookTypeStr) return true end -- TODO: Some hooks should have special processing - returning a value overwrites the param for the rest of the hooks end if (res) then return false, unpack(res, 2) else return false end end --- Executes a callback request simulating the player executing the specified command -- Calls the command execution hooks and if they allow, the command handler itself -- Returns true if the command was executed, false if not. -- Doesn't care whether the player is in the list of connected players or not function Simulator:executePlayerCommand(a_PlayerName, a_CommandString) -- Check params: assert(self) assert(type(a_PlayerName) == "string") assert(type(a_CommandString) == "string") -- Call the command execution hook: local split = self:splitCommandString(a_CommandString) if (self:executeHookCallback("HOOK_EXECUTE_COMMAND", self:getPlayerByName(a_PlayerName), split, a_CommandString)) then self.logger:trace("Plugin hook refused to execute command \"%s\" from player %s.", a_CommandString, a_PlayerName) return false end -- Call the command handler: split = self:splitCommandString(a_CommandString) -- Re-split, in case the hooks changed it local cmdReg = self.registeredCommandHandlers[split[1]] if not(cmdReg) then self.logger:warning("Trying to execute command \"%s\" for which there's no registered handler.", split[1]) return false end self:processCallbackRequest( { Function = cmdReg.callback, ParamValues = { split, self:getPlayerByName(a_PlayerName), a_CommandString }, Notes = "Command " .. a_CommandString, } ) return true end --- Returns the API signature for a function, based on its params (overload-resolution) -- a_FnDesc is the function's description table (array of signatures and map of properties) -- a_Params is an array-table of the params given by the plugin -- Returns the signature of the function (item in a_FnDescs) that matches the params -- If no signature matches, returns nil and an array-table of error messages from signature-matching function Simulator:findClassFunctionSignatureFromParams(a_FnDesc, a_Params, a_ClassName) -- Check params: assert(self) assert(type(a_FnDesc) == "table") assert(type(a_Params) == "table") -- Find the number of params in a_Params (note that some may be nil, in which case Lua's "#" operator doesn't work) local numParamsGiven = 0 for k, v in pairs(a_Params) do if (numParamsGiven < k) then numParamsGiven = k end end -- Check the signatures that have the same number of params: local msgs = {} for _, signature in ipairs(a_FnDesc) do local className if not(signature.IsGlobal) then className = a_ClassName end local doesMatch, msg = self:checkClassFunctionSignature(signature, a_Params, numParamsGiven, className) if (doesMatch) then return signature end table.insert(msgs, (msg or "<no message>") .. " (signature: " .. utils.prettyPrintFunctionSignature(signature) .. ")") end -- None of the signatures matched the params, report an error: return nil, msgs end --- Called when the request queue is empty and command fuzzing is enabled -- If there is a command yet to be fuzzed, queues its request function Simulator:fuzzCommandHandlers() -- Check params: assert(self) -- If called for the first time, make a list of not-yet-fuzzed commands: if not(self.currentFuzzedCommandTest) then self.logger:trace("Starting the command fuzzer") self.commandsToFuzz = {} local idx = 1 for cmd, _ in pairs(self.registeredCommandHandlers) do self.commandsToFuzz[idx] = cmd idx = idx + 1 end self.currentFuzzedCommandTest = 1 end -- If no more commands to fuzz, bail out: if not(self.commandsToFuzz[1]) then return end -- Add the fuzzing request for the next command handler into the queue: local test = self.currentFuzzedCommandTest local cmd = self:splitCommandString(self.commandsToFuzz[1]) local desc = self.registeredCommandHandlers[cmd[1]] if (test == 1) then self:addCommandCallbackRequest(desc.callback, cmd) elseif (test == 2) then table.insert(cmd, "a") self:addCommandCallbackRequest(desc.callback, cmd) elseif (test == 3) then table.insert(cmd, "1") self:addCommandCallbackRequest(desc.callback, cmd) -- TODO: more tests here else -- All tests done, move to next command (using recursion): table.remove(self.commandsToFuzz, 1) self.currentFuzzedCommandTest = 1 self:fuzzCommandHandlers() return end self.currentFuzzedCommandTest = self.currentFuzzedCommandTest + 1 end --- Returns a new UniqueID for an entity function Simulator:getNextUniqueID() -- Check params: assert(self) self.currUniqueID = (self.currUniqueID or 0) + 1 return self.currUniqueID end --- Returns a cPlayer instance that is bound to the specified player -- If the player is not in the list of players, returns nil function Simulator:getPlayerByName(a_PlayerName) -- Check params: assert(self) assert(type(a_PlayerName) == "string") -- If the player is not currently connected, return nil: if not(self.players[a_PlayerName]) then return nil end -- Create a new instance and bind it: local player = self:createInstance({Type = "cPlayer"}) local mt = getmetatable(player) mt.simulatorInternal_Name = a_PlayerName mt.simulatorInternal_UniqueID = self.players[a_PlayerName].uniqueID return player end --- Calls the plugin's Initialize() function function Simulator:initializePlugin() -- Check params: assert(getmetatable(self) == Simulator) -- Call the plugin's Initialize function: local res = self:processCallbackRequest( { Function = self.sandbox.Initialize, ParamValues = { self.sandbox.cPluginManager:Get():GetCurrentPlugin() }, Notes = "Initialize()", AllowsStore = {[1] = true}, } ) if not(res[1]) then self.logger:error(2, "The plugin initialization failed") end end --- Injects the API classes and global symbols into the simulator's sandbox function Simulator:injectApi(a_ApiDesc) -- Check params: assert(self) assert(type(a_ApiDesc.Classes) == "table") assert(type(a_ApiDesc.Globals) == "table") -- Inject the metatable override that creates global API symbols: local sandboxMT = getmetatable(self.sandbox) if not(sandboxMT) then sandboxMT = {} setmetatable(self.sandbox, sandboxMT) end local prevIndex = sandboxMT.__index sandboxMT.__index = function(a_Table, a_SymbolName) -- If a class is requested, create it: if (a_ApiDesc.Classes[a_SymbolName]) then a_Table[a_SymbolName] = self:createClass(a_SymbolName, a_ApiDesc.Classes[a_SymbolName]) return a_Table[a_SymbolName] end -- If a global API symbol is requested, create it: local endpoint = self:createApiEndpoint(a_ApiDesc.Globals, a_SymbolName, "Globals") if (endpoint) then a_Table[a_SymbolName] = endpoint return endpoint end -- Failed to create the endpoint, chain to previous __index or raise an error: if not(prevIndex) then self.logger:warning("Attempting to use an unknown Global value \"%s\", nil will be returned.\n%s", a_SymbolName, debug.traceback()) return nil end assert(type(prevIndex) == "function") -- We don't support table-based __index yet (but can be done) return prevIndex(a_Table, a_SymbolName) end self:prefillApi(a_ApiDesc) -- Store all enum definitions in a separate table: for className, cls in pairs(a_ApiDesc.Classes) do for enumName, enumValues in pairs(cls.Enums or {}) do self.enums[className .. "#" .. enumName] = enumValues end end for enumName, enumValues in pairs(a_ApiDesc.Globals.Enums or {}) do self.enums[enumName] = enumValues self.enums["Globals#" .. enumName] = enumValues -- Store under Globals#eEnum too end end -- Puts APIEndpoints in the sandbox if one of all provided patterns match it. function Simulator:prefillApi(a_ApiDesc) -- Returns true if the provided string matches any of the prefillSymbolPatterns local function matchesAnyPattern(a_Target) for _, pattern in pairs(self.options.prefillSymbolPatterns) do if (a_Target:match(pattern)) then return true end end return false; end local function fillApi(a_FAApiDesc, a_SymbolName, a_Sandbox) assert(type(a_FAApiDesc) == "table") assert(type(a_SymbolName) == "string") assert(type(a_Sandbox) == "table") for functionName, functionDesc in pairs(a_FAApiDesc.Functions) do if (matchesAnyPattern(a_SymbolName .. ":" .. functionName)) then a_Sandbox[functionName] = self:createClassFunction(functionDesc, functionName, a_SymbolName) end end for constantName, constantDesc in pairs(a_FAApiDesc.Constants) do if (constantDesc.Value and matchesAnyPattern(a_SymbolName .. "." .. constantName)) then a_Sandbox[constantName] = self:createClassConstant(constantDesc, constantName, a_SymbolName); end end return a_Sandbox end fillApi(a_ApiDesc.Globals, "Globals", self.sandbox) for className, classDesc in pairs(a_ApiDesc.Classes) do self.sandbox[className] = fillApi(classDesc, className, self.sandbox[className]) end end --- Returns an array-table of a_Params' types -- Resolves class types function Simulator:listParamTypes(a_Params) local res = {} for idx, param in ipairs(a_Params) do res[idx] = self:typeOf(param) end return res end --- Replacement for the global "loadfile" symbol in the sandbox -- Needs to apply the sandbox to the loaded code function Simulator:loadfile(a_FileName) -- Check params: assert(self) assert(type(self.sandbox) == "table") local res, msg = loadfile(a_FileName) if (res) then setfenv(res, self.sandbox) end return res, msg end --- Loads the plugin's files and executes their globals function Simulator:loadPluginFiles() -- Check params: assert(getmetatable(self) == Simulator) assert(self.options.pluginFiles[1]) -- Load the plugin files, execute the globals: for _, fnam in ipairs(self.options.pluginFiles) do local fn = assert(loadfile(fnam)) setfenv(fn, self.sandbox) fn() end assert(self.sandbox.Initialize, "The plugin doesn't have the Initialize() function.") end --- Replacement for the global "loadstring" symbol in the sandbox -- Needs to apply the sandbox to the loaded code function Simulator:loadstring(a_String) -- Check params: assert(self) assert(type(self.sandbox) == "table") local res, msg = loadstring(a_String) if not(res) then setfenv(res, self.sandbox) end return res, msg end --- Compares the type of a parameter to the type in the signature -- Returns true if the param type is compatible with the signature -- Compatibility is: -- - both are exactly equal -- - ParamType is a number and SignatureType being an enum -- - ParamType is nil and SignatureType is a class -- - ParamType is a class that is a descendant of the SignatureType class function Simulator:paramTypesMatch(a_ParamType, a_SignatureType) -- Check params: assert(type(a_ParamType) == "string") assert(type(a_SignatureType) == "string") assert(self) -- If the signature type is "any", any param type matches: if (a_SignatureType == "any") then return true end -- If the types are exactly equal, return "compatible": if (a_ParamType == a_SignatureType) then return true end -- If the param is nil, it is compatible with any class: if (a_ParamType == "nil") then return not(not(self.sandbox[a_SignatureType])) end -- If the signature says an enum and the param is a number, return "compatible": if (a_ParamType == "number") then if (self.enums[a_SignatureType]) then return true end end -- If both types are classes and the param is a descendant of signature, return "compatible": if (self:classInheritsFrom(a_ParamType, a_SignatureType)) then return true end return false end --- Keeps dequeueing the callback requests from the internal queue and calling them, until the queue is empty -- It is safe to queue more callback requests while it is executing function Simulator:processAllQueuedCallbackRequests() -- Check params: assert(self) -- Process the callback requests one by one. -- Don't delete the processed ones, just remember the last executed index, terminate when it reaches the last queued callback: local idx = 1 while (idx <= self.callbackRequests.n) do self:processCallbackRequest(self.callbackRequests[idx]) idx = idx + 1 end -- Reset the queue, everything has been processed, so just assign an empty one: self.callbackRequests = { n = 0 } end --- Processes a single callback request -- Prepares the params and calls the function -- Calls the appropriate simulator hooks -- Returns all the values that the callback returned function Simulator:processCallbackRequest(a_Request) -- Check params: assert(self) assert(a_Request) assert(a_Request.Function) a_Request.AllowsStore = a_Request.AllowsStore or {} if (a_Request.Notes) then self.logger:debug("Calling request \"%s\".", a_Request.Notes) end self:callHooks(self.hooks.onBeginRound, a_Request) -- Prepare the params: a_Request.ParamValues = a_Request.ParamValues or self:createInstances(a_Request.ParamTypes or {}) self:callHooks(self.hooks.onBeforeCallCallback, a_Request, a_Request.ParamValues) -- Call the callback: local returns = { a_Request.Function(unpack(a_Request.ParamValues)) } -- Process the returned values and finalize the params: self:callHooks(self.hooks.onAfterCallCallback, a_Request, a_Request.ParamValues, returns) self:callHooks(self.hooks.onEndRound, a_Request) return returns end --- Adds a callback request into the internal queue of callbacks to be made later on -- a_Request is a table describing the callback, as used in the processCallbackRequest() function function Simulator:queueCallbackRequest(a_Request) -- Check params: assert(self) assert(type(a_Request) == "table") assert(a_Request.Function) -- Add the request in the queue: local n = self.callbackRequests.n + 1 self.callbackRequests[n] = a_Request self.callbackRequests.n = n end --- Returns a path to use, while checking for redirection function Simulator:redirectPath(a_Path) -- Check params: assert(self) assert(type(a_Path) == "string") a_Path = self:collapseRelativePath(a_Path) -- If there is a matching entry in the redirects, use it: local match = self.redirects[a_Path] if (match) then local res = self.options.scenarioPath .. match self.logger:trace(string.format("Redirecting \"%s\" to \"%s\".", a_Path, res)) return res end -- If there is a full foldername match, use it: -- (eg. redirect for "folder1/folder2/", path is "folder1/folder2/folder3/file.txt" -> use the redirect for the front part local idx = 0 while (true) do idx = a_Path:find("/", idx + 1) -- find the next slash if not(idx) then -- No redirection match return a_Path end match = self.redirects[a_Path:sub(1, idx)] -- check the path up to the current slash for redirects: if (match) then local res = self.options.scenarioPath .. match .. a_Path.sub(idx + 1) self.logger:trace(string.format("Redirecting \"%s\" to \"%s\".", a_Path, res)) return res end end end --- Simulates the plugin, may hard-abort on error -- a_Options is the Options object that can be queried for global options -- a_Api is the complete API description function Simulator:run(a_Options) -- Check params: assert(type(a_Options) == "table") -- We have an Options object assert(a_Options.pluginFiles) -- There is a list of files assert(a_Options.pluginFiles[1]) -- The list is not empty -- Store the options so that they can be retrieved later on: self.options = a_Options -- Add the hooks based on the options: self:addHooks(a_Options) -- Load and execute the scenario: if not(a_Options.scenarioFileName) then self.logger:warning("No scenario file was specified, testing only plugin initialization. Use \"-s <filename>\" to specify a scenario file to execute.") self:loadPluginFiles() self:initializePlugin() else local scenario = Scenario:new(a_Options.scenarioFileName, self.logger) scenario:execute(self) end end --- Splits the command string at spaces -- Returns an array-table of strings of the original command, just like Cuberite command processor works function Simulator:splitCommandString(a_Cmd) local res = {} for w in a_Cmd:gmatch("%S+") do table.insert(res, w) end return res end --- Returns the type of the object -- Takes into account the emulated class types as well as the basic Lua types function Simulator:typeOf(a_Object) -- Check params: assert(self) assert(getmetatable(self) == Simulator) local t = type(a_Object) if (t == "userdata") then -- Check whether the object is a Cuberite class instance: local mt = getmetatable(a_Object) if not(mt) then -- Basic Lua userdatum return "userdata" end if (rawget(mt.__index, "simulatorInternal_ClassName")) then -- Cuberite class instance return mt.__index.simulatorInternal_ClassName end return "userdata" elseif (t == "table") then -- Check whether the object is a Cuberite class: local mt = getmetatable(a_Object) if not(mt) then -- Basic Lua table: return "table" end local mtmt = mt.__index if not(mtmt) then -- Basic Lua table (with a metatable) return "table" end if (rawget(mtmt, "simulatorInternal_ClassName")) then -- Cuberite class instance return mtmt.simulatorInternal_ClassName end -- Basic Lua table: return "table" end return t end --- Creates a new Simulator object with default callbacks local function createSimulator(a_Options, a_Logger) -- Check params: assert(type(a_Options) == "table") assert(type(a_Logger) == "table") local res res = { -- Hooks that the simulator calls for various events -- Each member is a table of functions, the simulator calls each function consecutively hooks = { onBeginRound = {}, -- When a new callback request is picked from the queue onBeforeCallCallback = {}, -- Just before the plugin's code is called onAfterCallCallback = {}, -- Right after the plugin's code returns onEndRound = {}, -- After finishing processing the callback request onAddedRequest = {}, -- Aftera new callback request is added to the callback request queue onApiFunctionCall = {}, -- An API function is being called }, -- The sandbox in which the plugin's code will be executed. Filled with defaults for now: sandbox = { -- Default Lua libraries: io = { close = io.close, flush = io.flush, input = io.input, lines = function(a_FileName, ...) -- Handles both io.lines("filename") and fileobj:lines(), need to distinguish: if (type(a_FileName) == "string") then a_FileName = res:redirectPath(a_FileName) end return io.lines(a_FileName, ...) end, open = function(a_FileName, ...) a_FileName = res:redirectPath(a_FileName) return io.open(a_FileName, ...) end, output = io.output, popen = io.popen, read = io.read, tmpfile = io.tmpfile, type = io.type, write = io.write, }, debug = debug, math = math, os = { clock = os.clock, date = os.date, difftime = os.difftime, execute = os.execute, exit = function(...) res.logger:error(2, "The os.exit() function should never be used in a Cuberite plugin!") end, getenv = os.getenv, remove = function(a_FileName, ...) return os.remove(res:redirectPath(a_FileName), ...) end, rename = function(a_SrcFileName, a_DstFileName, ...) return os.rename(res:redirectPath(a_SrcFileName), res:redirectPath(a_DstFileName), ...) end, setlocale = os.setlocale, time = os.time, tmpname = os.tmpname, }, string = string, table = table, -- Default Lua globals: assert = assert, collectgarbage = collectgarbage, dofile = function (a_FileName) return res:dofile(res:redirectPath(a_FileName)) end, error = error, getfenv = getfenv, getmetatable = getmetatable, ipairs = ipairs, load = load, loadfile = function(a_FileName) return res:loadfile(res:redirectPath(a_FileName)) end, loadstring = function(a_String) return res:loadstring(a_String) end, next = next, pairs = pairs, pcall = pcall, print = print, rawequal = rawequal, rawget = rawget, rawset = rawset, select = select, setfenv = setfenv, setmetatable = setmetatable, tonumber = tonumber, tostring = tostring, type = type, unpack = unpack, xpcall = xpcall, _VERSION = _VERSION, -- Indication about the simulator: IsPluginCheckerSimulator = true, PluginCheckerSimulatorVersion = 1, }, -- Enums extracted from the injected API -- Dictionary-table of "cClass#eEnum" -> { {Name = "ValueName1"}, {Name = "ValueName2"}, ... } -- The global enums have a key "eEnum" enums = {}, -- The hooks that the plugin has registered -- A dictionary of HookType -> { callback1, callback2, ... } registeredHooks = {}, -- The command handlers registered by the plugin -- A dictionary of Command -> { permission = <>, callback = <>, helpString = <> } registeredCommandHandlers = {}, -- The console command handlers registered by the plugin -- A dictionary of Command -> { callback = <>, helpString = <> } registeredConsoleCommandHandlers = {}, -- The webtabs registered via cWebAdmin:AddWebTab() or cPluginLua:AddWebTab() -- A dictionary of UrlPart -> { title = <>, callback = <> } registeredWebTabs = {}, -- The FIFO of requests for calling back -- Array of { Function = <fn>, ParamTypes = { <ParamTypes> }, ParamValues = { <OptionalParamValues> }, Notes = <optional-string> } -- ParamTypes is an array of strings describing the param types -- Param values is an optional array of param values to use. If present, ParamTypes is ignored -- Notes is a description for logging purposes -- Has an additional count in "n" for easy access callbackRequests = { n = 0, }, -- Values used for synthesizing semi-random API return values: testStringIndex = 1, testNumber = 1, -- Store the options so that they may be retrieved later on: options = a_Options, -- Store the logger for later use: logger = a_Logger, -- A dictionary of file / folder redirections. Maps the original path to the new path. redirects = {}, -- State manipulated through scenarios: worlds = {}, players = {}, } res.sandbox._G = res.sandbox setmetatable(res, Simulator) return res end return { create = createSimulator, }
unlicense
openwayne/chaos_theory
mods/worldedit/serialization.lua
10
8359
--- Schematic serialization and deserialiation. -- @module worldedit.serialization worldedit.LATEST_SERIALIZATION_VERSION = 5 local LATEST_SERIALIZATION_HEADER = worldedit.LATEST_SERIALIZATION_VERSION .. ":" --[[ Serialization version history: 1: Original format. Serialized Lua table with a weird linked format... 2: Position and node seperated into sub-tables in fields `1` and `2`. 3: List of nodes, one per line, with fields seperated by spaces. Format: <X> <Y> <Z> <Name> <Param1> <Param2> 4: Serialized Lua table containing a list of nodes with `x`, `y`, `z`, `name`, `param1`, `param2`, and `meta` fields. 5: Added header and made `param1`, `param2`, and `meta` fields optional. Header format: <Version>,<ExtraHeaderField1>,...:<Content> --]] --- Reads the header of serialized data. -- @param value Serialized WorldEdit data. -- @return The version as a positive natural number, or 0 for unknown versions. -- @return Extra header fields as a list of strings, or nil if not supported. -- @return Content (data after header). function worldedit.read_header(value) if value:find("^[0-9]+[%-:]") then local header_end = value:find(":", 1, true) local header = value:sub(1, header_end - 1):split(",") local version = tonumber(header[1]) table.remove(header, 1) local content = value:sub(header_end + 1) return version, header, content end -- Old versions that didn't include a header with a version number if value:find("([+-]?%d+)%s+([+-]?%d+)%s+([+-]?%d+)") and not value:find("%{") then -- List format return 3, nil, value elseif value:find("^[^\"']+%{%d+%}") then if value:find("%[\"meta\"%]") then -- Meta flat table format return 2, nil, value end return 1, nil, value -- Flat table format elseif value:find("%{") then -- Raw nested table format return 4, nil, value end return nil end --- Converts the region defined by positions `pos1` and `pos2` -- into a single string. -- @return The serialized data. -- @return The number of nodes serialized. function worldedit.serialize(pos1, pos2) pos1, pos2 = worldedit.sort_pos(pos1, pos2) worldedit.keep_loaded(pos1, pos2) local pos = {x=pos1.x, y=0, z=0} local count = 0 local result = {} local get_node, get_meta = minetest.get_node, minetest.get_meta while pos.x <= pos2.x do pos.y = pos1.y while pos.y <= pos2.y do pos.z = pos1.z while pos.z <= pos2.z do local node = get_node(pos) if node.name ~= "air" and node.name ~= "ignore" then count = count + 1 local meta = get_meta(pos):to_table() local meta_empty = true -- Convert metadata item stacks to item strings for name, inventory in pairs(meta.inventory) do for index, stack in ipairs(inventory) do meta_empty = false inventory[index] = stack.to_string and stack:to_string() or stack end end for k in pairs(meta) do if k ~= "inventory" then meta_empty = false break end end result[count] = { x = pos.x - pos1.x, y = pos.y - pos1.y, z = pos.z - pos1.z, name = node.name, param1 = node.param1 ~= 0 and node.param1 or nil, param2 = node.param2 ~= 0 and node.param2 or nil, meta = not meta_empty and meta or nil, } end pos.z = pos.z + 1 end pos.y = pos.y + 1 end pos.x = pos.x + 1 end -- Serialize entries result = minetest.serialize(result) return LATEST_SERIALIZATION_HEADER .. result, count end --- Loads the schematic in `value` into a node list in the latest format. -- Contains code based on [table.save/table.load](http://lua-users.org/wiki/SaveTableToFile) -- by ChillCode, available under the MIT license. -- @return A node list in the latest format, or nil on failure. local function load_schematic(value) local version, header, content = worldedit.read_header(value) local nodes = {} if version == 1 or version == 2 then -- Original flat table format local tables = minetest.deserialize(content) if not tables then return nil end -- Transform the node table into an array of nodes for i = 1, #tables do for j, v in pairs(tables[i]) do if type(v) == "table" then tables[i][j] = tables[v[1]] end end end nodes = tables[1] if version == 1 then --original flat table format for i, entry in ipairs(nodes) do local pos = entry[1] entry.x, entry.y, entry.z = pos.x, pos.y, pos.z entry[1] = nil local node = entry[2] entry.name, entry.param1, entry.param2 = node.name, node.param1, node.param2 entry[2] = nil end end elseif version == 3 then -- List format for x, y, z, name, param1, param2 in content:gmatch( "([+-]?%d+)%s+([+-]?%d+)%s+([+-]?%d+)%s+" .. "([^%s]+)%s+(%d+)%s+(%d+)[^\r\n]*[\r\n]*") do param1, param2 = tonumber(param1), tonumber(param2) table.insert(nodes, { x = tonumber(x), y = tonumber(y), z = tonumber(z), name = name, param1 = param1 ~= 0 and param1 or nil, param2 = param2 ~= 0 and param2 or nil, }) end elseif version == 4 or version == 5 then -- Nested table format if not jit then -- This is broken for larger tables in the current version of LuaJIT nodes = minetest.deserialize(content) else -- XXX: This is a filthy hack that works surprisingly well - in LuaJIT, `minetest.deserialize` will fail due to the register limit nodes = {} content = content:gsub("return%s*{", "", 1):gsub("}%s*$", "", 1) -- remove the starting and ending values to leave only the node data local escaped = content:gsub("\\\\", "@@"):gsub("\\\"", "@@"):gsub("(\"[^\"]*\")", function(s) return string.rep("@", #s) end) local startpos, startpos1, endpos = 1, 1 while true do -- go through each individual node entry (except the last) startpos, endpos = escaped:find("},%s*{", startpos) if not startpos then break end local current = content:sub(startpos1, startpos) local entry = minetest.deserialize("return " .. current) table.insert(nodes, entry) startpos, startpos1 = endpos, endpos end local entry = minetest.deserialize("return " .. content:sub(startpos1)) -- process the last entry table.insert(nodes, entry) end else return nil end return nodes end --- Determines the volume the nodes represented by string `value` would occupy -- if deserialized at `origin_pos`. -- @return Low corner position. -- @return High corner position. -- @return The number of nodes. function worldedit.allocate(origin_pos, value) local nodes = load_schematic(value) if not nodes then return nil end return worldedit.allocate_with_nodes(origin_pos, nodes) end -- Internal function worldedit.allocate_with_nodes(origin_pos, nodes) local huge = math.huge local pos1x, pos1y, pos1z = huge, huge, huge local pos2x, pos2y, pos2z = -huge, -huge, -huge local origin_x, origin_y, origin_z = origin_pos.x, origin_pos.y, origin_pos.z for i, entry in ipairs(nodes) do local x, y, z = origin_x + entry.x, origin_y + entry.y, origin_z + entry.z if x < pos1x then pos1x = x end if y < pos1y then pos1y = y end if z < pos1z then pos1z = z end if x > pos2x then pos2x = x end if y > pos2y then pos2y = y end if z > pos2z then pos2z = z end end local pos1 = {x=pos1x, y=pos1y, z=pos1z} local pos2 = {x=pos2x, y=pos2y, z=pos2z} return pos1, pos2, #nodes end --- Loads the nodes represented by string `value` at position `origin_pos`. -- @return The number of nodes deserialized. function worldedit.deserialize(origin_pos, value) local nodes = load_schematic(value) if not nodes then return nil end local pos1, pos2 = worldedit.allocate_with_nodes(origin_pos, nodes) worldedit.keep_loaded(pos1, pos2) local origin_x, origin_y, origin_z = origin_pos.x, origin_pos.y, origin_pos.z local count = 0 local add_node, get_meta = minetest.add_node, minetest.get_meta for i, entry in ipairs(nodes) do entry.x, entry.y, entry.z = origin_x + entry.x, origin_y + entry.y, origin_z + entry.z -- Entry acts as both position and node add_node(entry, entry) if entry.meta then get_meta(entry):from_table(entry.meta) end end return #nodes end
lgpl-2.1
Cyumus/Plugins
vault/items/sh_repairment.lua
1
1269
ITEM.name = "Toolkit" ITEM.desc = "A toolkit." ITEM.uniqueID = "toolkit" ITEM.model = Model("models/props_c17/SuitCase001a.mdl") ITEM.category = "Utils" ITEM.flag = "i" ITEM.price = 200 ITEM.functions = {} ITEM.functions.Open = { text = "Open", run = function(itemTable, client, data) if (CLIENT) then return end client:UpdateInv("food2_vegtableoil", 1, nil, true) client:UpdateInv("junk_cb", 3, nil, true) client:UpdateInv("hl2_m_wrench", 1, nil, true) client:UpdateInv("hl2_m_hammer", 1, nil, true) end } ITEM.functions.Use = { text = "Use", run = function(itemTable, client, data) if (CLIENT) then return end local raytrace = client:GetEyeTraceNoCursor() local box = raytrace.Entity if (box:IsValid() and box:GetClass() == "nut_vault") then nut.util.Notify("You use this toolkit and repair the vault.", client) timer.Simple(3, function() local luck = tonumber(math.floor(math.random(0, 3))) if luck >= 1 then nut.util.Notify("You repaired the vault successfully.", client) box.state = "closed" client:UpdateInv("toolkit", 1, nil, true) else nut.util.Notify("The toolkit brokes and you couldn't repair the vault.", client) end end) end end }
gpl-3.0
ld-test/dromozoa-commons
dromozoa/commons/base16.lua
3
3545
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-commons. -- -- dromozoa-commons 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. -- -- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>. local sequence_writer = require "dromozoa.commons.sequence_writer" local translate_range = require "dromozoa.commons.translate_range" local encoder_upper = {} local encoder_lower = {} local decoder = {} local n = ("0"):byte() for i = 0, 9 do local byte = i + n local char = string.char(byte) encoder_upper[i] = char encoder_lower[i] = char decoder[byte] = i end local n = ("A"):byte() - 10 for i = 10, 15 do local byte = i + n local char = string.char(byte) encoder_upper[i] = char decoder[byte] = i end local n = ("a"):byte() - 10 for i = 10, 15 do local byte = i + n local char = string.char(byte) encoder_lower[i] = char decoder[byte] = i end local function encode_impl(encoder, out, v) local b = v % 16 local a = (v - b) / 16 out:write(encoder[a], encoder[b]) end local function encode(encoder, out, s, min, max) for i = min + 3, max, 4 do local p = i - 3 local a, b, c, d = s:byte(p, i) encode_impl(encoder, out, a) encode_impl(encoder, out, b) encode_impl(encoder, out, c) encode_impl(encoder, out, d) end local i = max + 1 local p = i - (i - min) % 4 if p < i then local a, b, c = s:byte(p, max) if c then encode_impl(encoder, out, a) encode_impl(encoder, out, b) encode_impl(encoder, out, c) elseif b then encode_impl(encoder, out, a) encode_impl(encoder, out, b) else encode_impl(encoder, out, a) end end return out end local function decode(out, s, min, max) local n = max - min + 1 if n == 0 then return out elseif n % 2 ~= 0 then return nil, "length not divisible by 2" end for i = min + 3, max, 4 do local p = i - 3 if s:find("^%x%x%x%x", p) == nil then return nil, "decode error at position " .. p end local a, b, c, d = s:byte(p, i) out:write(string.char(decoder[a] * 16 + decoder[b], decoder[c] * 16 + decoder[d])) end if n % 4 == 2 then local p = max - 1 if s:find("^%x%x", p) == nil then return nil, "decode error at position " .. p end local a, b = s:byte(p, max) out:write(string.char(decoder[a] * 16 + decoder[b])) end return out end local class = {} function class.encode_upper(s, i, j) local s = tostring(s) return encode(encoder_upper, sequence_writer(), s, translate_range(#s, i, j)):concat() end function class.encode_lower(s, i, j) local s = tostring(s) return encode(encoder_lower, sequence_writer(), s, translate_range(#s, i, j)):concat() end function class.decode(s, i, j) local s = tostring(s) local result, message = decode(sequence_writer(), s, translate_range(#s, i, j)) if result == nil then return nil, message else return result:concat() end end class.encode = class.encode_upper return class
gpl-3.0
wagonrepairer/Zero-K
effects/gundam_dirt.lua
24
11215
-- dirt3 -- dirt -- dirt2 return { ["dirt3"] = { poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]], directional = true, emitrot = 90, emitrotspread = 25, emitvector = [[0, 0, 0]], gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]], numparticles = 5, particlelife = 8, particlelifespread = 40, particlesize = 20, particlesizespread = 0, particlespeed = 3, particlespeedspread = 10, pos = [[r-5 r5, r-25 r1, r-5 r5]], sizegrowth = 1.6, sizemod = 1.0, texture = [[dirt]], }, }, poof02 = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]], directional = true, emitrot = 45, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]], numparticles = 10, particlelife = 8, particlelifespread = 20, particlesize = 20, particlesizespread = 0, particlespeed = 2, particlespeedspread = 1, pos = [[r-50 r50, r-25 r1, r-50 r50]], sizegrowth = 1.6, sizemod = 1.0, texture = [[dirt]], }, }, wpoof01 = { class = [[CSimpleParticleSystem]], count = 10, water = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]], directional = true, emitrot = 45, emitrotspread = 25, emitvector = [[0, 0, 0]], gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]], numparticles = 4, particlelife = 6, particlelifespread = 40, particlesize = 20, particlesizespread = 0, particlespeed = 3, particlespeedspread = 10, pos = [[r-50 r50, r-25 r1, r-50 r50]], sizegrowth = 1.6, sizemod = 1.0, texture = [[dirtold]], }, }, wpoof02 = { class = [[CSimpleParticleSystem]], count = 10, water = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]], directional = true, emitrot = 45, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]], numparticles = 10, particlelife = 4, particlelifespread = 20, particlesize = 20, particlesizespread = 0, particlespeed = 2, particlespeedspread = 1, pos = [[r-50 r50, r-25 r1, r-50 r50]], sizegrowth = 1.6, sizemod = 1.0, texture = [[dirtold]], }, }, }, ["dirt"] = { poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]], directional = true, emitrot = 90, emitrotspread = 25, emitvector = [[0, 0, 0]], gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]], numparticles = 5, particlelife = 4, particlelifespread = 40, particlesize = 10, particlesizespread = 0, particlespeed = 3, particlespeedspread = 10, pos = [[r-1 r1, r-1 r1, r-1 r1]], sizegrowth = 0.8, sizemod = 1.0, texture = [[dirt]], }, }, poof02 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]], directional = true, emitrot = 90, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]], numparticles = 10, particlelife = 4, particlelifespread = 20, particlesize = 10, particlesizespread = 0, particlespeed = 2, particlespeedspread = 1, pos = [[r-1 r1, r-1 r1, r-1 r1]], sizegrowth = 0.8, sizemod = 1.0, texture = [[dirt]], }, }, wpoof01 = { class = [[CSimpleParticleSystem]], count = 1, water = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.2 0.2 0.4 0.2 0 0 0 0.0]], directional = true, emitrot = 25, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[r-0.01 r0.01, -0.18 r0.05, r-0.01 r0.01]], numparticles = 5, particlelife = 10, particlelifespread = 20, particlesize = 20, particlesizespread = 0, particlespeed = 2, particlespeedspread = 0.5, pos = [[r-1 r1, r-1 r1, r-1 r1]], sizegrowth = 0.6, sizemod = 1.0, texture = [[debris2]], }, }, wpoof02 = { class = [[CSimpleParticleSystem]], count = 1, water = true, properties = { airdrag = 0.9, alwaysvisible = false, colormap = [[0.2 0.2 0.4 0.05 0 0 0 0.0]], directional = true, emitrot = 90, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]], numparticles = 10, particlelife = 2, particlelifespread = 20, particlesize = 10, particlesizespread = 0, particlespeed = 1.8, particlespeedspread = 1, pos = [[r-1 r1, r-1 r1, r-1 r1]], sizegrowth = 0.8, sizemod = 1.0, texture = [[dirtplosion2]], }, }, }, ["dirt2"] = { poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]], directional = true, emitrot = 90, emitrotspread = 25, emitvector = [[0, 0, 0]], gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]], numparticles = 5, particlelife = 4, particlelifespread = 40, particlesize = 3, particlesizespread = 0, particlespeed = 1, particlespeedspread = 3, pos = [[r-50 r5, r-25 r1, r-50 r50]], sizegrowth = 0.2, sizemod = 1.0, texture = [[dirt]], }, }, poof02 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]], directional = true, emitrot = 45, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]], numparticles = 10, particlelife = 4, particlelifespread = 20, particlesize = 3, particlesizespread = 0, particlespeed = 0.6, particlespeedspread = 0.3, pos = [[r-50 r50, r-25 r1, r-50 r50]], sizegrowth = 0.2, sizemod = 1.0, texture = [[dirt]], }, }, wpoof01 = { class = [[CSimpleParticleSystem]], count = 1, water = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]], directional = true, emitrot = 45, emitrotspread = 25, emitvector = [[0, 0, 0]], gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]], numparticles = 4, particlelife = 3, particlelifespread = 40, particlesize = 3, particlesizespread = 0, particlespeed = 1, particlespeedspread = 3, pos = [[r-50 r50, r-25 r1, r-50 r50]], sizegrowth = 0.2, sizemod = 1.0, texture = [[dirtold]], }, }, wpoof02 = { class = [[CSimpleParticleSystem]], count = 1, water = true, properties = { airdrag = 1.0, alwaysvisible = false, colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]], directional = true, emitrot = 45, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]], numparticles = 10, particlelife = 2, particlelifespread = 20, particlesize = 3, particlesizespread = 0, particlespeed = 0.6, particlespeedspread = 0.3, pos = [[r-50 r50, r-25 r1, r-50 r50]], sizegrowth = 0.2, sizemod = 1.0, texture = [[dirtold]], }, }, }, }
gpl-2.0
xFleury/crawl-0.13.0-fairplay
source/dat/dlua/layout/hyper_decor.lua
1
4755
------------------------------------------------------------------------------ -- v_decor.lua: -- -- Functions that handle decorating walls, doors, and other points of interest ------------------------------------------------------------------------------ hyper.decor = {} ------------------------------------------------------------------------------ -- Decorator functions -- -- These callbacks decorate walls specifically where rooms join together. -- They mainly paint doors and windows, but sometimes open space. -- Paints all connecting points with floor to make completely open rooms function hyper.rooms.decorate_walls_open(state, connections, door_required) for i, door in ipairs(connections) do dgn.grid(door.grid_pos.x,door.grid_pos.y, "floor") end end -- Opens walls randomly according to a chance which can be modified by setting open_wall_chance on the generator function hyper.rooms.decorate_walls_partially_open(state, connections, door_required) -- Start by opening a single wall if we definitely need one if door_required then door = connections[crawl.random2(#connections)+1] end local door_chance = state.room.generator_used.open_wall_chance or 50 for i, door in ipairs(connections) do if crawl.x_chance_in_y(door_chance,100) then dgn.grid(door.grid_pos.x,door.grid_pos.y, "floor") end end end function hyper.rooms.decorate_walls(state, connections, door_required, has_windows, floors_instead) -- TODO: There is a slight edge case that can produce broken layouts. Where a room manages to place -- in such a way that the origin wall intersects with a second room, we might end up placing doors -- on that room instead and not the origin. Technically even this shouldn't matter because the -- second room should already be correctly connected to everything else, but I'm sure there is some -- situation where this could go wrong. What we should really do is divide the walls up by which -- room they attach to, rather than their normal; this means we can force door_required for -- definite on the origin wall. It will also make it easy to e.g. pick and choose how we decorate -- based on which room we're attaching to, rather than having to iterate through all the connections, -- and it solves the problem in Dis layouts where we wanted to choose a decorator for the whole -- outside room, not per wall. local have_door = true if not door_required then have_door = crawl.x_chance_in_y(5,6) end if have_door then -- TODO: Following was initially for Snake bubbles. But perhaps in V we could occasionally use floor or open_door. local door_feature = "closed_door" if floors_instead == true then door_feature = "floor" end -- TODO: Raise or lower the possible number of doors depending on how many connections we actually have local num_doors = math.abs(crawl.random2avg(9,4)-4)+1 -- Should tend towards 1 but rarely can be up to 5 for n=1,num_doors,1 do -- This could pick a door we've already picked; doesn't matter, this just makes more doors even slightly -- less likely local door = connections[crawl.random2(#connections)+1] if door ~= nil then dgn.grid(door.grid_pos.x,door.grid_pos.y, door_feature) door.is_door = true end end end -- Optionally place windows if has_windows == false or state.room.no_windows or state.options.no_windows or not crawl.one_chance_in(5) then return end -- Choose feature for window -- TODO: Pick other features in way that's similarly overrideable at multiple levels local window_feature = "clear_stone_wall" if state.options.layout_window_type ~= nil then window_feature = state.options.layout_window_type end if state.room.generator_used.window_type ~= nil then window_feature = state.room.generator_used.window_type end if state.window_type ~= nil then window_feature = state.window_type end local num_windows = math.abs(crawl.random2avg(5,3)-2)+2 -- Should tend towards 2 but rarely can be up to 4 for n=1,num_windows,1 do -- This could pick a door we've already picked; doesn't matter, this just makes more doors even slightly less likelier local door = connections[crawl.random2(#connections)+1] if door ~= nil and not door.is_door then dgn.grid(door.grid_pos.x,door.grid_pos.y, window_feature) door.is_window = true end end end ------------------------------------------------------------------------------ -- Decor rooms -- -- These rooms are designed to be placed inside other rooms to decorate them, -- sometimes in open space. -- function hyper.decor.phase_pattern(room,options,gen) -- local pattern = "x." -- end
gpl-2.0
shingenko/darkstar
scripts/globals/spells/victory_march.lua
18
1419
----------------------------------------- -- Spell: Victory March -- Gives party members Haste ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 43; if (sLvl+iLvl > 300) then power = power + math.floor((sLvl+iLvl-300) / 7); end if (power >= 96) then power = 96; end local iBoost = caster:getMod(MOD_MARCH_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost*16; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MARCH,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(75); end return EFFECT_MARCH; end;
gpl-3.0
shingenko/darkstar
scripts/globals/weaponskills/blast_shot.lua
30
1320
----------------------------------- -- Blast Shot -- Marksmanship weapon skill -- Skill Level: 200 -- Delivers a melee-distance ranged attack. params.accuracy varies with TP. -- Aligned with the Snow Gorget & Light Gorget. -- Aligned with the Snow Belt & Light Belt. -- Element: None -- Modifiers: AGI:30% -- 100%TP 200%TP 300%TP -- 2.00 2.00 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 2; params.ftp200 = 2; params.ftp300 = 2; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.agi_wsc = 0.7; end local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
openwayne/chaos_theory
mods/animalmaterials/cooking/init.lua
1
3667
--------------------------------------------------------- --Cooking Support, added by Mr Elmux -- You may use modify or do nearly anything except removing this Copyright hint ----------------------------------------------------------- local version = "0.1.1" core.log("action","MOD: Loading cooking (by Mr Elmux) ...") core.register_craftitem("cooking:meat_cooked", { description = "Cooked Meat", image = "cooking_cooked_meat.png", on_use = core.item_eat(6), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:meat_pork_cooked", { description = "Cooked Pork Meat", image = "cooking_cooked_meat.png", on_use = core.item_eat(6), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:meat_chicken_cooked", { description = "Cooked Chicken", image = "cooking_cooked_meat.png", on_use = core.item_eat(6), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:meat_beef_cooked", { description = "Cooked Beef", image = "cooking_cooked_meat.png", on_use = core.item_eat(6), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:meat_undead_cooked", { description = "Cooked Meat (Now Dead)", image = "cooking_cooked_meat.png", on_use = core.item_eat(-2), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:meat_venison_cooked", { description = "Cooked Venison Meat", image = "cooking_cooked_meat.png", on_use = core.item_eat(6), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:meat_toxic_cooked", { description = "Cooked Toxic Meat", image = "cooking_cooked_meat.png", on_use = core.item_eat(-5), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:fish_bluewhite_cooked", { description = "Cooked Bluewhite Meat", image = "cooking_cooked_meat.png", on_use = core.item_eat(6), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:fish_clownfish_cooked", { description = "Cooked Meat", image = "cooking_cooked_meat.png", on_use = core.item_eat(6), groups = { meat=1 , eatable=1}, stack_max = 25 }) core.register_craftitem("cooking:pork_cooked", { description = "Cooked Porkchop", inventory_image = "cooking_pork_cooked.png", on_use = core.item_eat(8), }) core.register_craft({ type= "cooking", recipe = "animalmaterials:meat_raw", output = "cooking:meat_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:meat_pork", output = "cooking:meat_pork_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:meat_chicken", output = "cooking:meat_chicken_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:meat_beef", output = "cooking:meat_beef_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:meat_undead", output = "cooking:meat_undead_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:meat_venison", output = "cooking:meat_venison_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:meat_toxic", output = "cooking:meat_toxic_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:fish_bluewhite", output = "cooking:fish_bluewhite_cooked", }) core.register_craft({ type= "cooking", recipe = "animalmaterials:fish_clownfish", output = "cooking:fish_clownfish_cooked", }) core.register_craft({ type = "cooking", output = "cooking:pork_cooked", recipe = "animalmaterials:pork_raw", cooktime = 5, }) core.log("action","MOD: cooking (by Mr Elmux) version .. " .. version .. " loaded.")
lgpl-2.1
shadobaker/TeleBeyond
plugins/chat.lua
7
2910
local function run(msg) if msg.text == "hi" then return "Hello\n"..msg.from.first_name end if msg.text == "Hi" then return "Hello\n"..msg.from.first_name end if msg.text == "Hello" then return "Hi\n"..msg.from.first_name end if msg.text == "hello" then return "Hi\n"..msg.from.first_name end if msg.text == "slm" then return "سلام\n"..msg.from.first_name end if msg.text == "Slm" then return "سلام\n"..msg.from.first_name end if msg.text == "salam" then return "سلام\n"..msg.from.first_name end if msg.text == "Salam" then return "سلام\n"..msg.from.first_name end if msg.text == "خوبی" then return "فدات تو خوبی؟" end if msg.text == "چه خبر" then return "سلامتی خبری نیس" end if msg.text == "چخبر" then return "سلامتی خبری نیس" end if msg.text == "mrhalix" then return "با بابا امینم چکار داری؟" end if msg.text == "Mrhalix" then return "با بابا امینم چکار داری؟" end if msg.text == "سلید" then return "مای فادِر بیا کارت دارن" end if msg.text == "سعید" then return "مای فادِر بیا کارت دارن" end if msg.text == "ممشوتک" then return "نگاییدم" end if msg.text == "mamshotak" then return "ممه هاش تکه😂" end if msg.text == "Mamshotak" then return "ممه هاش تکه😂" end if msg.text == "نوا" then return "چس اسپمر نگاییدم" end if msg.text == "نووا" then return "چس اسپمر نگاییدم" end if msg.text == "nova" then return "چس اسپمر نگاییدم" end if msg.text == "Nova" then return "چس اسپمر نگاییدم" end if msg.text == "امبرلا" then return "اسم اصلیش چسبرلاست" end if msg.text == "telebd" or msg.text == "Telebd" then return "بلی?" end if msg.text == "bot" then return "هوم؟" end if msg.text == "xy" then return "😐چخه" end if msg.text == "Xy" then return "😐چخه" end if msg.text == "؟" then return ":|" end if msg.text == "bye" then return "Bye\n"..msg.from.first_name end if msg.text == "Bye" then return "Bye\n"..msg.from.first_name end if msg.text == "بای" then return "خدافظ\n"..msg.from.first_name end if msg.text == "سلام" and is_sudo(msg) then return "😐✋سلام مای فادِر" else return "😐✋سلام\n"..msg.from.first_name end end return { description = "Chat With Robot Server", usage = "chat with robot", patterns = { "^[Hh]i$", "^[Hh]ello$", "^[Xx]y$", "^ممشوتک$", "^نوا$", "^نووا$", "^بای$", "^سلام$", "^خوبی$", "^سعید$", "^سلید$", "^چه خبر$", "^چخبر$", "^[Tt]elebd$", "^[Mm]rhalix$", "^[Mm]amshotak$", "^[Nn]ova$", "^[Bb]ot$", "^امبرلا$", "^[Bb]ye$", "^؟$", "^[Ss]alam$", }, run = run, --privileged = true, pre_process = pre_process }
gpl-2.0
wagonrepairer/Zero-K
LuaRules/Gadgets/exp_no_air_nuke.lua
17
1024
-- $Id: exp_no_air_nuke.lua 3171 2008-11-06 09:06:29Z det $ function gadget:GetInfo() return { name = "NoAirNuke", desc = "Disables the custom nuke effect, if the nuke is shoot in the air.", author = "jK", date = "Dec, 2007", license = "GNU GPL, v2 or later", layer = 0, enabled = true } end local GetGroundHeight = Spring.GetGroundHeight local nux = {} if (not gadgetHandler:IsSyncedCode()) then return false end local wantedList = {} --// find nukes for i=1,#WeaponDefs do local wd = WeaponDefs[i] --note that area of effect is radius, not diameter here! if (wd.damageAreaOfEffect >= 300 and wd.targetable) then nux[wd.id] = true wantedList[#wantedList + 1] = wd.id Script.SetWatchWeapon(wd.id, true) end end function gadget:Explosion_GetWantedWeaponDef() return wantedList end function gadget:Explosion(weaponID, px, py, pz, ownerID) if (nux[weaponID] and py-GetGroundHeight(px,pz)>100) then return true end return false end
gpl-2.0
fzimmermann89/texlive.js
texlive/texmf-dist/tex/luatex/lualibs/lualibs-lpeg.lua
4
38440
if not modules then modules = { } end modules ['l-lpeg'] = { version = 1.001, comment = "companion to luat-lib.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- we can get too many captures (e.g. on largexml files) which makes me wonder -- if P(foo)/"" can't be simplfied to N(foo) i.e. some direct instruction to the -- lpeg virtual machine to ignore it -- lpeg 12 vs lpeg 10: slower compilation, similar parsing speed (i need to check -- if i can use new features like capture / 2 and .B (at first sight the xml -- parser is some 5% slower) -- lpeg.P("abc") is faster than lpeg.P("a") * lpeg.P("b") * lpeg.P("c") -- a new lpeg fails on a #(1-P(":")) test and really needs a + P(-1) -- move utf -> l-unicode -- move string -> l-string or keep it here -- lpeg.B : backward without consumption -- lpeg.F = getmetatable(lpeg.P(1)).__len : forward without consumption lpeg = require("lpeg") -- does lpeg register itself global? local lpeg = lpeg -- The latest lpeg doesn't have print any more, and even the new ones are not -- available by default (only when debug mode is enabled), which is a pitty as -- as it helps nailing down bottlenecks. Performance seems comparable: some 10% -- slower pattern compilation, same parsing speed, although, -- -- local p = lpeg.C(lpeg.P(1)^0 * lpeg.P(-1)) -- local a = string.rep("123",100) -- lpeg.match(p,a) -- -- seems slower and is also still suboptimal (i.e. a match that runs from begin -- to end, one of the cases where string matchers win). if not lpeg.print then function lpeg.print(...) print(lpeg.pcode(...)) end end -- tracing (only used when we encounter a problem in integration of lpeg in luatex) -- some code will move to unicode and string -- local lpmatch = lpeg.match -- local lpprint = lpeg.print -- local lpp = lpeg.P -- local lpr = lpeg.R -- local lps = lpeg.S -- local lpc = lpeg.C -- local lpb = lpeg.B -- local lpv = lpeg.V -- local lpcf = lpeg.Cf -- local lpcb = lpeg.Cb -- local lpcg = lpeg.Cg -- local lpct = lpeg.Ct -- local lpcs = lpeg.Cs -- local lpcc = lpeg.Cc -- local lpcmt = lpeg.Cmt -- local lpcarg = lpeg.Carg -- function lpeg.match(l,...) print("LPEG MATCH") lpprint(l) return lpmatch(l,...) end -- function lpeg.P (l) local p = lpp (l) print("LPEG P =") lpprint(l) return p end -- function lpeg.R (l) local p = lpr (l) print("LPEG R =") lpprint(l) return p end -- function lpeg.S (l) local p = lps (l) print("LPEG S =") lpprint(l) return p end -- function lpeg.C (l) local p = lpc (l) print("LPEG C =") lpprint(l) return p end -- function lpeg.B (l) local p = lpb (l) print("LPEG B =") lpprint(l) return p end -- function lpeg.V (l) local p = lpv (l) print("LPEG V =") lpprint(l) return p end -- function lpeg.Cf (l) local p = lpcf (l) print("LPEG Cf =") lpprint(l) return p end -- function lpeg.Cb (l) local p = lpcb (l) print("LPEG Cb =") lpprint(l) return p end -- function lpeg.Cg (l) local p = lpcg (l) print("LPEG Cg =") lpprint(l) return p end -- function lpeg.Ct (l) local p = lpct (l) print("LPEG Ct =") lpprint(l) return p end -- function lpeg.Cs (l) local p = lpcs (l) print("LPEG Cs =") lpprint(l) return p end -- function lpeg.Cc (l) local p = lpcc (l) print("LPEG Cc =") lpprint(l) return p end -- function lpeg.Cmt (l) local p = lpcmt (l) print("LPEG Cmt =") lpprint(l) return p end -- function lpeg.Carg (l) local p = lpcarg(l) print("LPEG Carg =") lpprint(l) return p end local type, next, tostring = type, next, tostring local byte, char, gmatch, format = string.byte, string.char, string.gmatch, string.format ----- mod, div = math.mod, math.div local floor = math.floor local P, R, S, V, Ct, C, Cs, Cc, Cp, Cmt = lpeg.P, lpeg.R, lpeg.S, lpeg.V, lpeg.Ct, lpeg.C, lpeg.Cs, lpeg.Cc, lpeg.Cp, lpeg.Cmt local lpegtype, lpegmatch, lpegprint = lpeg.type, lpeg.match, lpeg.print -- let's start with an inspector: if setinspector then setinspector("lpeg",function(v) if lpegtype(v) then lpegprint(v) return true end end) end -- Beware, we predefine a bunch of patterns here and one reason for doing so -- is that we get consistent behaviour in some of the visualizers. lpeg.patterns = lpeg.patterns or { } -- so that we can share local patterns = lpeg.patterns local anything = P(1) local endofstring = P(-1) local alwaysmatched = P(true) patterns.anything = anything patterns.endofstring = endofstring patterns.beginofstring = alwaysmatched patterns.alwaysmatched = alwaysmatched local sign = S('+-') local zero = P('0') local digit = R('09') local digits = digit^1 local octdigit = R("07") local octdigits = octdigit^1 local lowercase = R("az") local uppercase = R("AZ") local underscore = P("_") local hexdigit = digit + lowercase + uppercase local hexdigits = hexdigit^1 local cr, lf, crlf = P("\r"), P("\n"), P("\r\n") ----- newline = crlf + S("\r\n") -- cr + lf local newline = P("\r") * (P("\n") + P(true)) + P("\n") -- P("\r")^-1 * P("\n")^-1 local escaped = P("\\") * anything local squote = P("'") local dquote = P('"') local space = P(" ") local period = P(".") local comma = P(",") local utfbom_32_be = P('\000\000\254\255') -- 00 00 FE FF local utfbom_32_le = P('\255\254\000\000') -- FF FE 00 00 local utfbom_16_be = P('\254\255') -- FE FF local utfbom_16_le = P('\255\254') -- FF FE local utfbom_8 = P('\239\187\191') -- EF BB BF local utfbom = utfbom_32_be + utfbom_32_le + utfbom_16_be + utfbom_16_le + utfbom_8 local utftype = utfbom_32_be * Cc("utf-32-be") + utfbom_32_le * Cc("utf-32-le") + utfbom_16_be * Cc("utf-16-be") + utfbom_16_le * Cc("utf-16-le") + utfbom_8 * Cc("utf-8") + alwaysmatched * Cc("utf-8") -- assume utf8 local utfstricttype = utfbom_32_be * Cc("utf-32-be") + utfbom_32_le * Cc("utf-32-le") + utfbom_16_be * Cc("utf-16-be") + utfbom_16_le * Cc("utf-16-le") + utfbom_8 * Cc("utf-8") local utfoffset = utfbom_32_be * Cc(4) + utfbom_32_le * Cc(4) + utfbom_16_be * Cc(2) + utfbom_16_le * Cc(2) + utfbom_8 * Cc(3) + Cc(0) local utf8next = R("\128\191") patterns.utfbom_32_be = utfbom_32_be patterns.utfbom_32_le = utfbom_32_le patterns.utfbom_16_be = utfbom_16_be patterns.utfbom_16_le = utfbom_16_le patterns.utfbom_8 = utfbom_8 patterns.utf_16_be_nl = P("\000\r\000\n") + P("\000\r") + P("\000\n") -- P("\000\r") * (P("\000\n") + P(true)) + P("\000\n") patterns.utf_16_le_nl = P("\r\000\n\000") + P("\r\000") + P("\n\000") -- P("\r\000") * (P("\n\000") + P(true)) + P("\n\000") patterns.utf_32_be_nl = P("\000\000\000\r\000\000\000\n") + P("\000\000\000\r") + P("\000\000\000\n") patterns.utf_32_le_nl = P("\r\000\000\000\n\000\000\000") + P("\r\000\000\000") + P("\n\000\000\000") patterns.utf8one = R("\000\127") patterns.utf8two = R("\194\223") * utf8next patterns.utf8three = R("\224\239") * utf8next * utf8next patterns.utf8four = R("\240\244") * utf8next * utf8next * utf8next patterns.utfbom = utfbom patterns.utftype = utftype patterns.utfstricttype = utfstricttype patterns.utfoffset = utfoffset local utf8char = patterns.utf8one + patterns.utf8two + patterns.utf8three + patterns.utf8four local validutf8char = utf8char^0 * endofstring * Cc(true) + Cc(false) local utf8character = P(1) * R("\128\191")^0 -- unchecked but fast patterns.utf8 = utf8char patterns.utf8char = utf8char patterns.utf8character = utf8character -- this one can be used in most cases so we might use that one patterns.validutf8 = validutf8char patterns.validutf8char = validutf8char local eol = S("\n\r") local spacer = S(" \t\f\v") -- + char(0xc2, 0xa0) if we want utf (cf mail roberto) local whitespace = eol + spacer local nonspacer = 1 - spacer local nonwhitespace = 1 - whitespace patterns.eol = eol patterns.spacer = spacer patterns.whitespace = whitespace patterns.nonspacer = nonspacer patterns.nonwhitespace = nonwhitespace local stripper = spacer ^0 * C((spacer ^0 * nonspacer ^1)^0) -- from example by roberto local fullstripper = whitespace^0 * C((whitespace^0 * nonwhitespace^1)^0) ----- collapser = Cs(spacer^0/"" * ((spacer^1 * endofstring / "") + (spacer^1/" ") + P(1))^0) local collapser = Cs(spacer^0/"" * nonspacer^0 * ((spacer^0/" " * nonspacer^1)^0)) local nospacer = Cs((whitespace^1/"" + nonwhitespace^1)^0) local b_collapser = Cs( whitespace^0 /"" * (nonwhitespace^1 + whitespace^1/" ")^0) local e_collapser = Cs((whitespace^1 * endofstring/"" + nonwhitespace^1 + whitespace^1/" ")^0) local m_collapser = Cs( (nonwhitespace^1 + whitespace^1/" ")^0) local b_stripper = Cs( spacer^0 /"" * (nonspacer^1 + spacer^1/" ")^0) local e_stripper = Cs((spacer^1 * endofstring/"" + nonspacer^1 + spacer^1/" ")^0) local m_stripper = Cs( (nonspacer^1 + spacer^1/" ")^0) patterns.stripper = stripper patterns.fullstripper = fullstripper patterns.collapser = collapser patterns.nospacer = nospacer patterns.b_collapser = b_collapser patterns.m_collapser = m_collapser patterns.e_collapser = e_collapser patterns.b_stripper = b_stripper patterns.m_stripper = m_stripper patterns.e_stripper = e_stripper patterns.lowercase = lowercase patterns.uppercase = uppercase patterns.letter = patterns.lowercase + patterns.uppercase patterns.space = space patterns.tab = P("\t") patterns.spaceortab = patterns.space + patterns.tab patterns.newline = newline patterns.emptyline = newline^1 patterns.equal = P("=") patterns.comma = comma patterns.commaspacer = comma * spacer^0 patterns.period = period patterns.colon = P(":") patterns.semicolon = P(";") patterns.underscore = underscore patterns.escaped = escaped patterns.squote = squote patterns.dquote = dquote patterns.nosquote = (escaped + (1-squote))^0 patterns.nodquote = (escaped + (1-dquote))^0 patterns.unsingle = (squote/"") * patterns.nosquote * (squote/"") -- will change to C in the middle patterns.undouble = (dquote/"") * patterns.nodquote * (dquote/"") -- will change to C in the middle patterns.unquoted = patterns.undouble + patterns.unsingle -- more often undouble patterns.unspacer = ((patterns.spacer^1)/"")^0 patterns.singlequoted = squote * patterns.nosquote * squote patterns.doublequoted = dquote * patterns.nodquote * dquote patterns.quoted = patterns.doublequoted + patterns.singlequoted patterns.digit = digit patterns.digits = digits patterns.octdigit = octdigit patterns.octdigits = octdigits patterns.hexdigit = hexdigit patterns.hexdigits = hexdigits patterns.sign = sign patterns.cardinal = digits patterns.integer = sign^-1 * digits patterns.unsigned = digit^0 * period * digits patterns.float = sign^-1 * patterns.unsigned patterns.cunsigned = digit^0 * comma * digits patterns.cpunsigned = digit^0 * (period + comma) * digits patterns.cfloat = sign^-1 * patterns.cunsigned patterns.cpfloat = sign^-1 * patterns.cpunsigned patterns.number = patterns.float + patterns.integer patterns.cnumber = patterns.cfloat + patterns.integer patterns.cpnumber = patterns.cpfloat + patterns.integer patterns.oct = zero * octdigits -- hm is this ok patterns.octal = patterns.oct patterns.HEX = zero * P("X") * (digit+uppercase)^1 patterns.hex = zero * P("x") * (digit+lowercase)^1 patterns.hexadecimal = zero * S("xX") * hexdigits patterns.hexafloat = sign^-1 * zero * S("xX") * (hexdigit^0 * period * hexdigits + hexdigits * period * hexdigit^0 + hexdigits) * (S("pP") * sign^-1 * hexdigits)^-1 patterns.decafloat = sign^-1 * (digit^0 * period * digits + digits * period * digit^0 + digits) * S("eE") * sign^-1 * digits patterns.propername = (uppercase + lowercase + underscore) * (uppercase + lowercase + underscore + digit)^0 * endofstring patterns.somecontent = (anything - newline - space)^1 -- (utf8char - newline - space)^1 patterns.beginline = #(1-newline) patterns.longtostring = Cs(whitespace^0/"" * ((patterns.quoted + nonwhitespace^1 + whitespace^1/"" * (endofstring + Cc(" ")))^0)) -- local function anywhere(pattern) -- slightly adapted from website -- return P { P(pattern) + 1 * V(1) } -- end local function anywhere(pattern) -- faster return (1-P(pattern))^0 * P(pattern) end lpeg.anywhere = anywhere function lpeg.instringchecker(p) p = anywhere(p) return function(str) return lpegmatch(p,str) and true or false end end -- function lpeg.splitter(pattern, action) -- return (((1-P(pattern))^1)/action+1)^0 -- end -- function lpeg.tsplitter(pattern, action) -- return Ct((((1-P(pattern))^1)/action+1)^0) -- end function lpeg.splitter(pattern, action) if action then return (((1-P(pattern))^1)/action+1)^0 else return (Cs((1-P(pattern))^1)+1)^0 end end function lpeg.tsplitter(pattern, action) if action then return Ct((((1-P(pattern))^1)/action+1)^0) else return Ct((Cs((1-P(pattern))^1)+1)^0) end end -- probleem: separator can be lpeg and that does not hash too well, but -- it's quite okay as the key is then not garbage collected local splitters_s, splitters_m, splitters_t = { }, { }, { } local function splitat(separator,single) local splitter = (single and splitters_s[separator]) or splitters_m[separator] if not splitter then separator = P(separator) local other = C((1 - separator)^0) if single then local any = anything splitter = other * (separator * C(any^0) + "") -- ? splitters_s[separator] = splitter else splitter = other * (separator * other)^0 splitters_m[separator] = splitter end end return splitter end local function tsplitat(separator) local splitter = splitters_t[separator] if not splitter then splitter = Ct(splitat(separator)) splitters_t[separator] = splitter end return splitter end lpeg.splitat = splitat lpeg.tsplitat = tsplitat function string.splitup(str,separator) if not separator then separator = "," end return lpegmatch(splitters_m[separator] or splitat(separator),str) end -- local p = splitat("->",false) print(lpegmatch(p,"oeps->what->more")) -- oeps what more -- local p = splitat("->",true) print(lpegmatch(p,"oeps->what->more")) -- oeps what->more -- local p = splitat("->",false) print(lpegmatch(p,"oeps")) -- oeps -- local p = splitat("->",true) print(lpegmatch(p,"oeps")) -- oeps local cache = { } function lpeg.split(separator,str) local c = cache[separator] if not c then c = tsplitat(separator) cache[separator] = c end return lpegmatch(c,str) end function string.split(str,separator) if separator then local c = cache[separator] if not c then c = tsplitat(separator) cache[separator] = c end return lpegmatch(c,str) else return { str } end end local spacing = patterns.spacer^0 * newline -- sort of strip local empty = spacing * Cc("") local nonempty = Cs((1-spacing)^1) * spacing^-1 local content = (empty + nonempty)^1 patterns.textline = content local linesplitter = tsplitat(newline) patterns.linesplitter = linesplitter function string.splitlines(str) return lpegmatch(linesplitter,str) end -- lpeg.splitters = cache -- no longer public local cache = { } function lpeg.checkedsplit(separator,str) local c = cache[separator] if not c then separator = P(separator) local other = C((1 - separator)^1) c = Ct(separator^0 * other * (separator^1 * other)^0) cache[separator] = c end return lpegmatch(c,str) end function string.checkedsplit(str,separator) local c = cache[separator] if not c then separator = P(separator) local other = C((1 - separator)^1) c = Ct(separator^0 * other * (separator^1 * other)^0) cache[separator] = c end return lpegmatch(c,str) end -- from roberto's site: local function f2(s) local c1, c2 = byte(s,1,2) return c1 * 64 + c2 - 12416 end local function f3(s) local c1, c2, c3 = byte(s,1,3) return (c1 * 64 + c2) * 64 + c3 - 925824 end local function f4(s) local c1, c2, c3, c4 = byte(s,1,4) return ((c1 * 64 + c2) * 64 + c3) * 64 + c4 - 63447168 end local utf8byte = patterns.utf8one/byte + patterns.utf8two/f2 + patterns.utf8three/f3 + patterns.utf8four/f4 patterns.utf8byte = utf8byte --~ local str = " a b c d " --~ local s = lpeg.stripper(lpeg.R("az")) print("["..lpegmatch(s,str).."]") --~ local s = lpeg.keeper(lpeg.R("az")) print("["..lpegmatch(s,str).."]") --~ local s = lpeg.stripper("ab") print("["..lpegmatch(s,str).."]") --~ local s = lpeg.keeper("ab") print("["..lpegmatch(s,str).."]") local cache = { } function lpeg.stripper(str) if type(str) == "string" then local s = cache[str] if not s then s = Cs(((S(str)^1)/"" + 1)^0) cache[str] = s end return s else return Cs(((str^1)/"" + 1)^0) end end local cache = { } function lpeg.keeper(str) if type(str) == "string" then local s = cache[str] if not s then s = Cs((((1-S(str))^1)/"" + 1)^0) cache[str] = s end return s else return Cs((((1-str)^1)/"" + 1)^0) end end function lpeg.frontstripper(str) -- or pattern (yet undocumented) return (P(str) + P(true)) * Cs(anything^0) end function lpeg.endstripper(str) -- or pattern (yet undocumented) return Cs((1 - P(str) * endofstring)^0) end -- Just for fun I looked at the used bytecode and -- p = (p and p + pp) or pp gets one more (testset). -- todo: cache when string function lpeg.replacer(one,two,makefunction,isutf) -- in principle we should sort the keys local pattern local u = isutf and utf8char or 1 if type(one) == "table" then local no = #one local p = P(false) if no == 0 then for k, v in next, one do p = p + P(k) / v end pattern = Cs((p + u)^0) elseif no == 1 then local o = one[1] one, two = P(o[1]), o[2] -- pattern = Cs(((1-one)^1 + one/two)^0) pattern = Cs((one/two + u)^0) else for i=1,no do local o = one[i] p = p + P(o[1]) / o[2] end pattern = Cs((p + u)^0) end else pattern = Cs((P(one)/(two or "") + u)^0) end if makefunction then return function(str) return lpegmatch(pattern,str) end else return pattern end end -- local pattern1 = P(1-P(pattern))^0 * P(pattern) : test for not nil -- local pattern2 = (P(pattern) * Cc(true) + P(1))^0 : test for true (could be faster, but not much) function lpeg.finder(lst,makefunction,isutf) -- beware: slower than find with 'patternless finds' local pattern if type(lst) == "table" then pattern = P(false) if #lst == 0 then for k, v in next, lst do pattern = pattern + P(k) -- ignore key, so we can use a replacer table end else for i=1,#lst do pattern = pattern + P(lst[i]) end end else pattern = P(lst) end if isutf then pattern = ((utf8char or 1)-pattern)^0 * pattern else pattern = (1-pattern)^0 * pattern end if makefunction then return function(str) return lpegmatch(pattern,str) end else return pattern end end -- print(lpeg.match(lpeg.replacer("e","a"),"test test")) -- print(lpeg.match(lpeg.replacer{{"e","a"}},"test test")) -- print(lpeg.match(lpeg.replacer({ e = "a", t = "x" }),"test test")) local splitters_f, splitters_s = { }, { } function lpeg.firstofsplit(separator) -- always return value local splitter = splitters_f[separator] if not splitter then local pattern = P(separator) splitter = C((1 - pattern)^0) splitters_f[separator] = splitter end return splitter end function lpeg.secondofsplit(separator) -- nil if not split local splitter = splitters_s[separator] if not splitter then local pattern = P(separator) splitter = (1 - pattern)^0 * pattern * C(anything^0) splitters_s[separator] = splitter end return splitter end local splitters_s, splitters_p = { }, { } function lpeg.beforesuffix(separator) -- nil if nothing but empty is ok local splitter = splitters_s[separator] if not splitter then local pattern = P(separator) splitter = C((1 - pattern)^0) * pattern * endofstring splitters_s[separator] = splitter end return splitter end function lpeg.afterprefix(separator) -- nil if nothing but empty is ok local splitter = splitters_p[separator] if not splitter then local pattern = P(separator) splitter = pattern * C(anything^0) splitters_p[separator] = splitter end return splitter end function lpeg.balancer(left,right) left, right = P(left), P(right) return P { left * ((1 - left - right) + V(1))^0 * right } end -- print(1,lpegmatch(lpeg.firstofsplit(":"),"bc:de")) -- print(2,lpegmatch(lpeg.firstofsplit(":"),":de")) -- empty -- print(3,lpegmatch(lpeg.firstofsplit(":"),"bc")) -- print(4,lpegmatch(lpeg.secondofsplit(":"),"bc:de")) -- print(5,lpegmatch(lpeg.secondofsplit(":"),"bc:")) -- empty -- print(6,lpegmatch(lpeg.secondofsplit(":",""),"bc")) -- print(7,lpegmatch(lpeg.secondofsplit(":"),"bc")) -- print(9,lpegmatch(lpeg.secondofsplit(":","123"),"bc")) -- this was slower but lpeg has been sped up in the meantime, so we no longer -- use this (still seems somewhat faster on long strings) -- -- local nany = utf8char/"" -- -- function lpeg.counter(pattern) -- pattern = Cs((P(pattern)/" " + nany)^0) -- return function(str) -- return #lpegmatch(pattern,str) -- end -- end function lpeg.counter(pattern,action) local n = 0 local pattern = (P(pattern) / function() n = n + 1 end + anything)^0 ----- pattern = (P(pattern) * (P(true) / function() n = n + 1 end) + anything)^0 ----- pattern = (P(pattern) * P(function() n = n + 1 end) + anything)^0 if action then return function(str) n = 0 ; lpegmatch(pattern,str) ; action(n) end else return function(str) n = 0 ; lpegmatch(pattern,str) ; return n end end end -- lpeg.print(lpeg.R("ab","cd","gh")) -- lpeg.print(lpeg.P("a","b","c")) -- lpeg.print(lpeg.S("a","b","c")) -- print(lpeg.count("äáàa",lpeg.P("á") + lpeg.P("à"))) -- print(lpeg.count("äáàa",lpeg.UP("áà"))) -- print(lpeg.count("äáàa",lpeg.US("àá"))) -- print(lpeg.count("äáàa",lpeg.UR("aá"))) -- print(lpeg.count("äáàa",lpeg.UR("àá"))) -- print(lpeg.count("äáàa",lpeg.UR(0x0000,0xFFFF))) function lpeg.is_lpeg(p) return p and lpegtype(p) == "pattern" end function lpeg.oneof(list,...) -- lpeg.oneof("elseif","else","if","then") -- assume proper order if type(list) ~= "table" then list = { list, ... } end -- table.sort(list) -- longest match first local p = P(list[1]) for l=2,#list do p = p + P(list[l]) end return p end -- For the moment here, but it might move to utilities. Beware, we need to -- have the longest keyword first, so 'aaa' comes beforte 'aa' which is why we -- loop back from the end cq. prepend. local sort = table.sort local function copyindexed(old) local new = { } for i=1,#old do new[i] = old end return new end local function sortedkeys(tab) local keys, s = { }, 0 for key,_ in next, tab do s = s + 1 keys[s] = key end sort(keys) return keys end function lpeg.append(list,pp,delayed,checked) local p = pp if #list > 0 then local keys = copyindexed(list) sort(keys) for i=#keys,1,-1 do local k = keys[i] if p then p = P(k) + p else p = P(k) end end elseif delayed then -- hm, it looks like the lpeg parser resolves anyway local keys = sortedkeys(list) if p then for i=1,#keys,1 do local k = keys[i] local v = list[k] p = P(k)/list + p end else for i=1,#keys do local k = keys[i] local v = list[k] if p then p = P(k) + p else p = P(k) end end if p then p = p / list end end elseif checked then -- problem: substitution gives a capture local keys = sortedkeys(list) for i=1,#keys do local k = keys[i] local v = list[k] if p then if k == v then p = P(k) + p else p = P(k)/v + p end else if k == v then p = P(k) else p = P(k)/v end end end else local keys = sortedkeys(list) for i=1,#keys do local k = keys[i] local v = list[k] if p then p = P(k)/v + p else p = P(k)/v end end end return p end -- inspect(lpeg.append({ a = "1", aa = "1", aaa = "1" } ,nil,true)) -- inspect(lpeg.append({ ["degree celsius"] = "1", celsius = "1", degree = "1" } ,nil,true)) -- function lpeg.exact_match(words,case_insensitive) -- local pattern = concat(words) -- if case_insensitive then -- local pattern = S(upper(characters)) + S(lower(characters)) -- local list = { } -- for i=1,#words do -- list[lower(words[i])] = true -- end -- return Cmt(pattern^1, function(_,i,s) -- return list[lower(s)] and i -- end) -- else -- local pattern = S(concat(words)) -- local list = { } -- for i=1,#words do -- list[words[i]] = true -- end -- return Cmt(pattern^1, function(_,i,s) -- return list[s] and i -- end) -- end -- end -- experiment: local p_false = P(false) local p_true = P(true) -- local function collapse(t,x) -- if type(t) ~= "table" then -- return t, x -- else -- local n = next(t) -- if n == nil then -- return t, x -- elseif next(t,n) == nil then -- -- one entry -- local k = n -- local v = t[k] -- if type(v) == "table" then -- return collapse(v,x..k) -- else -- return v, x .. k -- end -- else -- local tt = { } -- for k, v in next, t do -- local vv, kk = collapse(v,k) -- tt[kk] = vv -- end -- return tt, x -- end -- end -- end local lower = utf and utf.lower or string.lower local upper = utf and utf.upper or string.upper function lpeg.setutfcasers(l,u) lower = l or lower upper = u or upper end local function make1(t,rest) local p = p_false local keys = sortedkeys(t) for i=1,#keys do local k = keys[i] if k ~= "" then local v = t[k] if v == true then p = p + P(k) * p_true elseif v == false then -- can't happen else p = p + P(k) * make1(v,v[""]) end end end if rest then p = p + p_true end return p end local function make2(t,rest) -- only ascii local p = p_false local keys = sortedkeys(t) for i=1,#keys do local k = keys[i] if k ~= "" then local v = t[k] if v == true then p = p + (P(lower(k))+P(upper(k))) * p_true elseif v == false then -- can't happen else p = p + (P(lower(k))+P(upper(k))) * make2(v,v[""]) end end end if rest then p = p + p_true end return p end local function utfchartabletopattern(list,insensitive) -- goes to util-lpg local tree = { } local n = #list if n == 0 then for s in next, list do local t = tree local p, pk for c in gmatch(s,".") do if t == true then t = { [c] = true, [""] = true } p[pk] = t p = t t = false elseif t == false then t = { [c] = false } p[pk] = t p = t t = false else local tc = t[c] if not tc then tc = false t[c] = false end p = t t = tc end pk = c end if t == false then p[pk] = true elseif t == true then -- okay else t[""] = true end end else for i=1,n do local s = list[i] local t = tree local p, pk for c in gmatch(s,".") do if t == true then t = { [c] = true, [""] = true } p[pk] = t p = t t = false elseif t == false then t = { [c] = false } p[pk] = t p = t t = false else local tc = t[c] if not tc then tc = false t[c] = false end p = t t = tc end pk = c end if t == false then p[pk] = true elseif t == true then -- okay else t[""] = true end end end -- collapse(tree,"") -- needs testing, maybe optional, slightly faster because P("x")*P("X") seems slower than P"(xX") (why) -- inspect(tree) return (insensitive and make2 or make1)(tree) end lpeg.utfchartabletopattern = utfchartabletopattern function lpeg.utfreplacer(list,insensitive) local pattern = Cs((utfchartabletopattern(list,insensitive)/list + utf8character)^0) return function(str) return lpegmatch(pattern,str) or str end end -- local t = { "start", "stoep", "staart", "paard" } -- local p = lpeg.Cs((lpeg.utfchartabletopattern(t)/string.upper + 1)^1) -- local t = { "a", "abc", "ac", "abe", "abxyz", "xy", "bef","aa" } -- local p = lpeg.Cs((lpeg.utfchartabletopattern(t)/string.upper + 1)^1) -- inspect(lpegmatch(p,"a")=="A") -- inspect(lpegmatch(p,"aa")=="AA") -- inspect(lpegmatch(p,"aaaa")=="AAAA") -- inspect(lpegmatch(p,"ac")=="AC") -- inspect(lpegmatch(p,"bc")=="bc") -- inspect(lpegmatch(p,"zzbczz")=="zzbczz") -- inspect(lpegmatch(p,"zzabezz")=="zzABEzz") -- inspect(lpegmatch(p,"ab")=="Ab") -- inspect(lpegmatch(p,"abc")=="ABC") -- inspect(lpegmatch(p,"abe")=="ABE") -- inspect(lpegmatch(p,"xa")=="xA") -- inspect(lpegmatch(p,"bx")=="bx") -- inspect(lpegmatch(p,"bax")=="bAx") -- inspect(lpegmatch(p,"abxyz")=="ABXYZ") -- inspect(lpegmatch(p,"foobarbefcrap")=="foobArBEFcrAp") -- local t = { ["^"] = 1, ["^^"] = 2, ["^^^"] = 3, ["^^^^"] = 4 } -- local p = lpeg.Cs((lpeg.utfchartabletopattern(t)/t + 1)^1) -- inspect(lpegmatch(p," ^ ^^ ^^^ ^^^^ ^^^^^ ^^^^^^ ^^^^^^^ ")) -- local t = { ["^^"] = 2, ["^^^"] = 3, ["^^^^"] = 4 } -- local p = lpeg.Cs((lpeg.utfchartabletopattern(t)/t + 1)^1) -- inspect(lpegmatch(p," ^ ^^ ^^^ ^^^^ ^^^^^ ^^^^^^ ^^^^^^^ ")) -- lpeg.utfchartabletopattern { -- utfchar(0x00A0), -- nbsp -- utfchar(0x2000), -- enquad -- utfchar(0x2001), -- emquad -- utfchar(0x2002), -- enspace -- utfchar(0x2003), -- emspace -- utfchar(0x2004), -- threeperemspace -- utfchar(0x2005), -- fourperemspace -- utfchar(0x2006), -- sixperemspace -- utfchar(0x2007), -- figurespace -- utfchar(0x2008), -- punctuationspace -- utfchar(0x2009), -- breakablethinspace -- utfchar(0x200A), -- hairspace -- utfchar(0x200B), -- zerowidthspace -- utfchar(0x202F), -- narrownobreakspace -- utfchar(0x205F), -- math thinspace -- } -- a few handy ones: -- -- faster than find(str,"[\n\r]") when match and # > 7 and always faster when # > 3 patterns.containseol = lpeg.finder(eol) -- (1-eol)^0 * eol -- The next pattern^n variant is based on an approach suggested -- by Roberto: constructing a big repetition in chunks. -- -- Being sparse is not needed, and only complicate matters and -- the number of redundant entries is not that large. local function nextstep(n,step,result) local m = n % step -- mod(n,step) local d = floor(n/step) -- div(n,step) if d > 0 then local v = V(tostring(step)) local s = result.start for i=1,d do if s then s = v * s else s = v end end result.start = s end if step > 1 and result.start then local v = V(tostring(step/2)) result[tostring(step)] = v * v end if step > 0 then return nextstep(m,step/2,result) else return result end end function lpeg.times(pattern,n) return P(nextstep(n,2^16,{ "start", ["1"] = pattern })) end -- local p = lpeg.Cs((1 - lpeg.times(lpeg.P("AB"),25))^1) -- local s = "12" .. string.rep("AB",20) .. "34" .. string.rep("AB",30) .. "56" -- inspect(p) -- print(lpeg.match(p,s)) -- moved here (before util-str) do local trailingzeros = zero^0 * -digit -- suggested by Roberto local stripper = Cs(( digits * ( period * trailingzeros / "" + period * (digit - trailingzeros)^1 * (trailingzeros / "") ) + 1 )^0) lpeg.patterns.stripzeros = stripper -- multiple in string local nonzero = digit - zero local trailingzeros = zero^1 * endofstring local stripper = Cs( (1-period)^0 * ( period * trailingzeros/"" + period * (nonzero^1 + (trailingzeros/"") + zero^1)^0 + endofstring )) lpeg.patterns.stripzero = stripper -- slightly more efficient but expects a float ! -- local sample = "bla 11.00 bla 11 bla 0.1100 bla 1.00100 bla 0.00 bla 0.001 bla 1.1100 bla 0.100100100 bla 0.00100100100" -- collectgarbage("collect") -- str = string.rep(sample,10000) -- local ts = os.clock() -- lpegmatch(stripper,str) -- print(#str, os.clock()-ts, lpegmatch(stripper,sample)) end -- for practical reasons we keep this here: local byte_to_HEX = { } local byte_to_hex = { } local byte_to_dec = { } -- for md5 local hex_to_byte = { } for i=0,255 do local H = format("%02X",i) local h = format("%02x",i) local d = format("%03i",i) local c = char(i) byte_to_HEX[c] = H byte_to_hex[c] = h byte_to_dec[c] = d hex_to_byte[h] = c hex_to_byte[H] = c end local hextobyte = P(2)/hex_to_byte local bytetoHEX = P(1)/byte_to_HEX local bytetohex = P(1)/byte_to_hex local bytetodec = P(1)/byte_to_dec local hextobytes = Cs(hextobyte^0) local bytestoHEX = Cs(bytetoHEX^0) local bytestohex = Cs(bytetohex^0) local bytestodec = Cs(bytetodec^0) patterns.hextobyte = hextobyte patterns.bytetoHEX = bytetoHEX patterns.bytetohex = bytetohex patterns.bytetodec = bytetodec patterns.hextobytes = hextobytes patterns.bytestoHEX = bytestoHEX patterns.bytestohex = bytestohex patterns.bytestodec = bytestodec function string.toHEX(s) if not s or s == "" then return s else return lpegmatch(bytestoHEX,s) end end function string.tohex(s) if not s or s == "" then return s else return lpegmatch(bytestohex,s) end end function string.todec(s) if not s or s == "" then return s else return lpegmatch(bytestodec,s) end end function string.tobytes(s) if not s or s == "" then return s else return lpegmatch(hextobytes,s) end end -- local h = "ADFE0345" -- local b = lpegmatch(patterns.hextobytes,h) -- print(h,b,string.tohex(b),string.toHEX(b)) local patterns = { } -- can be made weak local function containsws(what) local p = patterns[what] if not p then local p1 = P(what) * (whitespace + endofstring) * Cc(true) local p2 = whitespace * P(p1) p = P(p1) + P(1-p2)^0 * p2 + Cc(false) patterns[what] = p end return p end lpeg.containsws = containsws function string.containsws(str,what) return lpegmatch(patterns[what] or containsws(what),str) end
gpl-2.0
shingenko/darkstar
scripts/globals/mobskills/Damnation_Dive.lua
18
1351
--------------------------------------------- -- Damnation Dive -- -- Description: Dives into a single target. Additional effect: Knockback + Stun -- Type: Physical -- Utsusemi/Blink absorb: 3 shadow -- Range: Melee -- Notes: Used instead of Gliding Spike by certain notorious monsters. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- --------------------------------------------------- -- onMobSkillCheck -- Check for Grah Family id 122,123,124 -- if not in Bird form, then ignore. --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if ((mob:getFamily() == 122 or mob:getFamily() == 123 or mob:getFamily() == 124) and mob:AnimationSub() ~= 3) then return 1; else return 0; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 3; local accmod = 1; local dmgmod = .8; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
ld-test/dromozoa-commons
test/test_base64.lua
3
1684
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-commons. -- -- dromozoa-commons 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. -- -- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>. local base64 = require "dromozoa.commons.base64" local function test(this, that) local code = base64.encode(this) assert(code == that) -- print(this, that) -- print(base64.decode(code)) assert(base64.decode(code) == this) end test("", "") test("f", "Zg==") test("fo", "Zm8=") test("foo", "Zm9v") test("foob", "Zm9vYg==") test("fooba", "Zm9vYmE=") test("foobar", "Zm9vYmFy") test("ABCDEFG", "QUJDREVGRw==") assert(not base64.decode("Zm9v====")) assert(not base64.decode("Zm9vZ===")) assert(not base64.decode("Zg=/")) assert(not base64.decode("Zg==Zg==")) assert(not base64.decode("Zm8=Zg==")) assert(not base64.decode("Zh==")) assert(not base64.decode("Zm9=")) assert(base64.encode_url("") == "") assert(base64.encode_url("f") == "Zg") assert(base64.encode_url("fo") == "Zm8") assert(base64.encode_url("foo") == "Zm9v") assert(base64.encode_url("\251") == "-w") assert(base64.encode_url("\252") == "_A")
gpl-3.0
Illarion-eV/Illarion-Content
lte/debuff_constitution.lua
5
1185
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") -- Long time effect (101) local M = {} function M.addEffect(theEffect, User) User:increaseAttrib("constitution", -2); end function M.callEffect(theEffect, User) return false; end function M.loadEffect(theEffect, User) User:increaseAttrib("constitution", -2); end function M.removeEffect (theEffect, User) common.InformNLS( User, "Deine Ausdauer kehrt zurück.", "Your constitution is back to normal.") User:increaseAttrib("constitution", 2); end return M
agpl-3.0
shingenko/darkstar
scripts/zones/Mount_Zhayolm/npcs/qm3.lua
16
1173
----------------------------------- -- Area: Mount Zhayolm -- NPC: ??? (Spawn Anantaboga(ZNM T2)) -- @pos -368 -13 366 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mount_Zhayolm/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(2587,1) and trade:getItemCount() == 1) then -- Trade Raw Buffalo player:tradeComplete(); SpawnMob(17027473,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); 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
shingenko/darkstar
scripts/zones/Western_Altepa_Desert/npcs/_3h7.lua
17
1890
----------------------------------- -- Area: Western Altepa Desert -- NPC: _3h7 (Emerald Column) -- Notes: Mechanism for Altepa Gate -- @pos -775 2 -460 125 ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Western_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local EmeraldID = npc:getID(); local Ruby = GetNPCByID(EmeraldID-2):getAnimation(); local Topaz = GetNPCByID(EmeraldID-1):getAnimation(); local Emerald = npc:getAnimation(); local Sapphire = GetNPCByID(EmeraldID+1):getAnimation(); if (Emerald ~= 8) then npc:setAnimation(8); GetNPCByID(EmeraldID-4):setAnimation(8); else player:messageSpecial(DOES_NOT_RESPOND); end if (Sapphire == 8 and Ruby == 8 and Topaz == 8) then local rand = math.random(15,30); local timeDoor = rand * 60; -- Add timer for the door GetNPCByID(EmeraldID-7):openDoor(timeDoor); -- Add same timer for the 4 center lights GetNPCByID(EmeraldID-6):openDoor(timeDoor); GetNPCByID(EmeraldID-5):openDoor(timeDoor); GetNPCByID(EmeraldID-4):openDoor(timeDoor); GetNPCByID(EmeraldID-3):openDoor(timeDoor); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
simon-wh/PAYDAY-2-BeardLib
Modules/Addons/InteractionsModule.lua
2
1104
InteractionsModule = InteractionsModule or BeardLib:ModuleClass("Interactions", ItemModuleBase) InteractionsModule.required_params = {} function InteractionsModule:AddInteractionsDataToTweak(i_self) for _, data in ipairs(self._config) do if data._meta == "interaction" then if i_self[data.id] then self:Err("Interaction with id '%s' already exists!", data.id) else data.text_id = data.text_id or ("hud_"..data.id) i_self[data.id] = table.merge(data.based_on and deep_clone(i_self[data.based_on] or {}) or {}, data.item or data) end end end end function InteractionsModule:RegisterHook() local first = BeardLib.Utils.XML:GetNode(self._config, "interaction") if first then if tweak_data and tweak_data.interaction then self:AddInteractionsDataToTweak(tweak_data.interaction) else Hooks:PostHook(InteractionTweakData, "init", self._mod.Name..'/'..first.id .. "AddInteractionData", ClassClbk(self, "AddInteractionsDataToTweak")) end end end
mit
shingenko/darkstar
scripts/zones/Al_Zahbi/npcs/Taten-Bilten.lua
19
1155
----------------------------------- -- Area: Al Zahbi -- NPC: Taten-Bilten -- Guild Merchant NPC: Clothcraft Guild -- @pos 71.598 -6.000 -56.930 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(60430,6,21,0)) then player:showText(npc,TATEN_BILTEN_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Illarion-eV/Illarion-Content
content/_gods/bragon.lua
3
1961
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local class = require('base.class') local baseelder = require("content._gods.baseelder") local common = require('base.common') local M = {} M.Bragon = class( baseelder.BaseElder, function(self, ...) self:_init(...) end ) function M.Bragon:_init(ordinal, elderOrdinal) baseelder.BaseElder._init(self, ordinal, elderOrdinal) -- call the base class constructor self.nameDe = "Brágon" self.nameEn = "Brágon" self.descriptionDe = "der Gott des Feuers" self.descriptionEn = "God of fire" self.devotionItems = { {id = 2553, number = 1}, -- pure fire {id = 2704, number = 1}, -- magical longsword {id = 2419, number = 1}, -- red priest robe } self.sacrificeItems = { -- array of tables defining groups of items for sacrificing { -- FIXME id_set = common.setFromList({ -- set of item IDs 2553, -- pure fire 2783, -- wand of fire }), minimal_quality = 0, -- int in 1..9 - if present, item quality has to be greater or equal minimal_durability = 0, -- int in 0..99 - if present, item durability has to be greater or equal value_multiplier = 1, -- float -- the monetary value gets multiplied by this }, } end return M
agpl-3.0
wagonrepairer/Zero-K
effects/gundam_unitrupture.lua
25
3297
-- unitrupture return { ["unitrupture"] = { dirtg = { class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.7, alwaysvisible = true, colormap = [[0.1 0.1 0.1 1.0 0.5 0.4 0.3 1.0 0 0 0 0.0]], directional = true, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 8, particlelife = 25, particlelifespread = 10, particlesize = 8, particlesizespread = 8, particlespeed = 1, particlespeedspread = 15, pos = [[r-1 r1, 1, r-1 r1]], sizegrowth = 1.2, sizemod = 1.0, texture = [[dirt]], useairlos = true, }, }, groundflash = { air = true, alwaysvisible = true, circlealpha = 0.6, circlegrowth = 6, flashalpha = 0.9, flashsize = 50, ground = true, ttl = 13, water = true, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, poof = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.5, alwaysvisible = true, colormap = [[1 1 1 0.01 0.9 0.8 0.7 0.01 0.9 0.5 0.2 0.01 0.5 0.1 0.1 0.01]], directional = true, emitrot = 5, emitrotspread = 1, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 2, particlelife = 10, particlelifespread = 5, particlesize = 10, particlesizespread = 2, particlespeed = 15, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 3, sizemod = 1, texture = [[flashside1]], useairlos = false, }, }, searingflame = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.8, colormap = [[1 1 1 0.01 0.9 0.5 0.4 0.04 0.9 0.4 0.1 0.01 0.5 0.1 0.1 0.01]], directional = true, emitrot = 45, emitrotspread = 32, emitvector = [[dir]], gravity = [[0, -0.01, 0]], numparticles = 8, particlelife = 10, particlelifespread = 5, particlesize = 20, particlesizespread = 0, particlespeed = 5, particlespeedspread = 5, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 0.5, texture = [[shot]], useairlos = false, }, }, }, }
gpl-2.0
shingenko/darkstar
scripts/globals/mobskills/Blade_Metsu.lua
18
1156
--------------------------------------------- -- Blade Metsu -- -- Description: Additional effect: Paralysis -- Hidden effect: temporarily enhances Subtle Blow effect. -- Type: Physical -- Range: Melee --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,3,3,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20; if (mob:getTP() == 300) then duration = 60; elseif (mob:getTP() >= 200) then duration = 40; end MobBuffMove(mob, EFFECT_SUBTLE_BLOW_PLUS, 10, 0, duration); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_PARALYSIS, 10, 0, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
ArcherSys/ArcherSys
Lua/lua/luarocks/fs/lua.lua
1
18172
--- Native Lua implementation of filesystem and platform abstractions, -- using LuaFileSystem, LZLib, MD5 and LuaCurl. module("luarocks.fs.lua", package.seeall) local fs = require("luarocks.fs") local cfg = require("luarocks.cfg") local dir = require("luarocks.dir") local util = require("luarocks.util") local socket_ok, http = pcall(require, "socket.http") local _, ftp = pcall(require, "socket.ftp") local zip_ok, lrzip = pcall(require, "luarocks.tools.zip") local unzip_ok, luazip = pcall(require, "zip"); _G.zip = nil local lfs_ok, lfs = pcall(require, "lfs") --local curl_ok, curl = pcall(require, "luacurl") local md5_ok, md5 = pcall(require, "md5") local posix_ok, posix = pcall(require, "posix") local tar = require("luarocks.tools.tar") local patch = require("luarocks.tools.patch") local dir_stack = {} math.randomseed(os.time()) dir_separator = "/" --- Quote argument for shell processing. -- Adds single quotes and escapes. -- @param arg string: Unquoted argument. -- @return string: Quoted argument. function Q(arg) assert(type(arg) == "string") -- FIXME Unix-specific return "'" .. arg:gsub("\\", "\\\\"):gsub("'", "'\\''") .. "'" end --- Test is file/dir is writable. -- Warning: testing if a file/dir is writable does not guarantee -- that it will remain writable and therefore it is no replacement -- for checking the result of subsequent operations. -- @param file string: filename to test -- @return boolean: true if file exists, false otherwise. function is_writable(file) assert(file) local result if fs.is_dir(file) then local file2 = file .. '/.tmpluarockstestwritable' local fh = io.open(file2, 'wb') result = fh ~= nil if fh then fh:close() end os.remove(file2) else local fh = io.open(file, 'rb+') result = fh ~= nil if fh then fh:close() end end return result end --- Create a temporary directory. -- @param name string: name pattern to use for avoiding conflicts -- when creating temporary directory. -- @return string or nil: name of temporary directory or nil on failure. function make_temp_dir(name) assert(type(name) == "string") name = name:gsub("\\", "/") local temp_dir = (os.getenv("TMP") or "/tmp") .. "/luarocks_" .. name:gsub(dir.separator, "_") .. "-" .. tostring(math.floor(math.random() * 10000)) if fs.make_dir(temp_dir) then return temp_dir else return nil end end --- Run the given command, quoting its arguments. -- The command is executed in the current directory in the dir stack. -- @param command string: The command to be executed. No quoting/escaping -- is applied. -- @param ... Strings containing additional arguments, which are quoted. -- @return boolean: true if command succeeds (status code 0), false -- otherwise. function execute(command, ...) assert(type(command) == "string") for _, arg in ipairs({...}) do assert(type(arg) == "string") command = command .. " " .. fs.Q(arg) end return fs.execute_string(command) end --- Check the MD5 checksum for a file. -- @param file string: The file to be checked. -- @param md5sum string: The string with the expected MD5 checksum. -- @return boolean: true if the MD5 checksum for 'file' equals 'md5sum', false if not -- or if it could not perform the check for any reason. function check_md5(file, md5sum) local computed = fs.get_md5(file) if not computed then return false end if computed:match("^"..md5sum) then return true else return false end end --------------------------------------------------------------------- -- LuaFileSystem functions --------------------------------------------------------------------- if lfs_ok then --- Run the given command. -- The command is executed in the current directory in the dir stack. -- @param cmd string: No quoting/escaping is applied to the command. -- @return boolean: true if command succeeds (status code 0), false -- otherwise. function execute_string(cmd) if os.execute(cmd) == 0 then return true else return false end end --- Obtain current directory. -- Uses the module's internal dir stack. -- @return string: the absolute pathname of the current directory. function current_dir() return lfs.currentdir() end --- Change the current directory. -- Uses the module's internal dir stack. This does not have exact -- semantics of chdir, as it does not handle errors the same way, -- but works well for our purposes for now. -- @param d string: The directory to switch to. function change_dir(d) table.insert(dir_stack, lfs.currentdir()) lfs.chdir(d) end --- Change directory to root. -- Allows leaving a directory (e.g. for deleting it) in -- a crossplatform way. function change_dir_to_root() table.insert(dir_stack, lfs.currentdir()) -- TODO Does this work on Windows? lfs.chdir("/") end --- Change working directory to the previous in the dir stack. -- @return true if a pop ocurred, false if the stack was empty. function pop_dir() local d = table.remove(dir_stack) if d then lfs.chdir(d) return true else return false end end --- Create a directory if it does not already exist. -- If any of the higher levels in the path name does not exist -- too, they are created as well. -- @param directory string: pathname of directory to create. -- @return boolean: true on success, false on failure. function make_dir(directory) assert(type(directory) == "string") directory = directory:gsub("\\", "/") local path = nil if directory:sub(2, 2) == ":" then path = directory:sub(1, 2) directory = directory:sub(4) else if directory:match("^/") then path = "" end end for d in directory:gmatch("([^"..dir.separator.."]+)"..dir.separator.."*") do path = path and path .. dir.separator .. d or d local mode = lfs.attributes(path, "mode") if not mode then if not lfs.mkdir(path) then return false end elseif mode ~= "directory" then return false end end return true end --- Remove a directory if it is empty. -- Does not return errors (for example, if directory is not empty or -- if already does not exist) -- @param d string: pathname of directory to remove. function remove_dir_if_empty(d) assert(d) lfs.rmdir(d) end --- Remove a directory if it is empty. -- Does not return errors (for example, if directory is not empty or -- if already does not exist) -- @param d string: pathname of directory to remove. function remove_dir_tree_if_empty(d) assert(d) for i=1,10 do lfs.rmdir(d) d = dir.dir_name(d) end end --- Copy a file. -- @param src string: Pathname of source -- @param dest string: Pathname of destination -- @return boolean or (boolean, string): true on success, false on failure, -- plus an error message. function copy(src, dest) assert(src and dest) local destmode = lfs.attributes(dest, "mode") if destmode == "directory" then dest = dir.path(dest, dir.base_name(src)) end local src_h, err = io.open(src, "rb") if not src_h then return nil, err end local dest_h, err = io.open(dest, "wb+") if not dest_h then src_h:close() return nil, err end while true do local block = src_h:read(8192) if not block then break end dest_h:write(block) end src_h:close() dest_h:close() return true end --- Implementation function for recursive copy of directory contents. -- @param src string: Pathname of source -- @param dest string: Pathname of destination -- @return boolean or (boolean, string): true on success, false on failure local function recursive_copy(src, dest) local srcmode = lfs.attributes(src, "mode") if srcmode == "file" then local ok = fs.copy(src, dest) if not ok then return false end elseif srcmode == "directory" then local subdir = dir.path(dest, dir.base_name(src)) fs.make_dir(subdir) for file in lfs.dir(src) do if file ~= "." and file ~= ".." then local ok = recursive_copy(dir.path(src, file), subdir) if not ok then return false end end end end return true end --- Recursively copy the contents of a directory. -- @param src string: Pathname of source -- @param dest string: Pathname of destination -- @return boolean or (boolean, string): true on success, false on failure, -- plus an error message. function copy_contents(src, dest) assert(src and dest) assert(lfs.attributes(src, "mode") == "directory") for file in lfs.dir(src) do if file ~= "." and file ~= ".." then local ok = recursive_copy(dir.path(src, file), dest) if not ok then return false, "Failed copying "..src.." to "..dest end end end return true end --- Implementation function for recursive removal of directories. -- @param src string: Pathname of source -- @param dest string: Pathname of destination -- @return boolean or (boolean, string): true on success, -- or nil and an error message on failure. local function recursive_delete(src) local srcmode = lfs.attributes(src, "mode") if srcmode == "file" then return os.remove(src) elseif srcmode == "directory" then for file in lfs.dir(src) do if file ~= "." and file ~= ".." then local ok, err = recursive_delete(dir.path(src, file)) if not ok then return nil, err end end end local ok, err = lfs.rmdir(src) if not ok then return nil, err end end return true end --- Delete a file or a directory and all its contents. -- For safety, this only accepts absolute paths. -- @param arg string: Pathname of source -- @return boolean: true on success, false on failure. function delete(arg) assert(arg) return recursive_delete(arg) or false end --- List the contents of a directory. -- @param at string or nil: directory to list (will be the current -- directory if none is given). -- @return table: an array of strings with the filenames representing -- the contents of a directory. function list_dir(at) assert(type(at) == "string" or not at) if not at then at = fs.current_dir() end if not fs.is_dir(at) then return {} end local result = {} for file in lfs.dir(at) do if file ~= "." and file ~= ".." then table.insert(result, file) end end return result end --- Implementation function for recursive find. -- @param cwd string: Current working directory in recursion. -- @param prefix string: Auxiliary prefix string to form pathname. -- @param result table: Array of strings where results are collected. local function recursive_find(cwd, prefix, result) for file in lfs.dir(cwd) do if file ~= "." and file ~= ".." then local item = prefix .. file table.insert(result, item) local pathname = dir.path(cwd, file) if lfs.attributes(pathname, "mode") == "directory" then recursive_find(pathname, item..dir_separator, result) end end end end --- Recursively scan the contents of a directory. -- @param at string or nil: directory to scan (will be the current -- directory if none is given). -- @return table: an array of strings with the filenames representing -- the contents of a directory. function find(at) assert(type(at) == "string" or not at) if not at then at = fs.current_dir() end if not fs.is_dir(at) then return {} end local result = {} recursive_find(at, "", result) return result end --- Test for existance of a file. -- @param file string: filename to test -- @return boolean: true if file exists, false otherwise. function exists(file) assert(file) return type(lfs.attributes(file)) == "table" end --- Test is pathname is a directory. -- @param file string: pathname to test -- @return boolean: true if it is a directory, false otherwise. function is_dir(file) assert(file) return lfs.attributes(file, "mode") == "directory" end --- Test is pathname is a regular file. -- @param file string: pathname to test -- @return boolean: true if it is a file, false otherwise. function is_file(file) assert(file) return lfs.attributes(file, "mode") == "file" end function set_time(file, time) return lfs.touch(file, time) end end --------------------------------------------------------------------- -- LuaZip functions --------------------------------------------------------------------- if zip_ok then function zip(zipfile, ...) return lrzip.zip(zipfile, ...) end end if unzip_ok then --- Uncompress files from a .zip archive. -- @param zipfile string: pathname of .zip archive to be extracted. -- @return boolean: true on success, false on failure. function unzip(zipfile) local zipfile, err = luazip.open(zipfile) if not zipfile then return nil, err end local files = zipfile:files() local file = files() repeat if file.filename:sub(#file.filename) == "/" then fs.make_dir(dir.path(fs.current_dir(), file.filename)) else local rf, err = zipfile:open(file.filename) if not rf then zipfile:close(); return nil, err end local contents = rf:read("*a") rf:close() local wf, err = io.open(dir.path(fs.current_dir(), file.filename), "wb") if not wf then zipfile:close(); return nil, err end wf:write(contents) wf:close() end file = files() until not file zipfile:close() return true end end --------------------------------------------------------------------- -- LuaCurl functions --------------------------------------------------------------------- if curl_ok then --- Download a remote file. -- @param url string: URL to be fetched. -- @param filename string or nil: this function attempts to detect the -- resulting local filename of the remote file as the basename of the URL; -- if that is not correct (due to a redirection, for example), the local -- filename can be given explicitly as this second argument. -- @return boolean: true on success, false on failure. function download(url, filename) assert(type(url) == "string") assert(type(filename) == "string" or not filename) filename = dir.path(fs.current_dir(), filename or dir.base_name(url)) local c = curl.new() if not c then return false end local file = io.open(filename, "wb") if not file then return false end local ok = c:setopt(curl.OPT_WRITEFUNCTION, function (stream, buffer) stream:write(buffer) return string.len(buffer) end) ok = ok and c:setopt(curl.OPT_WRITEDATA, file) ok = ok and c:setopt(curl.OPT_BUFFERSIZE, 5000) ok = ok and c:setopt(curl.OPT_HTTPHEADER, "Connection: Keep-Alive") ok = ok and c:setopt(curl.OPT_URL, url) ok = ok and c:setopt(curl.OPT_CONNECTTIMEOUT, 15) ok = ok and c:setopt(curl.OPT_USERAGENT, cfg.user_agent) ok = ok and c:perform() ok = ok and c:close() file:close() return ok end end --------------------------------------------------------------------- -- LuaSocket functions --------------------------------------------------------------------- if socket_ok then --- Download a remote file. -- @param url string: URL to be fetched. -- @param filename string or nil: this function attempts to detect the -- resulting local filename of the remote file as the basename of the URL; -- if that is not correct (due to a redirection, for example), the local -- filename can be given explicitly as this second argument. -- @return boolean: true on success, false on failure. function download(url, filename) assert(type(url) == "string") assert(type(filename) == "string" or not filename) filename = dir.path(fs.current_dir(), filename or dir.base_name(url)) local content, err if util.starts_with(url, "http:") then local res, status, headers, line = http.request(url) if not res then err = status elseif status ~= 200 then err = line else content = res end elseif util.starts_with(url, "ftp:") then content, err = ftp.get(url) end if not content then return false, "Failed downloading: " .. err end local file = io.open(filename, "wb") if not file then return false end file:write(content) file:close() return true end end --------------------------------------------------------------------- -- MD5 functions --------------------------------------------------------------------- if md5_ok then --- Get the MD5 checksum for a file. -- @param file string: The file to be computed. -- @return string: The MD5 checksum function get_md5(file) file = fs.absolute_name(file) local file = io.open(file, "rb") if not file then return false end local computed = md5.sumhexa(file:read("*a")) file:close() return computed end end --------------------------------------------------------------------- -- POSIX functions --------------------------------------------------------------------- if posix_ok then function chmod(file, mode) local err = posix.chmod(file, mode) return err == 0 end end --------------------------------------------------------------------- -- Other functions --------------------------------------------------------------------- --- Apply a patch. -- @param patchname string: The filename of the patch. function apply_patch(patchname, patchdata) local p, all_ok = patch.read_patch(patchname, patchdata) if not all_ok then return nil, "Failed reading patch "..patchname end if p then return patch.apply_patch(p, 1) end end --- Move a file. -- @param src string: Pathname of source -- @param dest string: Pathname of destination -- @return boolean or (boolean, string): true on success, false on failure, -- plus an error message. function move(src, dest) assert(src and dest) if fs.exists(dest) and not fs.is_dir(dest) then return false, "File already exists: "..dest end local ok, err = fs.copy(src, dest) if not ok then return false, err end ok = fs.delete(src) if not ok then return false, "Failed move: could not delete "..src.." after copy." end return true end
mit
wagonrepairer/Zero-K
LuaRules/Gadgets/factory_anti_slacker.lua
11
1772
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Factory Anti Slacker", desc = "Inhibits factory blocking.", author = "Licho, edited by KingRaptor", date = "10.4.2009", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end local spGetUnitDefID = Spring.GetUnitDefID local spGetGameFrame = Spring.GetGameFrame local spSetUnitBlocking = Spring.SetUnitBlocking local spGetUnitIsDead = Spring.GetUnitIsDead local noEject = { [UnitDefNames["missilesilo"].id] = true, [UnitDefNames["factoryship"].id] = true, [UnitDefNames["factoryplane"].id] = true, [UnitDefNames["factorygunship"].id] = true, } local ghostFrames = 30 --how long the unit will be ethereal local setBlocking = {} --indexed by gameframe, contains a subtable of unitIDs function gadget:GameFrame(n) if setBlocking[n] then --restore blocking for unitID, _ in pairs(setBlocking[n]) do if not spGetUnitIsDead(unitID) then spSetUnitBlocking(unitID, true) end end setBlocking[n] = nil end end function gadget:UnitFromFactory(unitID, unitDefID, teamID, builderID, builderDefID) if not noEject[builderDefID] then --Spring.Echo("Ejecting unit") local frame = spGetGameFrame() + ghostFrames if not setBlocking[frame] then setBlocking[frame] = {} end setBlocking[frame][unitID] = true spSetUnitBlocking(unitID, false) end end
gpl-2.0
ArcherSys/ArcherSys
Lua/lua/oil/corba/services/event/ProxyPushSupplier.lua
7
2450
local oil = require "oil" local oo = require "oil.oo" local assert = require "oil.assert" module("oil.corba.services.event.ProxyPushSupplier", oo.class) function __init(class, admin) return oo.rawnew(class, { admin = admin, connected = false, push_consumer = nil }) end -- Implementations shall raise the CORBA standard BAD_PARAM exception if a nil -- object reference is passed to the connect_push_consumer operation. If the -- ProxyPushSupplier is already connected to a PushConsumer, then the -- AlreadyConnected exception is raised. -- -- An implementation of a ProxyPushSupplier may put additional requirements on -- the interface supported by the push consumer. If the push consumer does not -- meet those requirements, the ProxyPushSupplier raises the TypeError -- exception. function connect_push_consumer(self, push_consumer) if self.connected then assert.exception{"IDL:omg.org/CosEventChannelAdmin/AlreadyConnected:1.0"} elseif not push_consumer then assert.exception{"IDL:omg.org/CORBA/BAD_PARAM:1.0"} end self.push_consumer = push_consumer self.connected = true self.admin:add_push_consumer(self, self.push_consumer) end -- The disconnect_push_supplier operation terminates the event communication; it -- releases resources used at the supplier to support the event communication. -- The PushSupplier object reference is disposed. Calling -- disconnect_push_supplier causes the implementation to call the -- disconnect_push_consumer operation on the corresponding PushConsumer -- interface (if that interface is known). -- -- Calling a disconnect operation on a consumer or supplier interface may cause -- a call to the corresponding disconnect operation on the connected supplier or -- consumer. -- -- Implementations must take care to avoid infinite recursive calls to these -- disconnect operations. If a consumer or supplier has received a disconnect -- call and subsequently receives another disconnect call, it shall raise a -- CORBA::OBJECT_NOT_EXIST exception. function disconnect_push_supplier(self) if not self.connected then assert.exception{"IDL:omg.org/CORBA/OBJECT_NOT_EXIST:1.0"} end self.connected = false assert.results(self.push_consumer) self.admin:rem_push_consumer(self, self.push_consumer) oil.pcall(self.push_consumer.disconnect_push_consumer, self.push_consumer) self.push_consumer = nil end
mit
wagonrepairer/Zero-K
LuaRules/Gadgets/unit_oneclick_weapon.lua
11
6231
------------------------------------------------------------------------------ -- HOW IT WORKS: -- Just calls a function in the unit script (to emit-sfx the weapon etc.) -- and sets reload time for one of the unit's weapons -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "One Click Weapon", desc = "Handles one-click weapon attacks like hoof stomp", author = "KingRaptor", date = "20 Aug 2011", license = "GNU LGPL, v2.1 or later", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -- speedups -------------------------------------------------------------------------------- local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitHealth = Spring.GetUnitHealth local spGetUnitTeam = Spring.GetUnitTeam local spGetUnitIsDead = Spring.GetUnitIsDead local spGetUnitRulesParam = Spring.GetUnitRulesParam include "LuaRules/Configs/customcmds.h.lua" if (gadgetHandler:IsSyncedCode()) then -------------------------------------------------------------------------------- -- SYNCED -------------------------------------------------------------------------------- local spGiveOrderToUnit = Spring.GiveOrderToUnit local oneClickWepCMD = { id = CMD_ONECLICK_WEAPON, name = "One-Click Weapon", action = "oneclickwep", cursor = 'oneclickwep', texture = "LuaUI/Images/Commands/Bold/action.png", type = CMDTYPE.ICON, tooltip = "Activate the unit's special weapon", } local INITIAL_CMD_DESC_ID = 500 local defs = include "LuaRules/Configs/oneclick_weapon_defs.lua" --local reloadFrame = {} --local scheduledReload = {} --local scheduledReloadByUnitID = {} local LOS_ACCESS = {inlos = true} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:Initialize() local unitList = Spring.GetAllUnits() for i=1,#(unitList) do local ud = spGetUnitDefID(unitList[i]) local team = spGetUnitTeam(unitList[i]) gadget:UnitCreated(unitList[i], ud, team) end end function gadget:UnitCreated(unitID, unitDefID, team) if defs[unitDefID] then --reloadFrame[unitID] = {} -- add oneclick weapon commands for i=1, #defs[unitDefID] do local desc = Spring.Utilities.CopyTable(oneClickWepCMD) desc.name = defs[unitDefID][i].name desc.tooltip = defs[unitDefID][i].tooltip or desc.tooltip desc.texture = defs[unitDefID][i].texture or desc.texture desc.params = {i} Spring.InsertUnitCmdDesc(unitID, INITIAL_CMD_DESC_ID + (i-1), desc) --reloadFrame[unitID][i] = -1000 end end end --[[ function gadget:UnitDestroyed(unitID) reloadFrame[unitID] = nil scheduledReload[ scheduledReloadByUnitID[unitID] ][unitID] = nil scheduledReloadByUnitID[unitID] = nil end ]]-- --[[ function gadget:GameFrame(n) if scheduledReload[n] then for unitID in pairs(scheduledReload[n]) do if Spring.ValidUnitID(unitID) then Spring.SetUnitRulesParam(unitID, "specialReloadFrame", 0, {inlos = true}) end end scheduledReload[n] = nil end end ]]-- local function doTheCommand(unitID, unitDefID, num) local data = defs[unitDefID] and defs[unitDefID][num] if (data) then local currentReload = (data.weaponToReload and Spring.GetUnitWeaponState(unitID, data.weaponToReload, "reloadState")) or (data.useSpecialReloadFrame and Spring.GetUnitRulesParam(unitID, "specialReloadFrame")) local frame = Spring.GetGameFrame() --if (reloadFrame[unitID][num] <= frame and not spGetUnitIsDead(unitID)) then if ((not currentReload or currentReload <= frame) and select(5, spGetUnitHealth(unitID)) == 1 and not spGetUnitIsDead(unitID)) then local env = Spring.UnitScript.GetScriptEnv(unitID) local func = env[data.functionToCall] Spring.UnitScript.CallAsUnit(unitID, func) local slowState = 1 - (spGetUnitRulesParam(unitID,"slowState") or 0) -- reload if (data.reloadTime and data.weaponToReload) then local reloadFrameVal = frame + data.reloadTime/slowState --reloadFrame[unitID][num] = reloadFrameVal --scheduledReloadByUnitID[unitID] = math.max(reloadFrameVal, scheduledReloadByUnitID[unitID] or 0) --Spring.SetUnitRulesParam(unitID, "specialReloadFrame", scheduledReloadByUnitID[unitID], {inlos = true}) -- for healthbar Spring.SetUnitWeaponState(unitID, data.weaponToReload, "reloadState", reloadFrameVal) end if (data.reloadTime and data.useSpecialReloadFrame) then local reloadFrameVal = frame + data.reloadTime Spring.SetUnitRulesParam(unitID, "specialReloadFrame", reloadFrameVal, LOS_ACCESS) Spring.SetUnitRulesParam(unitID, "specialReloadStart", frame, LOS_ACCESS) end return true end end return false end -- process command function gadget:CommandFallback(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions) if cmdID == CMD_ONECLICK_WEAPON then return true, doTheCommand(unitID, unitDefID, cmdParams[1] or 1) end return false -- command not used end function gadget:AllowCommand_GetWantedCommand() return {[CMD_ONECLICK_WEAPON] = true} end function gadget:AllowCommand_GetWantedUnitDefID() return true end function gadget:AllowCommand(unitID, unitDefID, teamID,cmdID, cmdParams, cmdOptions) if cmdID == CMD_ONECLICK_WEAPON and not cmdOptions.shift then local cmd = Spring.GetCommandQueue(unitID, 1) if cmd and cmd[1] and cmd[1].id and cmd[1].id == CMD_ONECLICK_WEAPON then Spring.GiveOrderToUnit(unitID,CMD.REMOVE,{cmd[1].tag},{}) return false end Spring.GiveOrderToUnit(unitID,CMD.INSERT,{0,CMD_ONECLICK_WEAPON,cmdParams[1] or 1},{"alt"}) return false end return true end else -------------------------------------------------------------------------------- -- UNSYNCED -------------------------------------------------------------------------------- function gadget:Initialize() gadgetHandler:RegisterCMDID(CMD_ONECLICK_WEAPON) Spring.SetCustomCommandDrawData(CMD_ONECLICK_WEAPON, "dgun", {1, 1, 1, 0.7}) Spring.AssignMouseCursor("oneclickwep", "cursordgun", true, true) gadgetHandler:RemoveGadget() end end
gpl-2.0
psychon/awesome
tests/examples/shims/root.lua
1
3925
local root = {_tags={}} local gtable = require("gears.table") local hotkeys = nil function root:tags() return root._tags end function root:size() --TODO use the screens return 0, 0 end function root:size_mm() return 0, 0 end function root.cursor() end -- GLOBAL KEYBINDINGS -- local keys = {} function root.keys(k) keys = k or keys return keys end -- FAKE INPUTS -- -- Turn keysym into modkey names local conversion = { Super_L = "Mod4", Control_L = "Control", Shift_L = "Shift", Alt_L = "Mod1", Super_R = "Mod4", Control_R = "Control", Shift_R = "Shift", Alt_R = "Mod1", } -- The currently pressed modkeys. local mods = {} local function get_mods() local ret = {} for mod in pairs(mods) do table.insert(ret, mod) end return ret end local function add_modkey(key) if not conversion[key] then return end mods[conversion[key]] = true end local function remove_modkey(key) if not conversion[key] then return end mods[conversion[key]] = nil end local function match_modifiers(mods1, mods2) if #mods1 ~= #mods2 then return false end for _, mod1 in ipairs(mods1) do if not gtable.hasitem(mods2, mod1) then return false end end return true end local function execute_keybinding(key, event) -- It *could* be extracted from gears.object private API, but it's equally -- ugly as using the list used by the hotkey widget. if not hotkeys then hotkeys = require("awful.key").hotkeys end for _, v in ipairs(hotkeys) do if key == v.key and match_modifiers(v.mod, get_mods()) and v[event] then v[event]() return end end end local fake_input_handlers = { key_press = function(key) add_modkey(key) if keygrabber._current_grabber then keygrabber._current_grabber(get_mods(), key, "press") else execute_keybinding(key, "press") end end, key_release = function(key) remove_modkey(key) if keygrabber._current_grabber then keygrabber._current_grabber(get_mods(), key, "release") else execute_keybinding(key, "release") end end, button_press = function() --[[TODO]] end, button_release = function() --[[TODO]] end, motion_notify = function() --[[TODO]] end, } function root.fake_input(event_type, detail, x, y) assert(fake_input_handlers[event_type], "Unknown event_type") fake_input_handlers[event_type](detail, x, y) end -- Send an artificial set of key events to trigger a key combination. -- It only works in the shims and should not be used with UTF-8 chars. function root._execute_keybinding(modifiers, key) for _, mod in ipairs(modifiers) do for real_key, mod_name in pairs(conversion) do if mod == mod_name then root.fake_input("key_press", real_key) break end end end root.fake_input("key_press" , key) root.fake_input("key_release", key) for _, mod in ipairs(modifiers) do for real_key, mod_name in pairs(conversion) do if mod == mod_name then root.fake_input("key_release", real_key) break end end end end -- Send artificial key events to write a string. -- It only works in the shims and should not be used with UTF-8 strings. function root._write_string(string, c) local old_c = client.focus if c then client.focus = c end for i=1, #string do local char = string:sub(i,i) root.fake_input("key_press" , char) root.fake_input("key_release", char) end if c then client.focus = old_c end end return root -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
shingenko/darkstar
scripts/globals/items/bowl_of_mog_pudding.lua
36
1154
----------------------------------------- -- ID: 6009 -- Item: Bowl of Mog Pudding -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 7 -- Vitality 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,6009); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 7); target:addMod(MOD_VIT, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 7); target:delMod(MOD_VIT, 3); end;
gpl-3.0
shingenko/darkstar
scripts/zones/Cape_Teriggan/npcs/relic.lua
38
1841
----------------------------------- -- Area: Cape Terrigan -- NPC: <this space intentionally left blank> -- @pos 73 4 -174 113 ----------------------------------- package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Cape_Teriggan/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 18347 and trade:getItemCount() == 4 and trade:hasItemQty(18347,1) and trade:hasItemQty(1583,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then player:startEvent(18,18348); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 18) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18348); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453); else player:tradeComplete(); player:addItem(18348); player:addItem(1453,30); player:messageSpecial(ITEM_OBTAINED,18348); player:messageSpecial(ITEMS_OBTAINED,1453,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
Illarion-eV/Illarion-Content
alchemy/item/id_167_yellow_bottle.lua
1
2052
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE common SET com_script='alchemy.item.id_167_yellow_bottle' WHERE com_itemid = 167; -- Yellow Potions -- Medicine (since illness will be a postVBU project, this will also be postVBU) local alchemy = require("alchemy.base.alchemy") local customPotion = require("alchemy.base.customPotion") local M = {} local function DrinkPotion(user,SourceItem) user:inform("Der Trank scheint keine Wirkung zu haben.","The potion seems to have no effect.") end function M.UseItem(user, SourceItem, ltstate) if SourceItem:getData("customPotion") ~= "" then customPotion.drinkInform(user, SourceItem) end -- repair potion in case it's broken alchemy.repairPotion(SourceItem) -- repair end if not ((SourceItem:getData("filledWith")=="potion") or (SourceItem:getData("filledWith") =="essenceBrew")) then return -- no potion, no essencebrew, something else end local cauldron = alchemy.GetCauldronInfront(user) if cauldron then -- infront of a cauldron? alchemy.FillIntoCauldron(user,SourceItem,cauldron,ltstate) else -- not infront of a cauldron, therefore drink! user:talk(Character.say, "#me trinkt eine gelbe Flüssigkeit.", "#me drinks a yellow liquid.") user.movepoints=user.movepoints - 20 DrinkPotion(user,SourceItem) -- call effect alchemy.EmptyBottle(user,SourceItem) end end return M
agpl-3.0
shingenko/darkstar
scripts/globals/items/carpenters_belt.lua
30
1212
----------------------------------------- -- ID: 15444 -- Item: Carpenter's belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Woodworking Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_WOODWORKING_IMAGERY) == true) then result = 236; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_WOODWORKING_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_WDW, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_WDW, 1); end;
gpl-3.0
shingenko/darkstar
scripts/globals/weaponskills/geirskogul.lua
18
2004
----------------------------------- -- Geirskogul -- Polearm weapon skill -- Skill Level: N/A -- Gae Assail/Gungnir: Shock Spikes. -- This weapon skill is only available with the stage 5 relic Polearm Gungnir, within Dynamis with the stage 4 Gae Assail, or by activating the latent effect on the Skogul Lance. -- Aligned with the Light Gorget, Aqua Gorget & Snow Gorget. -- Aligned with the Light Belt, Aqua Belt & Snow Belt. -- Element: None -- Modifiers: AGI:60% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.6; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.8; params.agi_wsc = 0.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if ((player:getEquipID(SLOT_MAIN) == 18300) and (player:getMainJob() == JOB_DRG)) then if (damage > 0) then if (player:getTP() >= 100 and player:getTP() < 200) then player:addStatusEffect(EFFECT_AFTERMATH, 6, 0, 20, 0, 7); elseif (player:getTP() >= 200 and player:getTP() < 300) then player:addStatusEffect(EFFECT_AFTERMATH, 6, 0, 40, 0, 7); elseif (player:getTP() == 300) then player:addStatusEffect(EFFECT_AFTERMATH, 6, 0, 60, 0, 7); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
ld-test/busted.ryanplusplus
busted/outputHandlers/utfTerminal.lua
2
4523
local ansicolors = require 'ansicolors' local s = require 'say' local pretty = require 'pl.pretty' return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) local successDot = ansicolors('%{green}●') local failureDot = ansicolors('%{red}●') local errorDot = ansicolors('%{magenta}●') local pendingDot = ansicolors('%{yellow}●') local pendingDescription = function(pending) local name = handler.getFullName(pending) local string = ansicolors('%{yellow}' .. s('output.pending')) .. ' → ' .. ansicolors('%{cyan}' .. pending.trace.short_src) .. ' @ ' .. ansicolors('%{cyan}' .. pending.trace.currentline) .. '\n' .. ansicolors('%{bright}' .. name) return string end local failureDescription = function(failure, isError) local string = ansicolors('%{red}' .. s('output.failure')) .. ' → ' if isError then string = ansicolors('%{magenta}' .. s('output.error')) if failure.message then string = string .. ' → ' .. ansicolors('%{cyan}' .. failure.message) .. '\n' end else string = string .. ansicolors('%{cyan}' .. failure.trace.short_src) .. ' @ ' .. ansicolors('%{cyan}' .. failure.trace.currentline) .. '\n' .. ansicolors('%{bright}' .. handler.getFullName(failure)) .. '\n' if type(failure.message) == 'string' then string = string .. failure.message elseif failure.message == nil then string = string .. 'Nil error' else string = string .. pretty.write(failure.message) end end if options.verbose and failure.trace.traceback then string = string .. '\n' .. failure.trace.traceback end return string end local statusString = function() local successString = s('output.success_plural') local failureString = s('output.failure_plural') local pendingString = s('output.pending_plural') local errorString = s('output.error_plural') local ms = handler.getDuration() local successes = handler.successesCount local pendings = handler.pendingsCount local failures = handler.failuresCount local errors = handler.errorsCount if successes == 0 then successString = s('output.success_zero') elseif successes == 1 then successString = s('output.success_single') end if failures == 0 then failureString = s('output.failure_zero') elseif failures == 1 then failureString = s('output.failure_single') end if pendings == 0 then pendingString = s('output.pending_zero') elseif pendings == 1 then pendingString = s('output.pending_single') end if errors == 0 then errorString = s('output.error_zero') elseif errors == 1 then errorString = s('output.error_single') end local formattedTime = ('%.6f'):format(ms):gsub('([0-9])0+$', '%1') return ansicolors('%{green}' .. successes) .. ' ' .. successString .. ' / ' .. ansicolors('%{red}' .. failures) .. ' ' .. failureString .. ' / ' .. ansicolors('%{magenta}' .. errors) .. ' ' .. errorString .. ' / ' .. ansicolors('%{yellow}' .. pendings) .. ' ' .. pendingString .. ' : ' .. ansicolors('%{bright}' .. formattedTime) .. ' ' .. s('output.seconds') end handler.testEnd = function(element, parent, status, debug) if not options.deferPrint then local string = successDot if status == 'pending' then string = pendingDot elseif status == 'failure' then string = failureDot end io.write(string) io.flush() end return nil, true end handler.suiteEnd = function(name, parent) print('') print(statusString()) for i, pending in pairs(handler.pendings) do print('') print(pendingDescription(pending)) end for i, err in pairs(handler.failures) do print('') print(failureDescription(err)) end for i, err in pairs(handler.errors) do print('') print(failureDescription(err, true)) end return nil, true end handler.error = function(element, parent, message, debug) io.write(errorDot) io.flush() return nil, true end local s = busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending }) busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) busted.subscribe({ 'error', 'file' }, handler.error) busted.subscribe({ 'error', 'describe' }, handler.error) return handler end
mit
matinJ/skynet
examples/client.lua
67
2101
package.cpath = "luaclib/?.so" package.path = "lualib/?.lua;examples/?.lua" if _VERSION ~= "Lua 5.3" then error "Use lua 5.3" end local socket = require "clientsocket" local proto = require "proto" local sproto = require "sproto" local host = sproto.new(proto.s2c):host "package" local request = host:attach(sproto.new(proto.c2s)) local fd = assert(socket.connect("127.0.0.1", 8888)) local function send_package(fd, pack) local package = string.pack(">s2", pack) socket.send(fd, package) end local function unpack_package(text) local size = #text if size < 2 then return nil, text end local s = text:byte(1) * 256 + text:byte(2) if size < s+2 then return nil, text end return text:sub(3,2+s), text:sub(3+s) end local function recv_package(last) local result result, last = unpack_package(last) if result then return result, last end local r = socket.recv(fd) if not r then return nil, last end if r == "" then error "Server closed" end return unpack_package(last .. r) end local session = 0 local function send_request(name, args) session = session + 1 local str = request(name, args, session) send_package(fd, str) print("Request:", session) end local last = "" local function print_request(name, args) print("REQUEST", name) if args then for k,v in pairs(args) do print(k,v) end end end local function print_response(session, args) print("RESPONSE", session) if args then for k,v in pairs(args) do print(k,v) end end end local function print_package(t, ...) if t == "REQUEST" then print_request(...) else assert(t == "RESPONSE") print_response(...) end end local function dispatch_package() while true do local v v, last = recv_package(last) if not v then break end print_package(host:dispatch(v)) end end send_request("handshake") send_request("set", { what = "hello", value = "world" }) while true do dispatch_package() local cmd = socket.readstdin() if cmd then if cmd == "quit" then send_request("quit") else send_request("get", { what = cmd }) end else socket.usleep(100) end end
mit
fzimmermann89/texlive.js
texlive/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/phylogenetics/DistanceMatrix.lua
1
12413
-- Copyright 2013 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header$ local DistanceMatrix = {} -- Imports local InterfaceToAlgorithms = require("pgf.gd.interface.InterfaceToAlgorithms") local declare = InterfaceToAlgorithms.declare --- declare { key = "distance matrix vertices", type = "string", summary = [[" A list of vertices that are used in the parsing of the |distance matrix| key. If this key is not used at all, all vertices of the graph will be used for the computation of a distance matrix. "]], documentation = [[" The vertices must be separated by spaces and/or commas. For vertices containing spaces or commas, the vertex names may be surrounded by single or double quotes (as in Lua). Typical examples are |a, b, c| or |"hello world", 'foo'|. "]] } --- declare { key = "distance matrix", type = "string", summary = [[" A distance matrix specifies ``desired distances'' between vertices in a graph. These distances are used, in particular, in algorithms for computing phylogenetic trees. "]], documentation = [[" When this key is parsed, the key |distance matrix vertices| is considered first. It is used to determine a list of vertices for which a distance matrix is computed, see that key for details. Let $n$ be the number of vertices derived from that key. The string passed to the |distance matrix| key is basically a sequence of numbers that are used to fill an $n \times n$ matrix. This works as follows: We keep track of a \emph{current position $p$} in the matrix, starting at the upper left corner of the matrix. We read the numbers in the string one by one, write it to the current position of the matrix, and advance the current position by going right one step; if we go past the right end of the matrix, we ``wrap around'' by going back to the left border of the matrix, but one line down. If we go past the bottom of the matrix, we start at the beginning once more. This basic behavior can be modified in different ways. First, when a number is followed by a semicolon instead of a comma or a space (which are the ``usual'' ways of indicating the end of a number), we immediately go down to the next line. Second, instead of a number you can directly provide a \emph{position} in the matrix and the current position will be set to this position. Such a position information is detected by a greater-than sign (|>|). It must be followed by % \begin{itemize} \item a number or a vertex name or \item a number or a vertex name, a comma, and another number or vertex name or \item a comma and a number and a vertex name. \end{itemize} % Examples of the respective cases are |>1|, |>a,b|, and |>,5|. The semantics is as follows: In all cases, if a vertex name rather than a number is given, it is converted into a number (namely the index of the vertex inside the matrix). Then, in the first case, the column of the current position is set to the given number; in the second case, the columns is set to the first number and the column is set to the second number; and in the third case only the row is set to the given number. (This idea is that following the |>|-sign comes a ``coordinate pair'' whose components are separated by a comma, but part of that pair may be missing.) If a vertex name contains special symbols like a space or a comma, you must surround it by single or double quotation marks (as in Lua). Once the string has been parsed completely, the matrix may be filled only partially. In this case, for each missing entry $(x,y)$, we try to set it to the value of the entry $(y,x)$, provided that entry is set. If neither are set, the entry is set to $0$. Let us now have a look at several examples that all produce the same matrix. The vertices are |a|, |b|, |c|. % \begin{codeexample}[code only, tikz syntax=false] 0, 1, 2 1, 0, 3 2, 3, 0 \end{codeexample} % \begin{codeexample}[code only, tikz syntax=false] 0 1 2 1 0 3 2 3 0 \end{codeexample} % \begin{codeexample}[code only, tikz syntax=false] ; 1; 2 3 \end{codeexample} % \begin{codeexample}[code only, tikz syntax=false] >,b 1; 2 3 \end{codeexample} % \begin{codeexample}[code only, tikz syntax=false] >b 1 2 >c 3 \end{codeexample} "]] } --- declare { key = "distances", type = "string", summary = [[" This key is used to specify the ``desired distances'' between a vertex and the other vertices in a graph. "]], documentation = [[" This key works similar to the |distance matrix| key, only it is passed to a vertex instead of to a whole graph. The syntax is the same, only the notion of different ``rows'' is not used. Here are some examples that all have the same effect, provided the nodes are |a|, |b|, and |c|. % \begin{codeexample}[code only, tikz syntax=false] 0, 1, 2 \end{codeexample} % \begin{codeexample}[code only, tikz syntax=false] 0 1 2 \end{codeexample} % \begin{codeexample}[code only, tikz syntax=false] >b 1 2 \end{codeexample} % \begin{codeexample}[code only, tikz syntax=false] >c 2, >b 1 \end{codeexample} "]] } local function to_index(s, indices) if s and s ~= "" then if s:sub(1,1) == '"' then local _, _, m = s:find('"(.*)"') return indices[InterfaceToAlgorithms.findVertexByName(m)] elseif s:sub(1,1) == "'" then local _, _, m = s:find("'(.*)'") return indices[InterfaceToAlgorithms.findVertexByName(m)] else local num = tonumber(s) if not num then return indices[InterfaceToAlgorithms.findVertexByName(s)] else return num end end end end local function compute_indices(vertex_string, vertices) local indices = {} if not vertex_string then for i,v in ipairs(vertices) do indices[i] = v indices[v] = i end else -- Ok, need to parse the vertex_string. Sigh. local pos = 1 while pos <= #vertex_string do local start = vertex_string:sub(pos,pos) if not start:find("[%s,]") then local _, vertex if start == '"' then _, pos, vertex = vertex_string:find('"(.-)"', pos) elseif start == "'" then _, pos, vertex = vertex_string:find("'(.-)'", pos) else _, pos, vertex = vertex_string:find("([^,%s'\"]*)", pos) end local v = assert(InterfaceToAlgorithms.findVertexByName(vertex), "unknown vertex name '" .. vertex .. "'") indices [#indices + 1] = v indices [v] = #indices end pos = pos + 1 end end return indices end --- -- Compute a distance matrix based on the values of a -- |distance matrix| and a |distance matrix vertices|. -- -- @param matrix_string A distance matrix string -- @param vertex_string A distance matrix vertex string -- @param vertices An array of all vertices in the graph. -- -- @return A distance matrix. This matrix will contain both a -- two-dimensional array (accessed through numbers) and also a -- two-dimensional hash table (accessed through vertex indices). Thus, -- you can write both |m[1][1]| and also |m[v][v]| to access the first -- entry of this matrix, provided |v == vertices[1]|. -- @return An index vector. This is an array of the vertices -- identified for the |vertex_string| parameter. function DistanceMatrix.computeDistanceMatrix(matrix_string, vertex_string, vertices) -- First, we create a table of the vertices we need to consider: local indices = compute_indices(vertex_string, vertices) -- Second, build matrix. local n = #indices local m = {} for i=1,n do m[i] = {} end local x = 1 local y = 1 local pos = 1 -- Start scanning the matrix_string while pos <= #matrix_string do local start = matrix_string:sub(pos,pos) if not start:find("[%s,]") then if start == '>' then local _, parse _, pos, parse = matrix_string:find(">([^%s>;]*)", pos) local a, b if parse:find(",") then _,_,a,b = parse:find("(.*),(.*)") else a = parse end x = to_index(a, indices) or x y = to_index(b, indices) or y elseif start == ';' then x = 1 y = y + 1 elseif start == ',' then x = x + 1 else local _, n _, pos, n = matrix_string:find("([^,;%s>]*)", pos) local num = assert(tonumber(n), "number expected in distance matrix") m[x][y] = num x = x + 1 -- Skip everything up to first comma: _, pos = matrix_string:find("(%s*,?)", pos+1) end end pos = pos + 1 if x > n then x = 1 y = y + 1 end if y > n then y = 1 end end -- Fill up for x=1,n do for y=1,n do if not m[x][y] then m[x][y] = m[y][x] or 0 end end end -- Copy to index version for x=1,n do local v = indices[x] m[v] = {} for y=1,n do local u = indices[y] m[v][u] = m[x][y] end end return m, indices end --- -- Compute a distance vector. See the key |distances| for details. -- -- @param vector_string A distance vector string -- @param vertex_string A distance matrix vertex string -- @param vertices An array of all vertices in the graph. -- -- @return A distance vector. Like a distance matrix, this vector will -- double indexed, once by numbers and once be vertex objects. -- @return An index vector. This is an array of the vertices -- identified for the |vertex_string| parameter. function DistanceMatrix.computeDistanceVector(vector_string, vertex_string, vertices) -- First, we create a table of the vertices we need to consider: local indices = compute_indices(vertex_string, vertices) -- Second, build matrix. local n = #indices local m = {} local x = 1 local pos = 1 -- Start scanning the vector_string while pos <= #vector_string do local start = vector_string:sub(pos,pos) if not start:find("[%s,]") then if start == '>' then local _, parse _, pos, parse = vector_string:find(">([^%s>;]*)", pos) x = to_index(parse, indices) or x elseif start == ',' then x = x + 1 else local _, n _, pos, n = vector_string:find("([^,;%s>]*)", pos) local num = assert(tonumber(n), "number expected in distance matrix") m[x] = num x = x + 1 -- Skip everything up to first comma: _, pos = vector_string:find("(%s*,?)", pos+1) end end pos = pos + 1 if x > n then x = 1 end end -- Fill up for x=1,n do m[x] = m[x] or 0 m[indices[x]] = m[x] end return m, indices end --- -- Compute a distance matrix for a graph that incorporates all -- information stored in the different options of the graph and the -- vertices. -- -- @param graph A digraph object. -- -- @return A distance matrix for all vertices of the graph. function DistanceMatrix.graphDistanceMatrix(digraph) local vertices = digraph.vertices local n = #vertices local m = {} for i,v in ipairs(vertices) do m[i] = {} m[v] = {} end local indices = {} for i,v in ipairs(vertices) do indices[i] = v indices[v] = i end if digraph.options['distance matrix'] then local sub, vers = DistanceMatrix.computeDistanceMatrix( digraph.options['distance matrix'], digraph.options['distance matrix vertices'], vertices ) for x=1,#vers do for y=1,#vers do m[vers[x]][vers[y]] = sub[x][y] end end end for i,v in ipairs(vertices) do if v.options['distances'] then local sub, vers = DistanceMatrix.computeDistanceVector( v.options['distances'], v.options['distance matrix vertices'], vertices ) for x=1,#vers do m[vers[x]][v] = sub[x] end end end -- Fill up number versions: for x,vx in ipairs(vertices) do for y,vy in ipairs(vertices) do m[x][y] = m[vx][vy] end end return m end return DistanceMatrix
gpl-2.0
shingenko/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5f5.lua
34
1106
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Shiva's Gate -- @pos 270 -34 100 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; end; -- ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
shingenko/darkstar
scripts/zones/Port_Windurst/npcs/Kumama.lua
36
1748
----------------------------------- -- Area: Port Windurst -- NPC: Kumama -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,KUMAMA_SHOP_DIALOG); stock = { 0x3239, 2268,1, --Linen Slops 0x32b9, 1462,1, --Holly Clogs 0x3004, 4482,1, --Mahogany Shield 0x3218, 482,2, --Leather Trousers 0x3231, 9936,2, --Cotton Brais 0x3298, 309,2, --Leather Highboots 0x32c0, 544,2, --Solea 0x32b1, 6633,2, --Cotton Gaiters 0x3002, 556,2, --Maple Shield 0x3230, 1899,3, --Brais 0x3238, 172,3, --Slops 0x32b0, 1269,3, --Gaiters 0x32b8, 111,3, --Ash Clogs 0x3001, 110,3 --Lauan Shield } showNationShop(player, WINDURST, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ld-test/dromozoa-commons
dromozoa/commons/sequence_writer.lua
1
1487
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-commons. -- -- dromozoa-commons 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. -- -- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>. local function write(data, i, j, n, value, ...) if j < n then j = j + 1 local t = type(value) if t == "string" or t == "number" then i = i + 1 data[i] = value return write(data, i, j, n, ...) else error("bad argument #" .. j .. " to 'write' (string expected, got " .. t .. ")") end else return data end end local class = {} function class.new() return {} end function class:write(...) return write(self, #self, 0, select("#", ...), ...) end function class:concat(sep) return table.concat(self, sep) end local metatable = { __index = class; } return setmetatable(class, { __call = function () return setmetatable(class.new(), metatable) end; })
gpl-3.0
shingenko/darkstar
scripts/zones/Halvung/mobs/Wamouracampa.lua
16
1604
----------------------------------- -- Area: Halvung -- MOB: Wamouracampa ----------------------------------- require("scripts/globals/status"); -- TODO: Damage resistances in streched and curled stances. Halting movement during stance change. Morph into Wamoura. ----------------------------------- -- OnMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("formTime", os.time() + math.random(43,47)); end; ----------------------------------- -- onMobRoam Action -- Autochange stance ----------------------------------- function onMobRoam(mob) local roamTime = mob:getLocalVar("formTime"); if (mob:AnimationSub() == 0 and os.time() > roamTime) then mob:AnimationSub(1); mob:setLocalVar("formTime", os.time() + math.random(43,47)); elseif (mob:AnimationSub() == 1 and os.time() > roamTime) then mob:AnimationSub(0); mob:setLocalVar("formTime", os.time() + math.random(43,47)); end end; ----------------------------------- -- OnMobFight Action -- Stance change in battle ----------------------------------- function onMobFight(mob,target) local fightTime = mob:getLocalVar("formTime"); if (mob:AnimationSub() == 0 and os.time() > fightTime) then mob:AnimationSub(1); mob:setLocalVar("formTime", os.time() + math.random(43,47)); elseif (mob:AnimationSub() == 1 and os.time() > fightTime) then mob:AnimationSub(0); mob:setLocalVar("formTime", os.time() + math.random(43,47)); end end; function onMobDeath(mob) end;
gpl-3.0
raffomania/ideophilia
src/states/menuState.lua
1
1024
local GameState = require("states/gameState") local KeyPressed = require("events/keyPressed") -- State superclass local State = require("core/state") local MenuState = class("MenuState", State) function MenuState:load() self.engine = Engine() self.eventmanager = EventManager() end function MenuState:update(dt) self.engine:update(dt) end function MenuState:draw() self.engine:draw() if constants.screenWidth > resources.images.title:getWidth() then love.graphics.draw(resources.images.title, (constants.screenWidth/2)-resources.images.title:getWidth()/2, constants.screenHeight/4, 0, 1, 1) else local scale = constants.screenWidth/resources.images.title:getWidth() love.graphics.draw(resources.images.title, 0, constants.screenHeight/4, 0, scale, scale) end end function MenuState:keypressed(key, isrepeat) self.eventmanager:fireEvent(KeyPressed(key, isrepeat)) -- Start the game when any key is pressed stack:push(GameState()) end return MenuState
mit
hiddenvirushacker/hiddenvirus
plugins/gnuplot.lua
622
1813
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot miss a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
wagonrepairer/Zero-K
scripts/armsptk.lua
11
4999
include "constants.lua" include "spider_walking.lua" -------------------------------------------------------------------------------- -- pieces -------------------------------------------------------------------------------- local base = piece 'base' local turret = piece 'turret' local box = piece 'box' local leg1 = piece 'leg1' -- back right local leg2 = piece 'leg2' -- middle right local leg3 = piece 'leg3' -- front right local leg4 = piece 'leg4' -- back left local leg5 = piece 'leg5' -- middle left local leg6 = piece 'leg6' -- front left local flares = { piece('missile1', 'missile2', 'missile3') } local smokePiece = {base, turret} -------------------------------------------------------------------------------- -- constants -------------------------------------------------------------------------------- -- Signal definitions local SIG_WALK = 1 local SIG_AIM = 2 local SIG_MISSILEANIM = {4, 8, 16} local PERIOD = 0.2 local sleepTime = PERIOD*1000 local legRaiseAngle = math.rad(30) local legRaiseSpeed = legRaiseAngle/PERIOD local legLowerSpeed = legRaiseAngle/PERIOD local legForwardAngle = math.rad(20) local legForwardTheta = math.rad(45) local legForwardOffset = 0 local legForwardSpeed = legForwardAngle/PERIOD local legMiddleAngle = math.rad(20) local legMiddleTheta = 0 local legMiddleOffset = 0 local legMiddleSpeed = legMiddleAngle/PERIOD local legBackwardAngle = math.rad(20) local legBackwardTheta = -math.rad(45) local legBackwardOffset = 0 local legBackwardSpeed = legBackwardAngle/PERIOD local restore_delay = 4000 -------------------------------------------------------------------------------- -- variables -------------------------------------------------------------------------------- local gun_1 = 1 -- four-stroke hexapedal walkscript local function Walk() Signal(SIG_WALK) SetSignalMask(SIG_WALK) while true do walk(leg1, leg2, leg3, leg4, leg5, leg6, legRaiseAngle, legRaiseSpeed, legLowerSpeed, legForwardAngle, legForwardOffset, legForwardSpeed, legForwardTheta, legMiddleAngle, legMiddleOffset, legMiddleSpeed, legMiddleTheta, legBackwardAngle, legBackwardOffset, legBackwardSpeed, legBackwardTheta, sleepTime) end end local function RestoreLegs() Signal(SIG_WALK) SetSignalMask(SIG_WALK) restoreLegs(leg1, leg2, leg3, leg4, leg5, leg6, legRaiseSpeed, legForwardSpeed, legMiddleSpeed,legBackwardSpeed) end function script.Create() StartThread(SmokeUnit, smokePiece) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(RestoreLegs) end local function RestoreAfterDelay() Sleep(restore_delay) Turn(turret, y_axis, 0, math.rad(45)) Turn(box, x_axis, 0, math.rad(45)) end function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(turret, y_axis, heading, math.rad(240)) Turn(box, x_axis, -pitch, math.rad(90)) WaitForTurn(turret, y_axis) WaitForTurn(box, x_axis) StartThread(RestoreAfterDelay) return true end function script.AimFromWeapon(num) return box end function script.QueryWeapon(num) return flares[gun_1] end local function HideMissile(num) Signal(SIG_MISSILEANIM[num]) SetSignalMask(SIG_MISSILEANIM[num]) Hide(flares[num]) Sleep(3000) Show(flares[num]) end function script.Shot(num) gun_1 = gun_1 + 1 if gun_1 > 3 then gun_1 = 1 end StartThread(HideMissile, gun_1) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(box, sfxNone) Explode(base, sfxNone) Explode(leg1, sfxNone) Explode(leg2, sfxNone) Explode(leg3, sfxNone) Explode(leg4, sfxNone) Explode(leg5, sfxNone) Explode(leg6, sfxNone) Explode(turret, sfxNone) return 1 elseif severity <= .50 then Explode(box, sfxFall) Explode(base, sfxNone) Explode(leg1, sfxFall) Explode(leg2, sfxFall) Explode(leg3, sfxFall) Explode(leg4, sfxFall) Explode(leg5, sfxFall) Explode(leg6, sfxFall) Explode(turret, sfxShatter) return 1 elseif severity <= .99 then Explode(box, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(base, sfxNone) Explode(leg1, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg2, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg3, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg4, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg5, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg6, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(turret, sfxShatter) return 2 else Explode(box, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(base, sfxNone) Explode(leg1, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg2, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg3, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg4, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg5, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg6, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(turret, sfxShatter) return 2 end end
gpl-2.0
shingenko/darkstar
scripts/zones/Throne_Room/npcs/_4l2.lua
51
1172
----------------------------------- -- Area: Throne Room -- NPC: Ore Door ------------------------------------- require("scripts/globals/bcnm"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
ArcherSys/ArcherSys
Lua/lua/oil/arch/ludo.lua
1
1061
local port = require "oil.port" local component = require "oil.component" local arch = require "oil.arch" module "oil.arch.ludo" -- MARSHALING ValueEncoder = component.Template{ codec = port.Facet, } -- REFERENCES ObjectReferrer = component.Template{ references = port.Facet, } -- REQUESTER OperationRequester = component.Template{ requests = port.Facet, channels = port.Receptacle, codec = port.Receptacle, } -- LISTENER RequestListener = component.Template{ listener = port.Facet, channels = port.Receptacle, codec = port.Receptacle, } function assemble(components) arch.start(components) -- COMMUNICATION ClientChannels.sockets = BasicSystem.sockets ServerChannels.sockets = BasicSystem.sockets -- REQUESTER OperationRequester.codec = ValueEncoder.codec OperationRequester.channels = ClientChannels.channels -- LISTENER RequestListener.codec = ValueEncoder.codec RequestListener.channels = ServerChannels.channels -- MARSHALING ValueEncoder.codec:localresources(components) arch.finish(components) end
mit
ld-test/dromozoa-commons
test/test_double.lua
1
1772
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-commons. -- -- dromozoa-commons 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. -- -- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>. local double = require "dromozoa.commons.double" local equal = require "dromozoa.commons.equal" local function test(this, that) assert(equal({ double.word(this) }, that)) assert(equal({ double.word(this, "<") }, that)) assert(equal({ double.word(this, ">") }, { that[2], that[1] })) end local DBL_MAX = 1.7976931348623157e+308 local DBL_DENORM_MIN = 4.9406564584124654e-324 local DBL_MIN = 2.2250738585072014e-308 local DBL_EPSILON = 2.2204460492503131e-16 test(42, { 0x00000000, 0x40450000 }) test(DBL_MAX, { 0xffffffff, 0x7fefffff }) test(DBL_DENORM_MIN, { 0x00000001, 0x00000000 }) test(DBL_MIN, { 0x00000000, 0x00100000 }) test(DBL_EPSILON, { 0x00000000, 0x3cb00000 }) test(math.pi, { 0x54442d18, 0x400921fb }) test(0, { 0x00000000, 0x00000000 }) test(-1 / math.huge, { 0x00000000, 0x80000000 }) test(math.huge, { 0x00000000, 0x7ff00000 }) test(-math.huge, { 0x00000000, 0xfff00000 }) test(0 / 0, { 0x00000000, 0xfff80000 })
gpl-3.0
QuetzalQatl/RustPluginManual
SnapshotAllPlugins/email.lua
1
5188
PLUGIN.Title = "Email API" PLUGIN.Version = V(0, 1, 3) PLUGIN.Description = "API for sending email messages via supported transactional email services." PLUGIN.Author = "Wulfspider" PLUGIN.Url = "http://forum.rustoxide.com/plugins/712/" PLUGIN.ResourceId = 712 PLUGIN.HasConfig = true local debug = false function PLUGIN:Init() self:LoadDefaultConfig() end function PLUGIN:EmailMessage(subject, message) if subject == "" then print("[" .. self.Title .. "] " .. self.Config.Messages.SubjectRequired) return end if message == "" then print("[" .. self.Title .. "] " .. self.Config.Messages.MessageRequired) return end if string.lower(self.Config.Settings.Provider) == "elastic" or string.lower(self.Config.Settings.Provider) == "elasticemail" then if self.Config.Settings.ApiKeyPrivate == "" then print("[" .. self.Title .. "] " .. self.Config.Messages.SetApiKey) return end self.url = "https://api.elasticemail.com/mailer/send" self.data = "api_key=" .. self.Config.Settings.ApiKeyPrivate .. "&username=" .. self.Config.Settings.Username .. "&from=" .. self.Config.Settings.EmailFrom .. "&from_name=" .. self.Config.Settings.NameFrom .. "&to=" .. self.Config.Settings.EmailTo .. "&toname=" .. self.Config.Settings.NameTo .. "&subject=" .. subject .. "&body_text=" .. message elseif string.lower(self.Config.Settings.Provider) == "mandrill" then if self.Config.Settings.ApiKeyPrivate == "" then print("[" .. self.Title .. "] " .. self.Config.Messages.SetApiKey) return end self.url = "https://mandrillapp.com/api/1.0/messages/send.json" self.data = '{\"key\": \"' .. self.Config.Settings.ApiKeyPrivate .. '\",' .. '\"message\": {' .. '\"from_email\": \"' .. self.Config.Settings.EmailFrom .. '\",' .. '\"from_name\": \"' .. self.Config.Settings.NameFrom .. '\",' .. '\"to\": [{' .. '\"email\": \"' .. self.Config.Settings.EmailTo .. '\",' .. '\"name\": \"' .. self.Config.Settings.NameTo .. '\"}],' .. '\"subject\": \"' .. subject .. '\",' .. '\"html\": \"' .. message .. '\"}}' elseif string.lower(self.Config.Settings.Provider) == "sendgrid" then if self.Config.Settings.ApiKeyPrivate == "" then print("[" .. self.Title .. "] " .. self.Config.Messages.SetApiKey) return end self.url = "https://api.sendgrid.com/api/mail.send.json" self.data = "api_key=" .. self.Config.Settings.ApiKeyPrivate .. "&api_user=" .. self.Config.Settings.Username .. "&from=" .. self.Config.Settings.EmailFrom .. "&fromname=" .. self.Config.Settings.NameFrom .. "&to=" .. self.Config.Settings.EmailTo .. "&toname=" .. self.Config.Settings.NameTo .. "&subject=" .. subject .. "&html=" .. message else print("[" .. self.Title .. "] " .. self.Config.Messages.InvalidProvider) return end webrequests.EnqueuePost(self.url, self.data, function(code, response) if debug then self:DebugMessages(self.url, self.data, code) end if code ~= 200 and code ~= 250 then print("[" .. self.Title .. "] " .. self.Config.Messages.SendFailed) else print("[" .. self.Title .. "] " .. self.Config.Messages.SendSuccess) end end, self.Plugin) end function PLUGIN:DebugMessages(url, data, code) if debug then print("[" .. self.Title .. "] POST URL: " .. tostring(url)) print("[" .. self.Title .. "] POST data: " .. tostring(data)) print("[" .. self.Title .. "] HTTP code: " .. code) end end function PLUGIN:LoadDefaultConfig() self.Config.Settings = self.Config.Settings or {} self.Config.Settings.ApiKeyPrivate = self.Config.Settings.ApiKeyPrivate or "" self.Config.Settings.ApiKeyPublic = self.Config.Settings.ApiKeyPublic or "" self.Config.Settings.EmailFrom = self.Config.Settings.EmailFrom or "me@me.tld" self.Config.Settings.EmailTo = self.Config.Settings.EmailTo or "you@you.tld" self.Config.Settings.NameFrom = self.Config.Settings.NameFrom or "Bob Barker" self.Config.Settings.NameTo = self.Config.Settings.NameTo or "Drew Carey" self.Config.Settings.Provider = self.Config.Settings.Provider or "mandrill" self.Config.Settings.Username = self.Config.Settings.Username or "" self.Config.Messages = self.Config.Messages or {} self.Config.Messages.InvalidProvider = self.Config.Messages.InvalidProvider or "Configured email provider is not valid!" self.Config.Messages.MessageRequired = self.Config.Messages.MessageRequired or "Message not given! Please enter one and try again" self.Config.Messages.SendFailed = self.Config.Messages.SendFailed or "Email failed to send!" self.Config.Messages.SendSuccess = self.Config.Messages.SendSuccess or "Email successfully sent!" self.Config.Messages.SetApiKey = self.Config.Messages.SetApiKey or "API key not set! Please set it and try again." self.Config.Messages.SubjectRequired = self.Config.Messages.SubjectRequired or "Subject not given! Please enter one and try again" self:SaveConfig() end
gpl-2.0
nadavo/DeepLearningCourse
hw3/utils/trainRecurrent.lua
1
7972
require 'optim' require 'eladtools' require 'nn' require 'recurrent' ---------------------------------------------------------------------- -- Output files configuration os.execute('mkdir -p ' .. opt.save) cmd:log(opt.save .. '/log.txt', opt) local netFilename = paths.concat(opt.save, 'Net') local optStateFilename = paths.concat(opt.save,'optState') local vocabSize = data.vocabSize local vocab = data.vocab local decoder = data.decoder local trainRegime = modelConfig.regime local recurrent = modelConfig.recurrent local stateSize = modelConfig.stateSize local embedder = modelConfig.embedder local classifier = modelConfig.classifier -- Model + Loss: local model = nn.Sequential() model:add(embedder) model:add(recurrent) model:add(nn.TemporalModule(classifier)) local criterion = nn.CrossEntropyCriterion()--ClassNLLCriterion() local TensorType = 'torch.FloatTensor' if opt.type =='cuda' then require 'cutorch' require 'cunn' cutorch.setDevice(opt.devid) cutorch.manualSeed(opt.seed) model:cuda() criterion = criterion:cuda() TensorType = 'torch.CudaTensor' ---Support for multiple GPUs - currently data parallel scheme if opt.nGPU > 1 then initState:resize(opt.batchSize / opt.nGPU, stateSize) local net = model model = nn.DataParallelTable(1) model:add(net, 1) for i = 2, opt.nGPU do cutorch.setDevice(i) model:add(net:clone(), i) -- Use the ith GPU end cutorch.setDevice(opt.devid) end end --sequential criterion local seqCriterion = nn.TemporalCriterion(criterion) -- Optimization configuration local Weights,Gradients = model:getParameters() --initialize weights uniformly Weights:uniform(-opt.initWeight, opt.initWeight) local savedModel = { embedder = embedder:clone('weight','bias', 'running_mean', 'running_std'), recurrent = recurrent:clone('weight','bias', 'running_mean', 'running_std'), classifier = classifier:clone('weight','bias', 'running_mean', 'running_std') } ---------------------------------------------------------------------- print '\n==> Network' print(model) print('\n==>' .. Weights:nElement() .. ' Parameters') print '\n==> Criterion' print(criterion) if trainRegime then print '\n==> Training Regime' table.foreach(trainRegime, function(x, val) print(string.format('%012s',x), unpack(val)) end) end ------------------Optimization Configuration-------------------------- local optimState = { learningRate = opt.LR, momentum = opt.momentum, weightDecay = opt.weightDecay, learningRateDecay = opt.LRDecay } local optimizer = Optimizer{ Model = model, Loss = seqCriterion, OptFunction = _G.optim[opt.optimization], OptState = optimState, Parameters = {Weights, Gradients}, Regime = trainRegime, GradRenorm = opt.gradClip } ---------------------------------------------------------------------- ---utility functions local function reshapeData(wordVec, seqLength, batchSize) local offset = offset or 0 local length = wordVec:nElement() local numBatches = torch.floor(length / (batchSize * seqLength)) local batchWordVec = wordVec.new():resize(numBatches, batchSize, seqLength) local endWords = wordVec.new():resize(numBatches, batchSize, 1) local endIdxs = torch.LongTensor() for i=1, batchSize do local startPos = torch.round((i - 1) * length / batchSize ) + 1 local sliceLength = seqLength * numBatches local endPos = startPos + sliceLength - 1 batchWordVec:select(2,i):copy(wordVec:narrow(1, startPos, sliceLength)) endIdxs:range(startPos + seqLength, endPos + 1, seqLength) endWords:select(2,i):copy(wordVec:index(1, endIdxs)) end return batchWordVec, endWords end local function saveModel(epoch) local fn = netFilename .. '_' .. epoch .. '.dat' torch.save(fn, { embedder = savedModel.embedder:clone():float(), recurrent = savedModel.recurrent:clone():float(), classifier = savedModel.classifier:clone():float(), inputSize = inputSize, stateSize = stateSize, vocab = vocab, decoder = decoder }) collectgarbage() end ---------------------------------------------------------------------- local function ForwardSeq(dataVec, train) local data, labels = reshapeData(dataVec, opt.seqLength, opt.batchSize ) local sizeData = data:size(1) local numSamples = 0 local lossVal = 0 local currLoss = 0 local x = torch.Tensor(opt.batchSize, opt.seqLength):type(TensorType) local yt = torch.Tensor(opt.batchSize, opt.seqLength):type(TensorType) -- input is a sequence model:sequence() model:forget() for b=1, sizeData do if b==1 or opt.shuffle then --no dependancy between consecutive batches model:zeroState() end x:copy(data[b]) yt:narrow(2,1,opt.seqLength-1):copy(x:narrow(2,2,opt.seqLength-1)) yt:select(2, opt.seqLength):copy(labels[b]) if train then if opt.nGPU > 1 then model:syncParameters() end y, currLoss = optimizer:optimize(x, yt) else y = model:forward(x) currLoss = seqCriterion:forward(y,yt) end lossVal = currLoss / opt.seqLength + lossVal numSamples = numSamples + x:size(1) xlua.progress(numSamples, sizeData*opt.batchSize) end collectgarbage() xlua.progress(numSamples, sizeData) return lossVal / sizeData end local function ForwardSingle(dataVec) local sizeData = dataVec:nElement() local numSamples = 0 local lossVal = 0 local currLoss = 0 -- input is from a single time step model:single() local x = torch.Tensor(1,1):type(TensorType) local y for i=1, sizeData-1 do x:fill(dataVec[i]) y = recurrent:forward(embedder:forward(x):select(2,1)) currLoss = criterion:forward(y, dataVec[i+1]) lossVal = currLoss + lossVal if (i % 100 == 0) then xlua.progress(i, sizeData) end end collectgarbage() return(lossVal/sizeData) end ------------------------------ local function train(dataVec) model:training() return ForwardSeq(dataVec, true) end local function evaluate(dataVec) model:evaluate() return ForwardSeq(dataVec, false) end local function sample(str, num, space, temperature) local num = num or 50 local temperature = temperature or 1 local function smp(preds) if temperature == 0 then local _, num = preds:max(2) return num else preds:div(temperature) -- scale by temperature local probs = preds:squeeze() probs:div(probs:sum()) -- renormalize so probs sum to one local num = torch.multinomial(probs:float(), 1):typeAs(preds) return num end end recurrent:evaluate() recurrent:single() local sampleModel = nn.Sequential():add(embedder):add(recurrent):add(classifier):add(nn.SoftMax():type(TensorType)) local pred, predText, embedded if str then local encoded = data.encode(str) for i=1, encoded:nElement() do pred = sampleModel:forward(encoded:narrow(1,i,1)) end wordNum = smp(pred) predText = str .. '... ' .. decoder[wordNum:squeeze()] else wordNum = torch.Tensor(1):random(vocabSize):type(TensorType) predText = '' end for i=1, num do pred = sampleModel:forward(wordNum) wordNum = smp(pred) if space then predText = predText .. ' ' .. decoder[wordNum:squeeze()] else predText = predText .. decoder[wordNum:squeeze()] end end return predText end return { train = train, evaluate = evaluate, sample = sample, saveModel = saveModel, optimState = optimState, model = model }
mit
kveratis/GameCode4
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/luasql/tests/test.lua
1
24318
#!/usr/local/bin/lua5.1 -- See Copyright Notice in license.html -- $Id: test.lua,v 1.52 2008/06/30 10:43:03 blumf Exp $ TOTAL_FIELDS = 40 TOTAL_ROWS = 40 --unused DEFINITION_STRING_TYPE_NAME = "text" QUERYING_STRING_TYPE_NAME = "text" CREATE_TABLE_RETURN_VALUE = 0 DROP_TABLE_RETURN_VALUE = 0 MSG_CURSOR_NOT_CLOSED = "cursor was not automatically closed by fetch" CHECK_GETCOL_INFO_TABLES = true --------------------------------------------------------------------- -- Creates a table that can handle differing capitalization of field -- names -- @return A table with altered metatable --------------------------------------------------------------------- local mt = { __index = function(t, i) if type(i) == "string" then return rawget(t, string.upper(i)) or rawget(t, string.lower(i)) end return rawget(t, i) end } function fetch_table () return setmetatable({}, mt) end --------------------------------------------------------------------- -- Produces a SQL statement which completely erases a table. -- @param table_name String with the name of the table. -- @return String with SQL statement. --------------------------------------------------------------------- function sql_erase_table (table_name) return string.format ("delete from %s", table_name) end --------------------------------------------------------------------- -- checks for a value and throw an error if it is invalid. --------------------------------------------------------------------- function assert2 (expected, value, msg) if not msg then msg = '' else msg = msg..'\n' end return assert (value == expected, msg.."wrong value ("..tostring(value).." instead of ".. tostring(expected)..")") end --------------------------------------------------------------------- -- Shallow compare of two tables --------------------------------------------------------------------- function table_compare(t1, t2) if t1 == t2 then return true; end for i, v in pairs(t1) do if t2[i] ~= v then return false; end end for i, v in pairs(t2) do if t1[i] ~= v then return false; end end return true end --------------------------------------------------------------------- -- object test. --------------------------------------------------------------------- function test_object (obj, objmethods) -- checking object type. assert2 (true, type(obj) == "userdata" or type(obj) == "table", "incorrect object type") -- trying to get metatable. assert2 ("LuaSQL: you're not allowed to get this metatable", getmetatable(obj), "error permitting access to object's metatable") -- trying to set metatable. assert2 (false, pcall (setmetatable, ENV, {})) -- checking existence of object's methods. for i = 1, table.getn (objmethods) do local method = obj[objmethods[i]] assert2 ("function", type(method)) assert2 (false, pcall (method), "no 'self' parameter accepted") end return obj end ENV_METHODS = { "close", "connect", } ENV_OK = function (obj) return test_object (obj, ENV_METHODS) end CONN_METHODS = { "close", "commit", "execute", "rollback", "setautocommit", } CONN_OK = function (obj) return test_object (obj, CONN_METHODS) end CUR_METHODS = { "close", "fetch", "getcolnames", "getcoltypes", } CUR_OK = function (obj) return test_object (obj, CUR_METHODS) end function checkUnknownDatabase(ENV) assert2 (nil, ENV:connect ("/unknown-data-base"), "this should be an error") end --------------------------------------------------------------------- -- basic checking test. --------------------------------------------------------------------- function basic_test () -- Check environment object. ENV = ENV_OK (luasql[driver] ()) assert2 (true, ENV:close(), "couldn't close environment") -- trying to connect with a closed environment. assert2 (false, pcall (ENV.connect, ENV, datasource, username, password), "error connecting with a closed environment") -- it is ok to close a closed object, but false is returned instead of true. assert2 (false, ENV:close()) -- Reopen the environment. ENV = ENV_OK (luasql[driver] ()) -- Check connection object. local conn, err = ENV:connect (datasource, username, password) assert (conn, (err or '').." ("..datasource..")") CONN_OK (conn) assert2 (true, conn:close(), "couldn't close connection") -- trying to execute a statement with a closed connection. assert2 (false, pcall (conn.execute, conn, "create table x (c char)"), "error while executing through a closed connection") -- it is ok to close a closed object, but false is returned instead of true. assert2 (false, conn:close()) -- Check error situation. checkUnknownDatabase(ENV) -- force garbage collection local a = {} setmetatable(a, {__mode="v"}) a.ENV = ENV_OK (luasql[driver] ()) a.CONN = a.ENV:connect (datasource, username, password) collectgarbage () collectgarbage () assert2(nil, a.ENV, "environment not collected") assert2(nil, a.CONN, "connection not collected") end --------------------------------------------------------------------- -- Build SQL command to create the test table. --------------------------------------------------------------------- function define_table (n) local t = {} for i = 1, n do table.insert (t, "f"..i.." "..DEFINITION_STRING_TYPE_NAME) end return "create table t ("..table.concat (t, ',')..")" end --------------------------------------------------------------------- -- Create a table with TOTAL_FIELDS character fields. --------------------------------------------------------------------- function create_table () -- Check SQL statements. CONN = CONN_OK (ENV:connect (datasource, username, password)) -- Create t. local cmd = define_table(TOTAL_FIELDS) assert2 (CREATE_TABLE_RETURN_VALUE, CONN:execute (cmd)) end --------------------------------------------------------------------- -- Fetch 2 values. --------------------------------------------------------------------- function fetch2 () -- insert a record. assert2 (1, CONN:execute ("insert into t (f1, f2) values ('b', 'c')")) -- retrieve data. local cur = CUR_OK (CONN:execute ("select f1, f2, f3 from t")) -- check data. local f1, f2, f3 = cur:fetch() assert2 ('b', f1) assert2 ('c', f2) assert2 (nil, f3) assert2 (nil, cur:fetch()) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- insert a second record. assert2 (1, CONN:execute ("insert into t (f1, f2) values ('d', 'e')")) cur = CUR_OK (CONN:execute ("select f1, f2, f3 from t order by f1")) local f1, f2, f3 = cur:fetch() assert2 ('b', f1, f2) -- f2 can be an error message assert2 ('c', f2) assert2 (nil, f3) f1, f2, f3 = cur:fetch() assert2 ('d', f1, f2) -- f2 can be an error message assert2 ('e', f2) assert2 (nil, f3) assert2 (nil, cur:fetch()) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- remove records. assert2 (2, CONN:execute ("delete from t where f1 in ('b', 'd')")) end --------------------------------------------------------------------- -- Test fetch with a new table, reusing a table and with different -- indexing. --------------------------------------------------------------------- function fetch_new_table () -- insert elements. assert2 (1, CONN:execute ("insert into t (f1, f2, f3, f4) values ('a', 'b', 'c', 'd')")) assert2 (1, CONN:execute ("insert into t (f1, f2, f3, f4) values ('f', 'g', 'h', 'i')")) -- retrieve data using a new table. local cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch(fetch_table()) assert2 (type(row), "table", err) assert2 ('a', row[1]) assert2 ('b', row[2]) assert2 ('c', row[3]) assert2 ('d', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) row, err = cur:fetch(fetch_table()) assert (type(row), "table", err) assert2 ('f', row[1]) assert2 ('g', row[2]) assert2 ('h', row[3]) assert2 ('i', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) assert2 (nil, cur:fetch{}) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- retrieve data reusing the same table. io.write ("reusing a table...") cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch(fetch_table()) assert (type(row), "table", err) assert2 ('a', row[1]) assert2 ('b', row[2]) assert2 ('c', row[3]) assert2 ('d', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) row, err = cur:fetch (row) assert (type(row), "table", err) assert2 ('f', row[1]) assert2 ('g', row[2]) assert2 ('h', row[3]) assert2 ('i', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) assert2 (nil, cur:fetch(fetch_table())) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- retrieve data reusing the same table with alphabetic indexes. io.write ("with alpha keys...") cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch (fetch_table(), "a") assert (type(row), "table", err) assert2 (nil, row[1]) assert2 (nil, row[2]) assert2 (nil, row[3]) assert2 (nil, row[4]) assert2 ('a', row.f1) assert2 ('b', row.f2) assert2 ('c', row.f3) assert2 ('d', row.f4) row, err = cur:fetch (row, "a") assert2 (type(row), "table", err) assert2 (nil, row[1]) assert2 (nil, row[2]) assert2 (nil, row[3]) assert2 (nil, row[4]) assert2 ('f', row.f1) assert2 ('g', row.f2) assert2 ('h', row.f3) assert2 ('i', row.f4) assert2 (nil, cur:fetch(row, "a")) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- retrieve data reusing the same table with both indexes. io.write ("with both keys...") cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch (fetch_table(), "an") assert (type(row), "table", err) assert2 ('a', row[1]) assert2 ('b', row[2]) assert2 ('c', row[3]) assert2 ('d', row[4]) assert2 ('a', row.f1) assert2 ('b', row.f2) assert2 ('c', row.f3) assert2 ('d', row.f4) row, err = cur:fetch (row, "an") assert (type(row), "table", err) assert2 ('f', row[1]) assert2 ('g', row[2]) assert2 ('h', row[3]) assert2 ('i', row[4]) assert2 ('f', row.f1) assert2 ('g', row.f2) assert2 ('h', row.f3) assert2 ('i', row.f4) assert2 (nil, cur:fetch(row, "an")) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- clean the table. assert2 (2, CONN:execute ("delete from t where f1 in ('a', 'f')")) end --------------------------------------------------------------------- -- Fetch many values --------------------------------------------------------------------- function fetch_many () -- insert values. local fields, values = "f1", "'v1'" for i = 2, TOTAL_FIELDS do fields = string.format ("%s,f%d", fields, i) values = string.format ("%s,'v%d'", values, i) end local cmd = string.format ("insert into t (%s) values (%s)", fields, values) assert2 (1, CONN:execute (cmd)) -- fetch values (without a table). local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = { cur:fetch () } assert2 ("string", type(row[1]), "error while trying to fetch many values (without a table)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with a table and default indexing). io.write ("with a table...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch(fetch_table()) assert2 ("string", type(row[1]), "error while trying to fetch many values (default indexing)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with numbered indexes on a table). io.write ("with numbered keys...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch (fetch_table(), "n") assert2 ("string", type(row[1]), "error while trying to fetch many values (numbered indexes)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with alphanumeric indexes on a table). io.write ("with alpha keys...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch (fetch_table(), "a") assert2 ("string", type(row.f1), "error while trying to fetch many values (alphanumeric indexes)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row['f'..i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with both indexes on a table). io.write ("with both keys...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch (fetch_table(), "na") assert2 ("string", type(row[1]), "error while trying to fetch many values (both indexes)") assert2 ("string", type(row.f1), "error while trying to fetch many values (both indexes)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) assert2 ('v'..i, row['f'..i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- clean the table. assert2 (1, CONN:execute ("delete from t where f1 = 'v1'")) end --------------------------------------------------------------------- --------------------------------------------------------------------- function rollback () -- begin transaction assert2 (true, CONN:setautocommit (false), "couldn't disable autocommit") -- insert a record and commit the operation. assert2 (1, CONN:execute ("insert into t (f1) values ('a')")) local cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber (cur:fetch ()), "Insert failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:commit(), "couldn't commit transaction") -- insert a record and roll back the operation. assert2 (1, CONN:execute ("insert into t (f1) values ('b')")) local cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (2, tonumber (cur:fetch ()), "Insert failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:rollback (), "couldn't roolback transaction") -- check resulting table with one record. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) -- delete a record and roll back the operation. assert2 (1, CONN:execute ("delete from t where f1 = 'a'")) cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (0, tonumber(cur:fetch())) assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:rollback (), "couldn't roolback transaction") -- check resulting table with one record. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) --[[ -- insert a second record and turn on the auto-commit mode. -- this will produce a rollback on PostgreSQL and a commit on ODBC. -- what to do? assert2 (1, CONN:execute ("insert into t (f1) values ('b')")) cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (2, tonumber (cur:fetch ()), "Insert failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:setautocommit (true), "couldn't enable autocommit") -- check resulting table with one record. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) --]] -- clean the table. assert2 (1, CONN:execute (sql_erase_table"t")) assert2 (true, CONN:commit (), "couldn't commit transaction") assert2 (true, CONN:setautocommit (true), "couldn't enable autocommit") -- check resulting table with no records. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (0, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) end --------------------------------------------------------------------- -- Get column names and types. --------------------------------------------------------------------- function column_info () -- insert elements. assert2 (1, CONN:execute ("insert into t (f1, f2, f3, f4) values ('a', 'b', 'c', 'd')")) local cur = CUR_OK (CONN:execute ("select f1,f2,f3,f4 from t")) -- get column information. local names, types = cur:getcolnames(), cur:getcoltypes() assert2 ("table", type(names), "getcolnames failed") assert2 ("table", type(types), "getcoltypes failed") assert2 (4, table.getn(names), "incorrect column names table") assert2 (4, table.getn(types), "incorrect column types table") for i = 1, table.getn(names) do assert2 ("f"..i, string.lower(names[i]), "incorrect column names table") local type_i = types[i] assert (type_i == QUERYING_STRING_TYPE_NAME, "incorrect column types table") end -- check if the tables are being reused. local n2, t2 = cur:getcolnames(), cur:getcoltypes() if CHECK_GETCOL_INFO_TABLES then assert2 (names, n2, "getcolnames is rebuilding the table") assert2 (types, t2, "getcoltypes is rebuilding the table") else assert2 (true, table_compare(names, n2), "getcolnames is inconsistent") assert2 (true, table_compare(types, t2), "getcoltypes is inconsistent") end assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) -- clean the table. assert2 (1, CONN:execute ("delete from t where f1 = 'a'")) end --------------------------------------------------------------------- -- Escaping strings --------------------------------------------------------------------- function escape () local escaped = CONN:escape"a'b'c'd" assert ("a\\'b\\'c\\'d" == escaped or "a''b''c''d" == escaped) end --------------------------------------------------------------------- --------------------------------------------------------------------- function check_close() -- an object with references to it can't be closed local cmd = "select * from t" local cur = CUR_OK(CONN:execute (cmd)) assert2 (true, cur:close(), "couldn't close cursor") -- force garbage collection local a = {} setmetatable(a, {__mode="v"}) a.CONN = ENV:connect (datasource, username, password) cur = CUR_OK(a.CONN:execute (cmd)) collectgarbage () collectgarbage () CONN_OK (a.CONN) a.cur = cur a.cur:close() a.CONN:close() cur = nil collectgarbage () assert2(nil, a.cur, "cursor not collected") collectgarbage () assert2(nil, a.CONN, "connection not collected") -- check cursor integrity after trying to close a connection local conn = CONN_OK (ENV:connect (datasource, username, password)) assert2 (1, conn:execute"insert into t (f1) values (1)", "could not insert a new record") local cur = CUR_OK (conn:execute (cmd)) local ok, err = pcall (conn.close, conn) CUR_OK (cur) assert (cur:fetch(), "corrupted cursor") cur:close () conn:close () end --------------------------------------------------------------------- --------------------------------------------------------------------- function drop_table () assert2 (true, CONN:setautocommit(true), "couldn't enable autocommit") -- Postgres retorns 0, ODBC retorns -1, sqlite returns 1 assert2 (DROP_TABLE_RETURN_VALUE, CONN:execute ("drop table t")) end --------------------------------------------------------------------- --------------------------------------------------------------------- function close_conn () assert (true, CONN:close()) assert (true, ENV:close()) end --------------------------------------------------------------------- -- Testing Extensions --------------------------------------------------------------------- EXTENSIONS = { } function extensions_test () for i, f in ipairs (EXTENSIONS) do f () end end --------------------------------------------------------------------- -- Testing numrows method. -- This is not a default test, it must be added to the extensions -- table to be executed. --------------------------------------------------------------------- function numrows() local cur = CUR_OK(CONN:execute"select * from t") assert2(0,cur:numrows()) cur:close() -- Inserts one row. assert2 (1, CONN:execute"insert into t (f1) values ('a')", "could not insert a new record") cur = CUR_OK(CONN:execute"select * from t") assert2(1,cur:numrows()) cur:close() -- Inserts three more rows (total = 4). assert2 (1, CONN:execute"insert into t (f1) values ('b')", "could not insert a new record") assert2 (1, CONN:execute"insert into t (f1) values ('c')", "could not insert a new record") assert2 (1, CONN:execute"insert into t (f1) values ('d')", "could not insert a new record") cur = CUR_OK(CONN:execute"select * from t") assert2(4,cur:numrows()) cur:close() -- Deletes one row assert2(1, CONN:execute"delete from t where f1 = 'a'", "could not delete the specified row") cur = CUR_OK(CONN:execute"select * from t") assert2(3,cur:numrows()) cur:close() -- Deletes all rows assert2 (3, CONN:execute (sql_erase_table"t")) cur = CUR_OK(CONN:execute"select * from t") assert2(0,cur:numrows()) cur:close() io.write (" numrows") end --------------------------------------------------------------------- -- Main --------------------------------------------------------------------- if type(arg[1]) ~= "string" then print (string.format ("Usage %s <driver> [<data source> [, <user> [, <password>]]]", arg[0])) os.exit() end driver = arg[1] datasource = arg[2] or "luasql-test" username = arg[3] or nil password = arg[4] or nil -- Loading driver specific functions if arg[0] then local path = string.gsub (arg[0], "^([^/]*%/).*$", "%1") if path == "test.lua" then path = "" end local file = path..driver..".lua" local f, err = loadfile (file) if not f then print ("LuaSQL test: couldn't find driver-specific test file (".. file..").\nProceeding with general test") else f () end end -- Complete set of tests tests = { { "basic checking", basic_test }, { "create table", create_table }, { "fetch two values", fetch2 }, { "fetch new table", fetch_new_table }, { "fetch many", fetch_many }, { "rollback", rollback }, { "get column information", column_info }, { "escape", escape }, { "extensions", extensions_test }, { "close objects", check_close }, { "drop table", drop_table }, { "close connection", close_conn }, } require ("luasql."..driver) assert (luasql, "Could not load driver: no luasql table.") io.write (luasql._VERSION.." "..driver.." driver test. "..luasql._COPYRIGHT.."\n") for i = 1, table.getn (tests) do local t = tests[i] io.write (t[1].." ...") local ok, err = xpcall (t[2], debug.traceback) if not ok then io.write ("\n"..err) io.write"\n... trying to drop test table ..." local ok, err = pcall (drop_table) if not ok then io.write (" failed: "..err) else io.write" OK !\n... and to close the connection ..." local ok, err = pcall (close_conn) if not ok then io.write (" failed: "..err) else io.write" OK !" end end io.write"\nThe test failed!\n" return end io.write (" OK !\n") end io.write ("The test passed!\n")
lgpl-3.0
wagonrepairer/Zero-K
LuaRules/Gadgets/unit_attributes.lua
3
18430
if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Attributes", desc = "Handles UnitRulesParam attributes.", author = "CarRepairer & Google Frog", date = "2009-11-27", --last update 2014-2-19 license = "GNU GPL, v2 or later", layer = -1, enabled = true, } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local UPDATE_PERIOD = 3 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local floor = math.floor local spValidUnitID = Spring.ValidUnitID local spGetUnitDefID = Spring.GetUnitDefID local spGetGameFrame = Spring.GetGameFrame local spGetUnitRulesParam = Spring.GetUnitRulesParam local spSetUnitRulesParam = Spring.SetUnitRulesParam local spSetUnitBuildSpeed = Spring.SetUnitBuildSpeed local spSetUnitWeaponState = Spring.SetUnitWeaponState local spGetUnitWeaponState = Spring.GetUnitWeaponState local spGiveOrderToUnit = Spring.GiveOrderToUnit local spGetUnitMoveTypeData = Spring.GetUnitMoveTypeData local spMoveCtrlGetTag = Spring.MoveCtrl.GetTag local spSetAirMoveTypeData = Spring.MoveCtrl.SetAirMoveTypeData local spSetGunshipMoveTypeData = Spring.MoveCtrl.SetGunshipMoveTypeData local spSetGroundMoveTypeData = Spring.MoveCtrl.SetGroundMoveTypeData local ALLY_ACCESS = {allied = true} local INLOS_ACCESS = {inlos = true} local getMovetype = Spring.Utilities.getMovetype local spSetUnitCOBValue = Spring.SetUnitCOBValue local COB_MAX_SPEED = COB.MAX_SPEED local WACKY_CONVERSION_FACTOR_1 = 2184.53 local CMD_WAIT = CMD.WAIT local workingGroundMoveType = true -- not ((Spring.GetModOptions() and (Spring.GetModOptions().pathfinder == "classic") and true) or false) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Sensor Handling local hasSensorOrJamm = { [ UnitDefNames['armarad'].id ] = true, [ UnitDefNames['spherecloaker'].id ] = true, [ UnitDefNames['armjamt'].id ] = true, [ UnitDefNames['armsonar'].id ] = true, [ UnitDefNames['corrad'].id ] = true, [ UnitDefNames['corawac'].id ] = true, [ UnitDefNames['reef'].id ] = true, } local radarUnitDef = {} local sonarUnitDef = {} local jammerUnitDef = {} for unitDefID,_ in pairs(hasSensorOrJamm) do local ud = UnitDefs[unitDefID] if ud.radarRadius > 0 then radarUnitDef[unitDefID] = ud.radarRadius end if ud.sonarRadius > 0 then sonarUnitDef[unitDefID] = ud.sonarRadius end if ud.jammerRadius > 0 then jammerUnitDef[unitDefID] = ud.jammerRadius end end local function UpdateSensorAndJamm(unitID, unitDefID, enabled, radarOverride, sonarOverride, jammerOverride, sightOverride) if radarUnitDef[unitDefID] or radarOverride then Spring.SetUnitSensorRadius(unitID, "radar", (enabled and (radarOverride or radarUnitDef[unitDefID])) or 0) end if sonarUnitDef[unitDefID] or sonarOverride then Spring.SetUnitSensorRadius(unitID, "sonar", (enabled and (sonarOverride or sonarUnitDef[unitDefID])) or 0) end if jammerUnitDef[unitDefID] or jammerOverride then Spring.SetUnitSensorRadius(unitID, "radarJammer", (enabled and (jammerOverride or jammerUnitDef[unitDefID])) or 0) end if sightOverride then Spring.SetUnitSensorRadius(unitID, "los", sightOverride) Spring.SetUnitSensorRadius(unitID, "airLos", sightOverride) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Build Speed Handling local origUnitBuildSpeed = {} local function updateBuildSpeed(unitID, ud, speedFactor) if ud.buildSpeed == 0 then return end local unitDefID = ud.id if not origUnitBuildSpeed[unitDefID] then origUnitBuildSpeed[unitDefID] = { buildSpeed = ud.buildSpeed, } end local state = origUnitBuildSpeed[unitDefID] spSetUnitRulesParam(unitID, "buildSpeed", state.buildSpeed*speedFactor, INLOS_ACCESS) spSetUnitBuildSpeed(unitID, state.buildSpeed*speedFactor, -- build 2*state.buildSpeed*speedFactor, -- repair state.buildSpeed*speedFactor, -- reclaim 0.5*state.buildSpeed*speedFactor) -- rezz end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Economy Handling local function updateEconomy(unitID, ud, factor) spSetUnitRulesParam(unitID,"resourceGenerationFactor", factor, INLOS_ACCESS) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Reload Time Handling local origUnitReload = {} local unitReloadPaused = {} local function updatePausedReload(unitID, unitDefID, gameFrame) local state = origUnitReload[unitDefID] for i = 1, state.weaponCount do local w = state.weapon[i] local reloadState = spGetUnitWeaponState(unitID, i , 'reloadState') if reloadState then local reloadTime = spGetUnitWeaponState(unitID, i , 'reloadTime') local newReload = 100000 -- set a high reload time so healthbars don't judder. NOTE: math.huge is TOO LARGE if reloadState < 0 then -- unit is already reloaded, so set unit to almost reloaded spSetUnitWeaponState(unitID, i, {reloadTime = newReload, reloadState = gameFrame+UPDATE_PERIOD+1}) else local nextReload = gameFrame+(reloadState-gameFrame)*newReload/reloadTime spSetUnitWeaponState(unitID, i, {reloadTime = newReload, reloadState = nextReload+UPDATE_PERIOD}) end end end end local function updateReloadSpeed(unitID, ud, speedFactor, gameFrame) local unitDefID = ud.id if not origUnitReload[unitDefID] then origUnitReload[unitDefID] = { weapon = {}, weaponCount = #ud.weapons, } local state = origUnitReload[unitDefID] for i = 1, state.weaponCount do local wd = WeaponDefs[ud.weapons[i].weaponDef] local reload = wd.reload state.weapon[i] = { reload = reload, burstRate = wd.salvoDelay, oldReloadFrames = floor(reload*30), } if wd.type == "BeamLaser" then state.weapon[i].burstRate = false -- beamlasers go screwy if you mess with their burst length end end end local state = origUnitReload[unitDefID] for i = 1, state.weaponCount do local w = state.weapon[i] local reloadState = spGetUnitWeaponState(unitID, i , 'reloadState') local reloadTime = spGetUnitWeaponState(unitID, i , 'reloadTime') if speedFactor <= 0 then if not unitReloadPaused[unitID] then local newReload = 100000 -- set a high reload time so healthbars don't judder. NOTE: math.huge is TOO LARGE unitReloadPaused[unitID] = unitDefID if reloadState < gameFrame then -- unit is already reloaded, so set unit to almost reloaded spSetUnitWeaponState(unitID, i, {reloadTime = newReload, reloadState = gameFrame+UPDATE_PERIOD+1}) else local nextReload = gameFrame+(reloadState-gameFrame)*newReload/reloadTime spSetUnitWeaponState(unitID, i, {reloadTime = newReload, reloadState = nextReload+UPDATE_PERIOD}) end -- add UPDATE_PERIOD so that the reload time never advances past what it is now end else if unitReloadPaused[unitID] then unitReloadPaused[unitID] = nil spSetUnitRulesParam(unitID, "reloadPaused", -1, INLOS_ACCESS) end local newReload = w.reload/speedFactor local nextReload = gameFrame+(reloadState-gameFrame)*newReload/reloadTime if w.burstRate then spSetUnitWeaponState(unitID, i, {reloadTime = newReload, reloadState = nextReload, burstRate = w.burstRate/speedFactor}) else spSetUnitWeaponState(unitID, i, {reloadTime = newReload, reloadState = nextReload}) end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Movement Speed Handling local origUnitSpeed = {} local function updateMovementSpeed(unitID, ud, speedFactor, turnAccelFactor, maxAccelerationFactor) local unitDefID = ud.id if not origUnitSpeed[unitDefID] then local moveData = spGetUnitMoveTypeData(unitID) origUnitSpeed[unitDefID] = { origSpeed = ud.speed, origReverseSpeed = (moveData.name == "ground") and moveData.maxReverseSpeed or ud.speed, origTurnRate = ud.turnRate, origMaxAcc = ud.maxAcc, origMaxDec = ud.maxDec, movetype = -1, } local state = origUnitSpeed[unitDefID] state.movetype = getMovetype(ud) end local state = origUnitSpeed[unitDefID] local decFactor = maxAccelerationFactor local isSlowed = speedFactor < 1 if isSlowed then -- increase brake rate to cause units to slow down to their new max speed correctly. decFactor = 1000 end if speedFactor <= 0 then speedFactor = 0 -- Set the units velocity to zero if it is attached to the ground. local x, y, z = Spring.GetUnitPosition(unitID) if x then local h = Spring.GetGroundHeight(x, z) if h and h >= y then Spring.SetUnitVelocity(unitID, 0,0,0) -- Perhaps attributes should do this: --local env = Spring.UnitScript.GetScriptEnv(unitID) --if env and env.script.StopMoving then -- Spring.UnitScript.CallAsUnit(unitID,env.script.StopMoving, hx, hy, hz) --end end end end if turnAccelFactor <= 0 then turnAccelFactor = 0 end local turnFactor = turnAccelFactor if turnFactor <= 0.001 then turnFactor = 0.001 end if maxAccelerationFactor <= 0 then maxAccelerationFactor = 0.001 end if spMoveCtrlGetTag(unitID) == nil then if state.movetype == 0 then local attribute = { maxSpeed = state.origSpeed *speedFactor, maxAcc = state.origMaxAcc *maxAccelerationFactor, --(speedFactor > 0.001 and speedFactor or 0.001) } spSetAirMoveTypeData (unitID, attribute) spSetAirMoveTypeData (unitID, attribute) elseif state.movetype == 1 then local attribute = { maxSpeed = state.origSpeed *speedFactor, --maxReverseSpeed = state.origReverseSpeed*speedFactor, turnRate = state.origTurnRate *turnFactor, accRate = state.origMaxAcc *maxAccelerationFactor, decRate = state.origMaxDec *maxAccelerationFactor } spSetGunshipMoveTypeData (unitID, attribute) elseif state.movetype == 2 then if workingGroundMoveType then local accRate = state.origMaxAcc*maxAccelerationFactor if isSlowed and accRate > speedFactor then -- Clamp acceleration to mitigate prevent brief speedup when executing new order -- 1 is here as an arbitary factor, there is no nice conversion which means that 1 is a good value. accRate = speedFactor end local attribute = { maxSpeed = state.origSpeed *speedFactor, maxReverseSpeed = (isSlowed and 0) or state.origReverseSpeed, --disallow reverse while slowed turnRate = state.origTurnRate *turnFactor, accRate = accRate, decRate = state.origMaxDec *decFactor, turnAccel = state.origTurnRate *turnAccelFactor*1.2, } spSetGroundMoveTypeData (unitID, attribute) else --Spring.Echo(state.origSpeed*speedFactor*WACKY_CONVERSION_FACTOR_1) --Spring.Echo(Spring.GetUnitCOBValue(unitID, COB_MAX_SPEED)) spSetUnitCOBValue(unitID, COB_MAX_SPEED, math.ceil(state.origSpeed*speedFactor*WACKY_CONVERSION_FACTOR_1)) end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- UnitRulesParam Handling local currentEcon = {} local currentBuildpower = {} local currentReload = {} local currentMovement = {} local currentTurn = {} local currentAcc = {} local unitSlowed = {} local unitAbilityDisabled = {} local function removeUnit(unitID) unitSlowed[unitID] = nil unitAbilityDisabled[unitID] = nil unitReloadPaused[unitID] = nil currentEcon[unitID] = nil currentBuildpower[unitID] = nil currentReload[unitID] = nil currentMovement[unitID] = nil currentTurn[unitID] = nil currentAcc[unitID] = nil end function UpdateUnitAttributes(unitID, frame) if not spValidUnitID(unitID) then removeUnit(unitID) return end local udid = spGetUnitDefID(unitID) if not udid then return end frame = frame or spGetGameFrame() local ud = UnitDefs[udid] local changedAtt = false -- Increased reload from CAPTURE -- local selfReloadSpeedChange = spGetUnitRulesParam(unitID,"selfReloadSpeedChange") local disarmed = spGetUnitRulesParam(unitID,"disarmed") or 0 local morphDisable = spGetUnitRulesParam(unitID,"morphDisable") or 0 local crashing = spGetUnitRulesParam(unitID,"crashing") or 0 -- Unit speed change (like sprint) -- local upgradesSpeedMult = spGetUnitRulesParam(unitID, "upgradesSpeedMult") local selfMoveSpeedChange = spGetUnitRulesParam(unitID, "selfMoveSpeedChange") local selfTurnSpeedChange = spGetUnitRulesParam(unitID, "selfTurnSpeedChange") local selfIncomeChange = spGetUnitRulesParam(unitID, "selfIncomeChange") local selfMaxAccelerationChange = spGetUnitRulesParam(unitID, "selfMaxAccelerationChange") --only exist in airplane?? -- SLOW -- local slowState = spGetUnitRulesParam(unitID,"slowState") local buildpowerMult = spGetUnitRulesParam(unitID, "buildpower_mult") if selfReloadSpeedChange or selfMoveSpeedChange or slowState or buildpowerMult or selfTurnSpeedChange or selfIncomeChange or disarmed or morphDisable or selfAccelerationChange then local slowMult = 1-(slowState or 0) local econMult = (slowMult)*(1 - disarmed)*(1 - morphDisable)*(selfIncomeChange or 1) local buildMult = (slowMult)*(1 - disarmed)*(1 - morphDisable)*(selfIncomeChange or 1)*(buildpowerMult or 1) local moveMult = (slowMult)*(selfMoveSpeedChange or 1)*(1 - morphDisable)*(upgradesSpeedMult or 1) local turnMult = (slowMult)*(selfMoveSpeedChange or 1)*(selfTurnSpeedChange or 1)*(1 - morphDisable) local reloadMult = (slowMult)*(selfReloadSpeedChange or 1)*(1 - disarmed)*(1 - morphDisable) local maxAccMult = (slowMult)*(selfMaxAccelerationChange or 1)*(upgradesSpeedMult or 1) -- Let other gadgets and widgets get the total effect without -- duplicating the pevious calculations. spSetUnitRulesParam(unitID, "totalReloadSpeedChange", reloadMult, INLOS_ACCESS) spSetUnitRulesParam(unitID, "totalEconomyChange", econMult, INLOS_ACCESS) spSetUnitRulesParam(unitID, "totalBuildPowerChange", buildMult, INLOS_ACCESS) spSetUnitRulesParam(unitID, "totalMoveSpeedChange", moveMult, INLOS_ACCESS) unitSlowed[unitID] = moveMult < 1 if reloadMult ~= currentReload[unitID] then updateReloadSpeed(unitID, ud, reloadMult, frame) currentReload[unitID] = reloadMult end if currentMovement[unitID] ~= moveMult or currentTurn[unitID] ~= turnMult or currentAcc[unitID] ~= maxAccMult then updateMovementSpeed(unitID, ud, moveMult, turnMult, maxAccMult*moveMult) currentMovement[unitID] = moveMult currentTurn[unitID] = turnMult currentAcc[unitID] = maxAccMult end if buildMult ~= currentBuildpower[unitID] then updateBuildSpeed(unitID, ud, buildMult) currentBuildpower[unitID] = buildMult end if econMult ~= currentEcon[unitID] then updateEconomy(unitID, ud, econMult) currentEcon[unitID] = econMult end if econMult ~= 1 or moveMult ~= 1 or reloadMult ~= 1 or turnMult ~= 1 or maxAccMult ~= 1 then changedAtt = true end else unitSlowed[unitID] = nil end local forcedOff = spGetUnitRulesParam(unitID, "forcedOff") local abilityDisabled = (forcedOff == 1 or disarmed == 1 or morphDisable == 1 or crashing == 1) local setNewState if abilityDisabled ~= unitAbilityDisabled[unitID] then spSetUnitRulesParam(unitID, "att_abilityDisabled", abilityDisabled and 1 or 0) unitAbilityDisabled[unitID] = abilityDisabled setNewState = true end if ud.shieldWeaponDef and spGetUnitRulesParam(unitID, "comm_shield_max") ~= 0 and setNewState then if abilityDisabled then Spring.SetUnitShieldState(unitID, spGetUnitRulesParam(unitID, "comm_shield_num") or -1, false) else Spring.SetUnitShieldState(unitID, spGetUnitRulesParam(unitID, "comm_shield_num") or -1, true) end end local radarOverride = spGetUnitRulesParam(unitID, "radarRangeOverride") local sonarOverride = spGetUnitRulesParam(unitID, "sonarRangeOverride") local jammerOverride = spGetUnitRulesParam(unitID, "jammingRangeOverride") local sightOverride = spGetUnitRulesParam(unitID, "sightRangeOverride") if setNewState or radarOverride or sonarOverride or jammerOverride or sightOverride then changedAtt = true UpdateSensorAndJamm(unitID, udid, not abilityDisabled, radarOverride, sonarOverride, jammerOverride, sightOverride) end local cloakBlocked = (spGetUnitRulesParam(unitID,"on_fire") == 1) or (disarmed == 1) or (morphDisable == 1) if cloakBlocked then GG.PokeDecloakUnit(unitID, 1) end -- remove the attributes if nothing is being changed if not changedAtt then removeUnit(unitID) end end function gadget:Initialize() GG.UpdateUnitAttributes = UpdateUnitAttributes end function gadget:GameFrame(f) if f % UPDATE_PERIOD == 1 then for unitID, unitDefID in pairs(unitReloadPaused) do updatePausedReload(unitID, unitDefID, f) end end end function gadget:UnitDestroyed(unitID) removeUnit(unitID) end function gadget:AllowCommand_GetWantedCommand() return true --{[CMD.ONOFF] = true, [70] = true} end function gadget:AllowCommand_GetWantedUnitDefID() return true end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if (cmdID == 70 and unitSlowed[unitID]) then return false else return true end end -- All information required for load is stored in unitRulesParams. function gadget:Load(zip) for _, unitID in ipairs(Spring.GetAllUnits()) do UpdateUnitAttributes(unitID) end end
gpl-2.0
wagonrepairer/Zero-K
units/armca.lua
2
5953
unitDef = { unitname = [[armca]], name = [[Crane]], description = [[Construction Aircraft, Builds at 4 m/s]], acceleration = 0.1, airStrafe = 0, amphibious = true, brakeRate = 0.1, buildCostEnergy = 220, buildCostMetal = 220, buildDistance = 160, builder = true, buildoptions = { }, buildPic = [[ARMCA.png]], buildRange3D = false, buildTime = 220, canFly = true, canGuard = true, canMove = true, canPatrol = true, canSubmerge = false, category = [[GUNSHIP UNARMED]], collisionVolumeOffsets = [[0 0 -5]], collisionVolumeScales = [[42 8 42]], collisionVolumeTest = 1, collisionVolumeType = [[cylY]], collide = true, corpse = [[DEAD]], cruiseAlt = 80, customParams = { airstrafecontrol = [[0]], description_bp = [[Aeronave de construç?o, constrói a 4 m/s]], description_de = [[Konstruktionsflugzeug, Baut mit 4 m/s]], description_es = [[Avión de construcción, construye a 4 m/s]], description_fr = [[Avion de Construction, Construit ? 4 m/s]], description_it = [[Aereo da costruzzione, costruisce a 4 m/s]], description_pl = [[Latajacy konstruktor, moc 4 m/s]], helptext = [[The Crane flies quickly over any terrain, but is fragile to any AA. Though it has relatively poor nano power compared to other constructors, it is able to build in many hard to reach places and expand an air players territory in a nonlinear fashion. Due to its mobility, it is ideal for reclaiming wrecks and other repetetitive tasks.]], helptext_bp = [[Crane voa rapidamente sobre qualquer terreno mas é derrubada facilmente por qualquer fogo anti-aéreo. Embora seu poder de construç?o seja ligeiramente mais baixo que o damaioria dos contrutores, sua agilidade e capacidade de voar sobre obstáculos permite a um jogador aéreo expandir seu território de forma n?o-linear. Sua mobilidade alta tamb?m a torna eficiente em reclamar destroços e outras atividades nas quais construtores terrestres gastariam mais tempo viajando que trabalhando.]], helptext_de = [[Der Crane bewegt sich flink über das Terrain, ist aber auch anfällig gegenüber AA. Obwohl er ziemlich wenig Baukraft hat, ist er in der Lage auch auf außergewöhnlichen Plätzen zu bauen. Durch seine Mobilität ist er ideal dafür geschaffen, Wracks zu absorbieren und daraus das Metall zu gewinnen.]], helptext_es = [[El Crane vuela rápidamente sobre qualquier terreno, pero es frágil a qualquier AA. Aunque tenga relativamente poco nano comparado con otros constructores, pude construir en muchos lugares inaccesibles y puede ampliar el territorio de un jugador en una manera no linear. Gracias a su mobilidad, es ideal para reclamar pecios.]], helptext_fr = [[Le Crane vole rapidement au dessus de tous les obstacles. Tr?s vuln?rable ? la d?fense a?rienne, il est id?al pour construire dans des endroits tres difficile d'acces ou pour r?cup?rer le m?tal des carcasses sur le champ de bataille.]], helptext_it = [[Il Crane vola velocemnte su qualunque terreno, ma ? fragile a qualunque AA. Anche se ha relativamente poco nano rispetto ad altri costruttori, riesce a costruire un posti inaccessibili e pu? espandere il territorio di un giocatore un una maniera non lineare. Grazie alla sua mobilit? ? ideale pere reclamare relitti.]], helptext_pl = [[Crane moze przelatywac z dosc duza predkoscia nad dowolnym terenem. Choc w porownaniu do pozostalych konstruktorow ma niska moc, jego wysoka ruchliwosc pozwala mu budowac w trudno dostepnych miejscach, szybko przeczesywac pole bitwy w poszukiwaniu zlomu i wykonywac inne wymagajace mobilnosci czynnosci.]], modelradius = [[10]], }, energyMake = 0.12, energyUse = 0, explodeAs = [[GUNSHIPEX]], floater = true, footprintX = 2, footprintZ = 2, hoverAttack = true, iconType = [[builderair]], idleAutoHeal = 5, idleTime = 1800, mass = 130, maxDamage = 240, maxVelocity = 6, metalMake = 0.12, minCloakDistance = 75, noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]], objectName = [[corvalk.s3o]], script = [[armca.lua]], seismicSignature = 0, selfDestructAs = [[GUNSHIPEX]], showNanoSpray = false, side = [[ARM]], sightDistance = 380, smoothAnim = true, terraformSpeed = 240, turnRate = 500, workerTime = 4, featureDefs = { DEAD = { description = [[Wreckage - Crane]], blocking = true, category = [[corpses]], damage = 240, energy = 0, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, height = [[40]], hitdensity = [[100]], metal = 88, object = [[corvalk_dead.s3o]], reclaimable = true, reclaimTime = 88, }, HEAP = { description = [[Debris - Crane]], blocking = false, category = [[heaps]], damage = 240, energy = 0, footprintX = 2, footprintZ = 2, height = [[4]], hitdensity = [[100]], metal = 44, object = [[debris2x2b.s3o]], reclaimable = true, reclaimTime = 44, }, }, } return lowerkeys({ armca = unitDef })
gpl-2.0
matinJ/skynet
lualib/mysql.lua
31
15725
-- Copyright (C) 2012 Yichun Zhang (agentzh) -- Copyright (C) 2014 Chang Feng -- This file is modified version from https://github.com/openresty/lua-resty-mysql -- The license is under the BSD license. -- Modified by Cloud Wu (remove bit32 for lua 5.3) local socketchannel = require "socketchannel" local mysqlaux = require "mysqlaux.c" local crypt = require "crypt" local sub = string.sub local strgsub = string.gsub local strformat = string.format local strbyte = string.byte local strchar = string.char local strrep = string.rep local strunpack = string.unpack local strpack = string.pack local sha1= crypt.sha1 local setmetatable = setmetatable local error = error local tonumber = tonumber local new_tab = function (narr, nrec) return {} end local _M = { _VERSION = '0.13' } -- constants local STATE_CONNECTED = 1 local STATE_COMMAND_SENT = 2 local COM_QUERY = 0x03 local SERVER_MORE_RESULTS_EXISTS = 8 -- 16MB - 1, the default max allowed packet size used by libmysqlclient local FULL_PACKET_SIZE = 16777215 local mt = { __index = _M } -- mysql field value type converters local converters = new_tab(0, 8) for i = 0x01, 0x05 do -- tiny, short, long, float, double converters[i] = tonumber end converters[0x08] = tonumber -- long long converters[0x09] = tonumber -- int24 converters[0x0d] = tonumber -- year converters[0xf6] = tonumber -- newdecimal local function _get_byte2(data, i) return strunpack("<I2",data,i) end local function _get_byte3(data, i) return strunpack("<I3",data,i) end local function _get_byte4(data, i) return strunpack("<I4",data,i) end local function _get_byte8(data, i) return strunpack("<I8",data,i) end local function _set_byte2(n) return strpack("<I2", n) end local function _set_byte3(n) return strpack("<I3", n) end local function _set_byte4(n) return strpack("<I4", n) end local function _from_cstring(data, i) return strunpack("z", data, i) end local function _dumphex(bytes) return strgsub(bytes, ".", function(x) return strformat("%02x ", strbyte(x)) end) end local function _compute_token(password, scramble) if password == "" then return "" end --_dumphex(scramble) local stage1 = sha1(password) --print("stage1:", _dumphex(stage1) ) local stage2 = sha1(stage1) local stage3 = sha1(scramble .. stage2) local i = 0 return strgsub(stage3,".", function(x) i = i + 1 -- ~ is xor in lua 5.3 return strchar(strbyte(x) ~ strbyte(stage1, i)) end) end local function _compose_packet(self, req, size) self.packet_no = self.packet_no + 1 local packet = _set_byte3(size) .. strchar(self.packet_no) .. req return packet end local function _send_packet(self, req, size) local sock = self.sock self.packet_no = self.packet_no + 1 local packet = _set_byte3(size) .. strchar(self.packet_no) .. req return socket.write(self.sock,packet) end local function _recv_packet(self,sock) local data = sock:read( 4) if not data then return nil, nil, "failed to receive packet header: " end local len, pos = _get_byte3(data, 1) if len == 0 then return nil, nil, "empty packet" end if len > self._max_packet_size then return nil, nil, "packet size too big: " .. len end local num = strbyte(data, pos) self.packet_no = num data = sock:read(len) if not data then return nil, nil, "failed to read packet content: " end local field_count = strbyte(data, 1) local typ if field_count == 0x00 then typ = "OK" elseif field_count == 0xff then typ = "ERR" elseif field_count == 0xfe then typ = "EOF" elseif field_count <= 250 then typ = "DATA" end return data, typ end local function _from_length_coded_bin(data, pos) local first = strbyte(data, pos) if not first then return nil, pos end if first >= 0 and first <= 250 then return first, pos + 1 end if first == 251 then return nil, pos + 1 end if first == 252 then pos = pos + 1 return _get_byte2(data, pos) end if first == 253 then pos = pos + 1 return _get_byte3(data, pos) end if first == 254 then pos = pos + 1 return _get_byte8(data, pos) end return false, pos + 1 end local function _from_length_coded_str(data, pos) local len len, pos = _from_length_coded_bin(data, pos) if len == nil then return nil, pos end return sub(data, pos, pos + len - 1), pos + len end local function _parse_ok_packet(packet) local res = new_tab(0, 5) local pos res.affected_rows, pos = _from_length_coded_bin(packet, 2) res.insert_id, pos = _from_length_coded_bin(packet, pos) res.server_status, pos = _get_byte2(packet, pos) res.warning_count, pos = _get_byte2(packet, pos) local message = sub(packet, pos) if message and message ~= "" then res.message = message end return res end local function _parse_eof_packet(packet) local pos = 2 local warning_count, pos = _get_byte2(packet, pos) local status_flags = _get_byte2(packet, pos) return warning_count, status_flags end local function _parse_err_packet(packet) local errno, pos = _get_byte2(packet, 2) local marker = sub(packet, pos, pos) local sqlstate if marker == '#' then -- with sqlstate pos = pos + 1 sqlstate = sub(packet, pos, pos + 5 - 1) pos = pos + 5 end local message = sub(packet, pos) return errno, message, sqlstate end local function _parse_result_set_header_packet(packet) local field_count, pos = _from_length_coded_bin(packet, 1) local extra extra = _from_length_coded_bin(packet, pos) return field_count, extra end local function _parse_field_packet(data) local col = new_tab(0, 2) local catalog, db, table, orig_table, orig_name, charsetnr, length local pos catalog, pos = _from_length_coded_str(data, 1) db, pos = _from_length_coded_str(data, pos) table, pos = _from_length_coded_str(data, pos) orig_table, pos = _from_length_coded_str(data, pos) col.name, pos = _from_length_coded_str(data, pos) orig_name, pos = _from_length_coded_str(data, pos) pos = pos + 1 -- ignore the filler charsetnr, pos = _get_byte2(data, pos) length, pos = _get_byte4(data, pos) col.type = strbyte(data, pos) --[[ pos = pos + 1 col.flags, pos = _get_byte2(data, pos) col.decimals = strbyte(data, pos) pos = pos + 1 local default = sub(data, pos + 2) if default and default ~= "" then col.default = default end --]] return col end local function _parse_row_data_packet(data, cols, compact) local pos = 1 local ncols = #cols local row if compact then row = new_tab(ncols, 0) else row = new_tab(0, ncols) end for i = 1, ncols do local value value, pos = _from_length_coded_str(data, pos) local col = cols[i] local typ = col.type local name = col.name if value ~= nil then local conv = converters[typ] if conv then value = conv(value) end end if compact then row[i] = value else row[name] = value end end return row end local function _recv_field_packet(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end if typ ~= 'DATA' then return nil, "bad field packet type: " .. typ end -- typ == 'DATA' return _parse_field_packet(packet) end local function _recv_decode_packet_resp(self) return function(sock) -- don't return more than 2 results return true, (_recv_packet(self,sock)) end end local function _recv_auth_resp(self) return function(sock) local packet, typ, err = _recv_packet(self,sock) if not packet then --print("recv auth resp : failed to receive the result packet") error ("failed to receive the result packet"..err) --return nil,err end if typ == 'ERR' then local errno, msg, sqlstate = _parse_err_packet(packet) error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) --return nil, errno,msg, sqlstate end if typ == 'EOF' then error "old pre-4.1 authentication protocol not supported" end if typ ~= 'OK' then error "bad packet type: " end return true, true end end local function _mysql_login(self,user,password,database) return function(sockchannel) local packet, typ, err = sockchannel:response( _recv_decode_packet_resp(self) ) --local aat={} if not packet then error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end self.protocol_ver = strbyte(packet) local server_ver, pos = _from_cstring(packet, 2) if not server_ver then error "bad handshake initialization packet: bad server version" end self._server_ver = server_ver local thread_id, pos = _get_byte4(packet, pos) local scramble1 = sub(packet, pos, pos + 8 - 1) if not scramble1 then error "1st part of scramble not found" end pos = pos + 9 -- skip filler -- two lower bytes self._server_capabilities, pos = _get_byte2(packet, pos) self._server_lang = strbyte(packet, pos) pos = pos + 1 self._server_status, pos = _get_byte2(packet, pos) local more_capabilities more_capabilities, pos = _get_byte2(packet, pos) self._server_capabilities = self._server_capabilities|more_capabilities<<16 local len = 21 - 8 - 1 pos = pos + 1 + 10 local scramble_part2 = sub(packet, pos, pos + len - 1) if not scramble_part2 then error "2nd part of scramble not found" end local scramble = scramble1..scramble_part2 local token = _compute_token(password, scramble) local client_flags = 260047; local req = strpack("<I4I4c24zs1z", client_flags, self._max_packet_size, strrep("\0", 24), -- TODO: add support for charset encoding user, token, database) local packet_len = #req local authpacket=_compose_packet(self,req,packet_len) return sockchannel:request(authpacket,_recv_auth_resp(self)) end end local function _compose_query(self, query) self.packet_no = -1 local cmd_packet = strchar(COM_QUERY) .. query local packet_len = 1 + #query local querypacket = _compose_packet(self, cmd_packet, packet_len) return querypacket end local function read_result(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err --error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end if typ == 'OK' then local res = _parse_ok_packet(packet) if res and res.server_status&SERVER_MORE_RESULTS_EXISTS ~= 0 then return res, "again" end return res end if typ ~= 'DATA' then return nil, "packet type " .. typ .. " not supported" --error( "packet type " .. typ .. " not supported" ) end -- typ == 'DATA' local field_count, extra = _parse_result_set_header_packet(packet) local cols = new_tab(field_count, 0) for i = 1, field_count do local col, err, errno, sqlstate = _recv_field_packet(self, sock) if not col then return nil, err, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end cols[i] = col end local packet, typ, err = _recv_packet(self, sock) if not packet then --error( err) return nil, err end if typ ~= 'EOF' then --error ( "unexpected packet type " .. typ .. " while eof packet is ".. "expected" ) return nil, "unexpected packet type " .. typ .. " while eof packet is ".. "expected" end -- typ == 'EOF' local compact = self.compact local rows = new_tab( 4, 0) local i = 0 while true do packet, typ, err = _recv_packet(self, sock) if not packet then --error (err) return nil, err end if typ == 'EOF' then local warning_count, status_flags = _parse_eof_packet(packet) if status_flags&SERVER_MORE_RESULTS_EXISTS ~= 0 then return rows, "again" end break end -- if typ ~= 'DATA' then -- return nil, 'bad row packet type: ' .. typ -- end -- typ == 'DATA' local row = _parse_row_data_packet(packet, cols, compact) i = i + 1 rows[i] = row end return rows end local function _query_resp(self) return function(sock) local res, err, errno, sqlstate = read_result(self,sock) if not res then local badresult ={} badresult.badresult = true badresult.err = err badresult.errno = errno badresult.sqlstate = sqlstate return true , badresult end if err ~= "again" then return true, res end local mulitresultset = {res} mulitresultset.mulitresultset = true local i =2 while err =="again" do res, err, errno, sqlstate = read_result(self,sock) if not res then return true, mulitresultset end mulitresultset[i]=res i=i+1 end return true, mulitresultset end end function _M.connect( opts) local self = setmetatable( {}, mt) local max_packet_size = opts.max_packet_size if not max_packet_size then max_packet_size = 1024 * 1024 -- default 1 MB end self._max_packet_size = max_packet_size self.compact = opts.compact_arrays local database = opts.database or "" local user = opts.user or "" local password = opts.password or "" local channel = socketchannel.channel { host = opts.host, port = opts.port or 3306, auth = _mysql_login(self,user,password,database ), } -- try connect first only once channel:connect(true) self.sockchannel = channel return self end function _M.disconnect(self) self.sockchannel:close() setmetatable(self, nil) end function _M.query(self, query) local querypacket = _compose_query(self, query) local sockchannel = self.sockchannel if not self.query_resp then self.query_resp = _query_resp(self) end return sockchannel:request( querypacket, self.query_resp ) end function _M.server_ver(self) return self._server_ver end function _M.quote_sql_str( str) return mysqlaux.quote_sql_str(str) end function _M.set_compact_arrays(self, value) self.compact = value end return _M
mit
obsy/luci
applications/luci-app-dump1090/luasrc/model/cbi/dump1090.lua
30
7206
-- Copyright 2014-2015 Álvaro Fernández Rojas <noltari@gmail.com> -- Licensed to the public under the Apache License 2.0. m = Map("dump1090", "dump1090", translate("dump1090 is a Mode S decoder specifically designed for RTLSDR devices, here you can configure the settings.")) s = m:section(TypedSection, "dump1090", "") s.addremove = true s.anonymous = false enable=s:option(Flag, "disabled", translate("Enabled")) enable.enabled="0" enable.disabled="1" enable.default = "1" enable.rmempty = false respawn=s:option(Flag, "respawn", translate("Respawn")) respawn.default = false device_index=s:option(Value, "device_index", translate("RTL device index")) device_index.rmempty = true device_index.datatype = "uinteger" gain=s:option(Value, "gain", translate("Gain (-10 for auto-gain)")) gain.rmempty = true gain.datatype = "integer" enable_agc=s:option(Flag, "enable_agc", translate("Enable automatic gain control")) enable_agc.default = false freq=s:option(Value, "freq", translate("Frequency")) freq.rmempty = true freq.datatype = "uinteger" ifile=s:option(Value, "ifile", translate("Data file")) ifile.rmempty = true ifile.datatype = "file" iformat=s:option(ListValue, "iformat", translate("Sample format for data file")) iformat:value("", translate("Default")) iformat:value("UC8") iformat:value("SC16") iformat:value("SC16Q11") throttle=s:option(Flag, "throttle", translate("When reading from a file play back in realtime, not at max speed")) throttle.default = false raw=s:option(Flag, "raw", translate("Show only messages hex values")) raw.default = false net=s:option(Flag, "net", translate("Enable networking")) modeac=s:option(Flag, "modeac", translate("Enable decoding of SSR Modes 3/A & 3/C")) modeac.default = false net_beast=s:option(Flag, "net_beast", translate("TCP raw output in Beast binary format")) net_beast.default = false net_only=s:option(Flag, "net_only", translate("Enable just networking, no RTL device or file used")) net_only.default = false net_bind_address=s:option(Value, "net_bind_address", translate("IP address to bind to")) net_bind_address.rmempty = true net_bind_address.datatype = "ipaddr" net_http_port=s:option(Value, "net_http_port", translate("HTTP server port")) net_http_port.rmempty = true net_http_port.datatype = "port" net_ri_port=s:option(Value, "net_ri_port", translate("TCP raw input listen port")) net_ri_port.rmempty = true net_ri_port.datatype = "port" net_ro_port=s:option(Value, "net_ro_port", translate("TCP raw output listen port")) net_ro_port.rmempty = true net_ro_port.datatype = "port" net_sbs_port=s:option(Value, "net_sbs_port", translate("TCP BaseStation output listen port")) net_sbs_port.rmempty = true net_sbs_port.datatype = "port" net_bi_port=s:option(Value, "net_bi_port", translate("TCP Beast input listen port")) net_bi_port.rmempty = true net_bi_port.datatype = "port" net_bo_port=s:option(Value, "net_bo_port", translate("TCP Beast output listen port")) net_bo_port.rmempty = true net_bo_port.datatype = "port" net_fatsv_port=s:option(Value, "net_fatsv_port", translate("FlightAware TSV output port")) net_fatsv_port.rmempty = true net_fatsv_port.datatype = "port" net_ro_size=s:option(Value, "net_ro_size", translate("TCP raw output minimum size")) net_ro_size.rmempty = true net_ro_size.datatype = "uinteger" net_ro_interval=s:option(Value, "net_ro_interval", translate("TCP raw output memory flush rate in seconds")) net_ro_interval.rmempty = true net_ro_interval.datatype = "uinteger" net_heartbeat=s:option(Value, "net_heartbeat", translate("TCP heartbeat rate in seconds")) net_heartbeat.rmempty = true net_heartbeat.datatype = "uinteger" net_buffer=s:option(Value, "net_buffer", translate("TCP buffer size 64Kb * (2^n)")) net_buffer.rmempty = true net_buffer.datatype = "uinteger" net_verbatim=s:option(Flag, "net_verbatim", translate("Do not apply CRC corrections to messages we forward")) net_verbatim.default = false forward_mlat=s:option(Flag, "forward_mlat", translate("Allow forwarding of received mlat results to output ports")) forward_mlat.default = false lat=s:option(Value, "lat", translate("Reference/receiver latitude for surface posn")) lat.rmempty = true lat.datatype = "float" lon=s:option(Value, "lon", translate("Reference/receiver longitude for surface posn")) lon.rmempty = true lon.datatype = "float" max_range=s:option(Value, "max_range", translate("Absolute maximum range for position decoding")) max_range.rmempty = true max_range.datatype = "uinteger" fix=s:option(Flag, "fix", translate("Enable single-bits error correction using CRC")) fix.default = false no_fix=s:option(Flag, "no_fix", translate("Disable single-bits error correction using CRC")) no_fix.default = false no_crc_check=s:option(Flag, "no_crc_check", translate("Disable messages with broken CRC")) no_crc_check.default = false phase_enhance=s:option(Flag, "phase_enhance", translate("Enable phase enhancement")) phase_enhance.default = false agressive=s:option(Flag, "agressive", translate("More CPU for more messages")) agressive.default = false mlat=s:option(Flag, "mlat", translate("Display raw messages in Beast ascii mode")) mlat.default = false stats=s:option(Flag, "stats", translate("Print stats at exit")) stats.default = false stats_range=s:option(Flag, "stats_range", translate("Collect/show range histogram")) stats_range.default = false stats_every=s:option(Value, "stats_every", translate("Show and reset stats every seconds")) stats_every.rmempty = true stats_every.datatype = "uinteger" onlyaddr=s:option(Flag, "onlyaddr", translate("Show only ICAO addresses")) onlyaddr.default = false metric=s:option(Flag, "metric", translate("Use metric units")) metric.default = false snip=s:option(Value, "snip", translate("Strip IQ file removing samples")) snip.rmempty = true snip.datatype = "uinteger" debug_mode=s:option(Value, "debug", translate("Debug mode flags")) debug_mode.rmempty = true ppm=s:option(Value, "ppm", translate("Set receiver error in parts per million")) ppm.rmempty = true ppm.datatype = "uinteger" html_dir=s:option(Value, "html_dir", translate("Base directory for the internal HTTP server")) html_dir.rmempty = true html_dir.datatype = "directory" write_json=s:option(Value, "write_json", translate("Periodically write json output to a directory")) write_json.rmempty = true write_json.datatype = "directory" write_json_every=s:option(Flag, "write_json_every", translate("Write json output every t seconds")) write_json_every.rmempty = true write_json_every.datatype = "uinteger" json_location_accuracy=s:option(ListValue, "json_location_accuracy", translate("Accuracy of receiver location in json metadata")) json_location_accuracy:value("", translate("Default")) json_location_accuracy:value("0", "No location") json_location_accuracy:value("1", "Approximate") json_location_accuracy:value("2", "Exact") oversample=s:option(Flag, "oversample", translate("Use the 2.4MHz demodulator")) oversample.default = false dcfilter=s:option(Flag, "dcfilter", translate("Apply a 1Hz DC filter to input data")) dcfilter.default = false measure_noise=s:option(Flag, "measure_noise", translate("Measure noise power")) measure_noise.default = false return m
apache-2.0
shingenko/darkstar
scripts/zones/Ifrits_Cauldron/npcs/relic.lua
38
1848
----------------------------------- -- Area: Ifrit's Cauldron -- NPC: <this space intentionally left blank> -- @pos -18 40 20 205 ----------------------------------- package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Ifrits_Cauldron/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 18329 and trade:getItemCount() == 4 and trade:hasItemQty(18329,1) and trade:hasItemQty(1582,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1451,1)) then player:startEvent(32,18330); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 32) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18330); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1450); else player:tradeComplete(); player:addItem(18330); player:addItem(1450,30); player:messageSpecial(ITEM_OBTAINED,18330); player:messageSpecial(ITEMS_OBTAINED,1450,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
jsat97/sysdig
userspace/sysdig/chisels/iobytes_file.lua
18
1602
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/>. --]] -- Chisel description description = "Counts the total bytes read from and written to files."; short_description = "Sum of file I/O bytes"; category = "I/O"; -- Chisel argument list args = { } tot = 0 totin = 0 totout = 0 -- Initialization callback function on_init() -- Request the fields fbytes = chisel.request_field("evt.rawarg.res") ftime = chisel.request_field("evt.time.s") fisread = chisel.request_field("evt.is_io_read") -- set the filter chisel.set_filter("evt.is_io=true and fd.type=file") chisel.set_interval_s(1) return true end -- Event parsing callback function on_event() bytes = evt.field(fbytes) isread = evt.field(fisread) if bytes ~= nil and bytes > 0 then tot = tot + bytes if isread then totin = totin + bytes else totout = totout + bytes end end return true end function on_interval(delta) etime = evt.field(ftime) print(etime .. " in:" .. totin .. " out:" .. totout .. " tot:" .. tot) tot = 0 totin = 0 totout = 0 return true end
gpl-2.0
kveratis/GameCode4
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/loop/lua/loop/collection/MapWithArrayOfKeys.lua
1
2412
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Map of Objects that Keeps an Array of Key Values -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- Notes: -- -- Can only store non-numeric values. -- -- Use of key strings equal to the name of one method prevents its usage. -- -------------------------------------------------------------------------------- local rawget = rawget local table = require "table" local oo = require "loop.simple" local UnorderedArray = require "loop.collection.UnorderedArray" module("loop.collection.MapWithArrayOfKeys", oo.class) keyat = rawget function value(self, key, value) if value == nil then return self[key] else self[key] = value end end function add(self, key, value) self[#self + 1] = key self[key] = value end function addat(self, index, key, value) table.insert(self, index, key) self[key] = value end function remove(self, key) for i = 1, #self do if self[i] == key then return removeat(self, i) end end end function removeat(self, index) self[ self[index] ] = nil return UnorderedArray.remove(self, index) end function valueat(self, index, value) if value == nil then return self[ self[index] ] else self[ self[index] ] = value end end
lgpl-3.0
shingenko/darkstar
scripts/zones/Kazham-Jeuno_Airship/Zone.lua
28
1458
----------------------------------- -- -- Zone: Kazham-Jeuno_Airship -- ----------------------------------- ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) or (player:getYPos() == 0) or (player:getZPos() == 0)) then player:setPos(math.random(-4, 4),1,math.random(-23,-12)); end return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x000A); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x000A) then local prevzone = player:getPreviousZone(); if (prevzone == 250) then player:setPos(0,0,0,0,246); elseif (prevzone == 246) then player:setPos(0,0,0,0,250); end end end;
gpl-3.0