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
microcai/skynet
examples/login/gated.lua
57
2201
local msgserver = require "snax.msgserver" local crypt = require "crypt" local skynet = require "skynet" local loginservice = tonumber(...) local server = {} local users = {} local username_map = {} local internal_id = 0 -- login server disallow multi login, so login_handler never be reentry -- call by login server function server.login_handler(uid, secret) if users[uid] then error(string.format("%s is already login", uid)) end internal_id = internal_id + 1 local id = internal_id -- don't use internal_id directly local username = msgserver.username(uid, id, servername) -- you can use a pool to alloc new agent local agent = skynet.newservice "msgagent" local u = { username = username, agent = agent, uid = uid, subid = id, } -- trash subid (no used) skynet.call(agent, "lua", "login", uid, id, secret) users[uid] = u username_map[username] = u msgserver.login(username, secret) -- you should return unique subid return id end -- call by agent function server.logout_handler(uid, subid) local u = users[uid] if u then local username = msgserver.username(uid, subid, servername) assert(u.username == username) msgserver.logout(u.username) users[uid] = nil username_map[u.username] = nil skynet.call(loginservice, "lua", "logout",uid, subid) end end -- call by login server function server.kick_handler(uid, subid) local u = users[uid] if u then local username = msgserver.username(uid, subid, servername) assert(u.username == username) -- NOTICE: logout may call skynet.exit, so you should use pcall. pcall(skynet.call, u.agent, "lua", "logout") end end -- call by self (when socket disconnect) function server.disconnect_handler(username) local u = username_map[username] if u then skynet.call(u.agent, "lua", "afk") end end -- call by self (when recv a request from client) function server.request_handler(username, msg) local u = username_map[username] return skynet.tostring(skynet.rawcall(u.agent, "client", msg)) end -- call by self (when gate open) function server.register_handler(name) servername = name skynet.call(loginservice, "lua", "register_gate", servername, skynet.self()) end msgserver.start(server)
mit
jsfdez/premake-core
tests/actions/vstudio/vc200x/test_compiler_block.lua
9
13247
-- -- tests/actions/vstudio/vc200x/test_compiler_block.lua -- Validate generation the VCCLCompiler element in Visual Studio 200x C/C++ projects. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local suite = test.declare("vs200x_compiler_block") local vc200x = premake.vstudio.vc200x -- -- Setup/teardown -- local wks, prj function suite.setup() _ACTION = "vs2008" wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") vc200x.VCCLCompilerTool(cfg) end -- -- Verify the basic structure of the compiler block with no flags or settings. -- function suite.looksGood_onDefaultSettings() prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- If include directories are specified, the <AdditionalIncludeDirectories> should be added. -- function suite.additionalIncludeDirs_onIncludeDirs() includedirs { "include/lua", "include/zlib" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="include\lua;include\zlib" ]] end -- -- Ensure macros are not truncated (see issue #63) -- function suite.additionalIncludeDirs_onIncludeDirs_with_vs_macros() includedirs { "$(Macro1)/foo/bar/$(Macro2)/baz" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="$(Macro1)\foo\bar\$(Macro2)\baz" ]] end -- -- Verify the handling of the Symbols flag. The format must be set, and the -- debug runtime library must be selected. -- function suite.looksGood_onSymbolsFlag() flags "Symbols" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Verify the handling of the Symbols in conjunction with the Optimize flag. -- The release runtime library must be used. -- function suite.looksGood_onSymbolsAndOptimizeFlags() flags { "Symbols" } optimize "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="3" /> ]] end -- -- Verify the handling of the C7 debug information format. -- function suite.looksGood_onC7DebugFormat() flags "Symbols" debugformat "C7" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="1" /> ]] end --- -- Test precompiled header handling; the header should be treated as -- a plain string value, with no path manipulation applied, since it -- needs to match the value of the #include statement used in the -- project code. --- function suite.compilerBlock_OnPCH() location "build" pchheader "include/common.h" pchsource "source/common.cpp" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="2" PrecompiledHeaderThrough="include/common.h" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Floating point flag tests -- function suite.compilerBlock_OnFpFast() floatingpoint "Fast" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" FloatingPointModel="2" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end function suite.compilerBlock_OnFpStrict() floatingpoint "Strict" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" FloatingPointModel="1" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check that the "minimal rebuild" flag is applied correctly. -- function suite.minimalRebuildFlagsSet_onMinimalRebuildAndSymbols() flags { "Symbols", "NoMinimalRebuild" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Check that the "no buffer security check" flag is applied correctly. -- function suite.noBufferSecurityFlagSet_onBufferSecurityCheck() flags { "NoBufferSecurityCheck" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" BufferSecurityCheck="false" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check that the CompileAs value is set correctly for C language projects. -- function suite.compileAsSet_onC() language "C" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" CompileAs="1" /> ]] end -- -- Verify the correct runtime library is used when symbols are enabled. -- function suite.runtimeLibraryIsDebug_onSymbolsNoOptimize() flags { "Symbols" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Verify the correct warnings settings are used when extra warnings are enabled. -- function suite.runtimeLibraryIsDebug_onExtraWarnings() warnings "Extra" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="4" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when FatalWarnings are enabled. -- function suite.runtimeLibraryIsDebug_onFatalWarnings() flags { "FatalWarnings" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" WarnAsError="true" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when no warnings are enabled. -- function suite.runtimeLibraryIsDebug_onNoWarnings_whichDisablesAllOtherWarningsFlags() flags { "FatalWarnings" } warnings "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="0" DebugInformationFormat="0" /> ]] end -- -- Verify the correct Detect64BitPortabilityProblems settings are used when _ACTION < "VS2008". -- function suite._64BitPortabilityOn_onVS2005() _ACTION = "vs2005" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="0" /> ]] end function suite._64BitPortabilityOff_onVS2005_andCLR() _ACTION = "vs2005" clr "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when no warnings are enabled. -- function suite.runtimeLibraryIsDebug_onVS2005_NoWarnings() _ACTION = "vs2005" warnings "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="0" DebugInformationFormat="0" /> ]] end -- -- Xbox 360 uses the same structure, but changes the element name. -- function suite.looksGood_onXbox360() system "Xbox360" prepare() test.capture [[ <Tool Name="VCCLX360CompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check handling of forced includes. -- function suite.forcedIncludeFiles() forceincludes { "stdafx.h", "include/sys.h" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" ForcedIncludeFiles="stdafx.h;include\sys.h" ]] end function suite.forcedUsingFiles() forceusings { "stdafx.h", "include/sys.h" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" ForcedUsingFiles="stdafx.h;include\sys.h" ]] end -- -- Verify handling of the NoRuntimeChecks flag. -- function suite.onNoRuntimeChecks() flags { "NoRuntimeChecks" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" RuntimeLibrary="2" ]] end -- -- Check handling of the EnableMultiProcessorCompile flag. -- function suite.onMultiProcessorCompile() flags { "MultiProcessorCompile" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" AdditionalOptions="/MP" Optimization="0" BasicRuntimeChecks="3" ]] end -- -- Check handling of the ReleaseRuntime flag; should override the -- default behavior of linking the debug runtime when symbols are -- enabled with no optimizations. -- function suite.releaseRuntime_onFlag() flags { "Symbols", "ReleaseRuntime" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="2" ]] end function suite.releaseRuntime_onStaticAndReleaseRuntime() flags { "Symbols", "ReleaseRuntime", "StaticRuntime" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="0" ]] end -- -- Check the LinkTimeOptimization flag. -- function suite.flags_onLinkTimeOptimization() flags { "LinkTimeOptimization" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" WholeProgramOptimization="true" ]] end -- -- Check the optimization flags. -- function suite.optimization_onOptimize() optimize "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" ]] end function suite.optimization_onOptimizeSize() optimize "Size" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="1" StringPooling="true" ]] end function suite.optimization_onOptimizeSpeed() optimize "Speed" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="2" StringPooling="true" ]] end function suite.optimization_onOptimizeFull() optimize "Full" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" ]] end function suite.optimization_onOptimizeOff() optimize "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" ]] end function suite.optimization_onOptimizeDebug() optimize "Debug" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" ]] end -- -- Check handling of the OmitDefaultLibrary flag. -- function suite.onOmitDefaultLibrary() flags { "OmitDefaultLibrary" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" OmitDefaultLibName="true" ]] end
bsd-3-clause
ArchiveTeam/adrive-grab
urlcode.lua
58
3476
---------------------------------------------------------------------------- -- Utility functions for encoding/decoding of URLs. -- -- @release $Id: urlcode.lua,v 1.10 2008/01/21 16:11:32 carregal Exp $ ---------------------------------------------------------------------------- local ipairs, next, pairs, tonumber, type = ipairs, next, pairs, tonumber, type local string = string local table = table module ("cgilua.urlcode") ---------------------------------------------------------------------------- -- Decode an URL-encoded string (see RFC 2396) ---------------------------------------------------------------------------- function unescape (str) str = string.gsub (str, "+", " ") str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end) str = string.gsub (str, "\r\n", "\n") return str end ---------------------------------------------------------------------------- -- URL-encode a string (see RFC 2396) ---------------------------------------------------------------------------- function escape (str) str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^0-9a-zA-Z ])", -- locale independent function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") return str end ---------------------------------------------------------------------------- -- Insert a (name=value) pair into table [[args]] -- @param args Table to receive the result. -- @param name Key for the table. -- @param value Value for the key. -- Multi-valued names will be represented as tables with numerical indexes -- (in the order they came). ---------------------------------------------------------------------------- function insertfield (args, name, value) if not args[name] then args[name] = value else local t = type (args[name]) if t == "string" then args[name] = { args[name], value, } elseif t == "table" then table.insert (args[name], value) else error ("CGILua fatal error (invalid args table)!") end end end ---------------------------------------------------------------------------- -- Parse url-encoded request data -- (the query part of the script URL or url-encoded post data) -- -- Each decoded (name=value) pair is inserted into table [[args]] -- @param query String to be parsed. -- @param args Table where to store the pairs. ---------------------------------------------------------------------------- function parsequery (query, args) if type(query) == "string" then local insertfield, unescape = insertfield, unescape string.gsub (query, "([^&=]+)=([^&=]*)&?", function (key, val) insertfield (args, unescape(key), unescape(val)) end) end end ---------------------------------------------------------------------------- -- URL-encode the elements of a table creating a string to be used in a -- URL for passing data/parameters to another script -- @param args Table where to extract the pairs (name=value). -- @return String with the resulting encoding. ---------------------------------------------------------------------------- function encodetable (args) if args == nil or next(args) == nil then -- no args or empty args? return "" end local strp = "" for key, vals in pairs(args) do if type(vals) ~= "table" then vals = {vals} end for i,val in ipairs(vals) do strp = strp.."&"..escape(key).."="..escape(val) end end -- remove first & return string.sub(strp,2) end
unlicense
Cloudef/darkstar
scripts/zones/Metalworks/npcs/Naji.lua
5
4810
----------------------------------- -- Area: Metalworks -- NPC: Naji -- Involved in Quests: The doorman (finish), Riding on the Clouds -- Involved in Mission: Bastok 6-2 -- !pos 64 -14 -4 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 6) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; function onTrigger(player,npc) if (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman, WAR AF1 player:startEvent(750); elseif (player:getCurrentMission(BASTOK) ~= 255) then local currentMission = player:getCurrentMission(BASTOK); if (currentMission == THE_ZERUHN_REPORT and player:hasKeyItem(ZERUHN_REPORT)) then if (player:seenKeyItem(ZERUHN_REPORT)) then player:startEvent(710,0); else player:startEvent(710,1); end elseif (currentMission == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then player:startEvent(711); elseif (currentMission == THE_EMISSARY and player:hasKeyItem(KINDRED_REPORT)) then player:startEvent(714); elseif (currentMission == THE_EMISSARY) then if (player:hasKeyItem(LETTER_TO_THE_CONSULS_BASTOK) == false and player:getVar("MissionStatus") == 0) then player:startEvent(713); else player:showText(npc,GOOD_LUCK); end elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK) and player:getVar("MissionStatus") == 0) then player:startEvent(720); elseif (currentMission == DARKNESS_RISING and player:getVar("MissionStatus") == 1) then player:startEvent(721); elseif (player:hasKeyItem(BURNT_SEAL)) then player:startEvent(722); elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 0) then player:startEvent(761); elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 3) then player:startEvent(762); else player:startEvent(700); end elseif (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman player:startEvent(750); else player:startEvent(700); end end; -- 0x02c6 711 700 713 714 0x02cb 0x02cd 720 721 750 0x03f0 0x03f1 761 -- 762 0x030e 0x0325 0x034d 0x036d 0x03aa 0x03ab 0x03ac 0x03ad 0x03ae 0x03cb 0x03c9 0x03ca function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 750) then if (player:getFreeSlotsCount(0) >= 1) then player:addItem(16678); player:messageSpecial(ITEM_OBTAINED, 16678); -- Razor Axe player:delKeyItem(YASINS_SWORD); player:setVar("theDoormanCS",0); player:addFame(BASTOK,30); player:completeQuest(BASTOK,THE_DOORMAN); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16678); -- Razor Axe end elseif (csid == 710) then player:delKeyItem(ZERUHN_REPORT); player:completeMission(BASTOK,THE_ZERUHN_REPORT); elseif (csid == 713) then player:addKeyItem(LETTER_TO_THE_CONSULS_BASTOK); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_CONSULS_BASTOK); player:setVar("MissionStatus",1); elseif (csid == 720 and option == 0 or csid == 721) then player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK); player:addKeyItem(NEW_FEIYIN_SEAL); player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL); player:setVar("MissionStatus",10); elseif (csid == 720 and option == 1) then player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK); player:setVar("MissionStatus",1); elseif (csid == 761) then player:setVar("MissionStatus",1); elseif (csid == 714 or csid == 722 or csid == 762) then finishMissionTimeline(player,1,csid,option); end end;
gpl-3.0
herksaw/protoquest
libs/hardoncollider/init.lua
9
9043
--[[ Copyright (c) 2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _NAME, common_local = ..., common if not (type(common) == 'table' and common.class and common.instance) then assert(common_class ~= false, 'No class commons specification available.') require(_NAME .. '.class') end local Shapes = require(_NAME .. '.shapes') local Spatialhash = require(_NAME .. '.spatialhash') -- reset global table `common' (required by class commons) if common_local ~= common then common_local, common = common, common_local end local newPolygonShape = Shapes.newPolygonShape local newCircleShape = Shapes.newCircleShape local newPointShape = Shapes.newPointShape local function __NULL__() end local HC = {} function HC:init(cell_size, callback_collide, callback_stop) self._active_shapes = {} self._passive_shapes = {} self._ghost_shapes = {} self.groups = {} self._colliding_only_last_frame = {} self.on_collide = callback_collide or __NULL__ self.on_stop = callback_stop or __NULL__ self._hash = common_local.instance(Spatialhash, cell_size) end function HC:clear() self._active_shapes = {} self._passive_shapes = {} self._ghost_shapes = {} self.groups = {} self._colliding_only_last_frame = {} self._hash = common_local.instance(Spatialhash, self._hash.cell_size) return self end function HC:setCallbacks(collide, stop) if type(collide) == "table" and not (getmetatable(collide) or {}).__call then stop = collide.stop collide = collide.collide end if collide then assert(type(collide) == "function" or (getmetatable(collide) or {}).__call, "collision callback must be a function or callable table") self.on_collide = collide end if stop then assert(type(stop) == "function" or (getmetatable(stop) or {}).__call, "stop callback must be a function or callable table") self.on_stop = stop end return self end function HC:addShape(shape) assert(shape.bbox and shape.collidesWith, "Cannot add custom shape: Incompatible shape.") self._active_shapes[shape] = shape self._hash:insert(shape, shape:bbox()) shape._groups = {} local hash = self._hash local move, rotate,scale = shape.move, shape.rotate, shape.scale for _, func in ipairs{'move', 'rotate', 'scale'} do local old_func = shape[func] shape[func] = function(self, ...) local x1,y1,x2,y2 = self:bbox() old_func(self, ...) local x3,y3,x4,y4 = self:bbox() hash:update(self, x1,y1, x2,y2, x3,y3, x4,y4) end end function shape:_removeFromHash() shape.move, shape.rotate, shape.scale = move, rotate, scale return hash:remove(shape, self:bbox()) end function shape:neighbors() local neighbors = hash:inRange(self:bbox()) rawset(neighbors, self, nil) return neighbors end function shape:inGroup(group) return self._groups[group] end return shape end function HC:activeShapes() return pairs(self._active_shapes) end function HC:shapesInRange(x1,y1, x2,y2) return self._hash:inRange(x1,y1, x2,y2) end function HC:addPolygon(...) return self:addShape(newPolygonShape(...)) end function HC:addRectangle(x,y,w,h) return self:addPolygon(x,y, x+w,y, x+w,y+h, x,y+h) end function HC:addCircle(cx, cy, radius) return self:addShape(newCircleShape(cx,cy, radius)) end function HC:addPoint(x,y) return self:addShape(newPointShape(x,y)) end function HC:share_group(shape, other) for name,group in pairs(shape._groups) do if group[other] then return true end end return false end -- check for collisions function HC:update(dt) -- cache for tested/colliding shapes local tested, colliding = {}, {} local function may_skip_test(shape, other) return (shape == other) or (tested[other] and tested[other][shape]) or self._ghost_shapes[other] or self:share_group(shape, other) end -- collect active shapes. necessary, because a callback might add shapes to -- _active_shapes, which will lead to undefined behavior (=random crashes) in -- next() local active = {} for shape in self:activeShapes() do active[shape] = shape end local only_last_frame = self._colliding_only_last_frame for shape in pairs(active) do tested[shape] = {} for other in self._hash:rangeIter(shape:bbox()) do if not self._active_shapes[shape] then -- break out of this loop is shape was removed in a callback break end if not may_skip_test(shape, other) then local collide, sx,sy = shape:collidesWith(other) if collide then if not colliding[shape] then colliding[shape] = {} end colliding[shape][other] = {sx, sy} -- flag shape colliding this frame and call collision callback if only_last_frame[shape] then only_last_frame[shape][other] = nil end self.on_collide(dt, shape, other, sx, sy) end tested[shape][other] = true end end end -- call stop callback on shapes that do not collide anymore for a,reg in pairs(only_last_frame) do for b, info in pairs(reg) do self.on_stop(dt, a, b, info[1], info[2]) end end self._colliding_only_last_frame = colliding end -- get list of shapes at point (x,y) function HC:shapesAt(x, y) local shapes = {} for s in pairs(self._hash:cellAt(x,y)) do if s:contains(x,y) then shapes[#shapes+1] = s end end return shapes end -- remove shape from internal tables and the hash function HC:remove(shape, ...) if not shape then return end self._active_shapes[shape] = nil self._passive_shapes[shape] = nil self._ghost_shapes[shape] = nil for name, group in pairs(shape._groups) do group[shape] = nil end shape:_removeFromHash() return self:remove(...) end -- group support function HC:addToGroup(group, shape, ...) if not shape then return end assert(self._active_shapes[shape] or self._passive_shapes[shape], "Shape is not registered with HC") if not self.groups[group] then self.groups[group] = {} end self.groups[group][shape] = true shape._groups[group] = self.groups[group] return self:addToGroup(group, ...) end function HC:removeFromGroup(group, shape, ...) if not shape or not self.groups[group] then return end assert(self._active_shapes[shape] or self._passive_shapes[shape], "Shape is not registered with HC") self.groups[group][shape] = nil shape._groups[group] = nil return self:removeFromGroup(group, ...) end function HC:setPassive(shape, ...) if not shape then return end if not self._ghost_shapes[shape] then assert(self._active_shapes[shape], "Shape is not active") self._active_shapes[shape] = nil self._passive_shapes[shape] = shape end return self:setPassive(...) end function HC:setActive(shape, ...) if not shape then return end if not self._ghost_shapes[shape] then assert(self._passive_shapes[shape], "Shape is not passive") self._active_shapes[shape] = shape self._passive_shapes[shape] = nil end return self:setActive(...) end function HC:setGhost(shape, ...) if not shape then return end assert(self._active_shapes[shape] or self._passive_shapes[shape], "Shape is not registered with HC") self._active_shapes[shape] = nil -- dont remove from passive shapes, see below self._ghost_shapes[shape] = shape return self:setGhost(...) end function HC:setSolid(shape, ...) if not shape then return end assert(self._ghost_shapes[shape], "Shape not a ghost") -- re-register shape. passive shapes were not unregistered above, so if a shape -- is not passive, it must be registered as active again. if not self._passive_shapes[shape] then self._active_shapes[shape] = shape end self._ghost_shapes[shape] = nil return self:setSolid(...) end -- the module HC = common_local.class("HardonCollider", HC) local function new(...) return common_local.instance(HC, ...) end return setmetatable({HardonCollider = HC, new = new}, {__call = function(_,...) return new(...) end})
mit
nevercast/cuberite
MCServer/Plugins/APIDump/Hooks/OnKilling.lua
36
1190
return { HOOK_KILLING = { CalledWhen = "A player or a mob is dying.", DefaultFnName = "OnKilling", -- also used as pagename Desc = [[ This hook is called whenever a {{cPawn|pawn}}'s (a player's or a mob's) health reaches zero. This means that the pawn is about to be killed, unless a plugin "revives" them by setting their health back to a positive value. ]], Params = { { Name = "Victim", Type = "{{cPawn}}", Notes = "The player or mob that is about to be killed" }, { Name = "Killer", Type = "{{cEntity}}", Notes = "The entity that has caused the victim to lose the last point of health. May be nil for environment damage" }, { Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "The damage type, cause and effects." }, }, Returns = [[ If the function returns false or no value, Cuberite calls other plugins with this event. If the function returns true, no other plugin is called for this event.</p> <p> In either case, the victim's health is then re-checked and if it is greater than zero, the victim is "revived" with that health amount. If the health is less or equal to zero, the victim is killed. ]], }, -- HOOK_KILLING }
apache-2.0
romonzaman/newfies-dialer
lua/libs/uuid4.lua
12
3046
--[[ The MIT License (MIT) Copyright (c) 2012 Toby Jennings Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local M = {} ----- math.randomseed( os.time() ) math.random() ----- local function num2bs(num) local _mod = math.fmod or math.mod local _floor = math.floor -- local result = "" if(num == 0) then return "0" end while(num > 0) do result = _mod(num,2) .. result num = _floor(num*0.5) end return result end -- local function bs2num(num) local _sub = string.sub local index, result = 0, 0 if(num == "0") then return 0; end for p=#num,1,-1 do local this_val = _sub( num, p,p ) if this_val == "1" then result = result + ( 2^index ) end index=index+1 end return result end -- local function padbits(num,bits) if #num == bits then return num end if #num > bits then print("too many bits") end local pad = bits - #num for i=1,pad do num = "0" .. num end return num end -- local function getUUID() local _rnd = math.random local _fmt = string.format -- _rnd() -- local time_low_a = _rnd(0, 65535) local time_low_b = _rnd(0, 65535) -- local time_mid = _rnd(0, 65535) -- local time_hi = _rnd(0, 4095 ) time_hi = padbits( num2bs(time_hi), 12 ) local time_hi_and_version = bs2num( "0100" .. time_hi ) -- local clock_seq_hi_res = _rnd(0,63) clock_seq_hi_res = padbits( num2bs(clock_seq_hi_res), 6 ) clock_seq_hi_res = "10" .. clock_seq_hi_res -- local clock_seq_low = _rnd(0,255) clock_seq_low = padbits( num2bs(clock_seq_low), 8 ) -- local clock_seq = bs2num(clock_seq_hi_res .. clock_seq_low) -- local node = {} for i=1,6 do node[i] = _rnd(0,255) end -- local guid = "" guid = guid .. padbits(_fmt("%X",time_low_a), 4) guid = guid .. padbits(_fmt("%X",time_low_b), 4) .. "-" guid = guid .. padbits(_fmt("%X",time_mid), 4) .. "-" guid = guid .. padbits(_fmt("%X",time_hi_and_version), 4) .. "-" guid = guid .. padbits(_fmt("%X",clock_seq), 4) .. "-" -- for i=1,6 do guid = guid .. padbits(_fmt("%X",node[i]), 2) end -- return guid end -- M.getUUID = getUUID return M
mpl-2.0
fiallo1313veeee/Anti_bot
plugins/dictionary.lua
9
1631
--[[ -- 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 "en", 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 some text", usage = { "[/!]trans text. Translate the text to English.", "[/!]trans target_lang text.", "[/!]trans source,target text", }, patterns = { "^[/!]trans ([%w]+),([%a]+) (.+)", "^[/!]trans ([%w]+) (.+)", "^[/!]trans (.+)", }, run = run } end
gpl-2.0
letoram/durden
durden/uiprim/popup.lua
1
12023
-- Copyright 2019, Björn Ståhl -- License: 3-Clause BSD -- Reference: http://durden.arcan-fe.com -- Description: UI primitive for spawning a simple popup menu. -- Dependencies: assumes builtin/mouse.lua is loaded and active. -- Limitations: -- * Does not implement scrolling, assumes all entries fits inside buffer, -- (though could be added using the step_group setup) -- * Menu contents is static, activation collapses all. -- * Does not implement submenu spawning or positioning -- Notes: -- * suppl_setup_mousegrab can be used to capture mouse input outside local spawn_popup -- entry point used for testing as an appl of its own, -- and an example of how to set it up and use it if (APPLID == "uiprim_popup_test") then _G[APPLID] = function (arguments) system_load("builtin/mouse.lua")() local cursor = fill_surface(8, 8, 0, 255, 0); mouse_setup(cursor, 65535, 1, true); system_defaultfont("default.ttf", 12, 1) local list = { { label = "this", kind = "action", eval = function() return true end, handler = function() print("this entered"); end }, { label = "is not", kind = "action", handler = function() return { { label = "an exit", kind = "action", eval = function() return false end, handler = function() print("ebichuman") end } } end, submenu = true } } if #arguments > 0 then for i,v in ipairs(arguments) do table.insert(list, { name = string.lower(v), label = v, kind = "action", eval = function() return i % 2 ~= 0 end, handler = function() print(v) end }) end end SYMTABLE = system_load("builtin/keyboard.lua")() -- simple border example, just adds a fill-rate burning double+ csurf local popup = spawn_popup(list, { border_attach = function(tbl, anchor) local bw = 1 local props = image_surface_resolve(anchor) local frame = color_surface( props.width + 4 * bw, props.height + 4 * bw, 0xaa, 0xaa, 0xaa) local bg = color_surface( props.width + 2 * bw, props.height + 2 * bw, 0x22, 0x22, 0x22) show_image({frame, bg}) link_image(frame, anchor) link_image(bg, anchor) move_image(frame, -2 * bw, -2 * bw) move_image(bg, -bw, -bw) image_inherit_order(frame, true) image_inherit_order(bg, true) order_image(frame, -2) order_image(bg, -1) image_mask_set(frame, MASK_UNPICKABLE) image_mask_set(bg, MASK_UNPICKABLE) order_image(anchor, 10) end }) move_image(popup.anchor, 50, 50) if not popup then return shutdown("couldn't build popup", EXIT_FAILURE) end local dispatch = { ["UP"] = function() popup:step_up() end, ["DOWN"] = function() popup:step_down() end, ["ESCAPE"] = function() shutdown() end } uiprim_popup_test_input = function(iotbl) if iotbl.mouse then mouse_iotbl_input(iotbl); elseif iotbl.translated and iotbl.active then local sym, _ = SYMTABLE:patch(iotbl) if (dispatch[sym]) then dispatch[sym]() end end end end end -- manual / button triggered cursor navigation, just step up -- until we reach the last active item and stay there, if not -- possible the cursor will be hidden local function step_up(ctx) for i=1,#ctx.menu do ctx.index = ctx.index - 1 if ctx.index == 0 then ctx.index = #ctx.menu end if ctx.menu[ctx.index].active then ctx:set_index(ctx.index) return end end ctx:set_index(1) end local function step_dn(ctx) for i=1,#ctx.menu do ctx.index = ctx.index + 1 if ctx.index > #ctx.menu then ctx.index = 1 end if ctx.menu[ctx.index].active then ctx:set_index(ctx.index) return end end ctx:set_index(1) end local function menu_to_fmtstr(menu, options) local text_list = {} local sym_list = {} local text_valid = options.text_valid or "\\f,0\\#ffffff" local text_invalid = options.text_invalid or "\\f,0\\#999999" local text_menu = options.text_menu or "\f,0\\#aaaaaa" for i,v in ipairs(menu) do local fmt_suffix = i > 1 and [[\n\r]] or "" local prefix local suffix = "" if not v.active then prefix = text_invalid elseif v.submenu then prefix = text_menu suffix = options.text_menu_suf and options.text_menu_suf or "" else prefix = text_valid end if v.format then prefix = prefix .. v.format end table.insert(text_list, prefix .. fmt_suffix) table.insert(text_list, v.label .. suffix) table.insert(sym_list, v.shortcut and v.shortcut or "") end return text_list, sym_list end local function set_index(ctx, i) if i < 1 or i > #ctx.menu then return end ctx.index = i -- it would possibly be nicer to have the 'invert' effect that some -- toolkits provide, but it is a bit of a hassle unless we can do it -- with a shader setting start-end s,t and simply modulate the color -- there. if ctx.menu[i].active then local y = ctx.line_pos[i] local h if ctx.index == #ctx.menu then h = ctx.max_h - ctx.line_pos[i] else h = ctx.line_pos[i+1] - ctx.line_pos[i] end if (valid_vid(ctx.cursor)) then blend_image(ctx.cursor, 0.5) move_image(ctx.cursor, 0, ctx.line_pos[i]) resize_image(ctx.cursor, ctx.max_w, h) end if ctx.options.cursor_at then ctx.options.cursor_at(ctx, ctx.cursor, 0, ctx.line_pos[i], ctx.max_w, h); end elseif valid_vid(ctx.cursor) then hide_image(ctx.cursor) end end local function drop(ctx) if ctx.animation_out > 0 then blend_image(ctx.anchor, 0, ctx.animation_out) expire_image(ctx.anchor, ctx.animation_out) else delete_image(ctx.anchor); end end local function cancel(ctx) if not valid_vid(ctx.anchor) then return end drop(ctx); if not ctx.in_finish and ctx.options.on_finish then ctx.options.on_finish(ctx); end end local function trigger(ctx) if not ctx.menu[ctx.index].active then return end -- let the handler determine if we are done and should be closed or not if ctx.options.on_finish then if ctx.options.on_finish(ctx, ctx.menu[ctx.index]) then return end end -- otherwise we can run it (and decide if we handle a new menu or not, -- and what method, i.e. replace current or reposition) drop(ctx); -- submenu spawn / positioning is advanced and up to the parent if ctx.menu[ctx.index].handler and not ctx.menu[ctx.index].submenu then ctx.menu[ctx.index].handler() end end local function tbl_copy(tbl) local res = {} for k,v in pairs(tbl) do if type(v) == "table" then res[k] = tbl_copy(v) else res[k] = v end end return res end -- menu : normal compliant menu table, assumed to have passed -- the rules in menu.lua:menu_validate. fields used: -- label (text string to present) -- eval (determine if an action on it is valid or not) -- submenu (tag with an icon to indicate a submenu to trigger -- shortcut (text- str for right column) -- -- valid options: -- anchor - parent vid to attach to -- text_valid - string prefix to use for a line of valid output -- text_invalid - string prefix to use for a line of inactive output -- text_menu - string prefix to use for a line of a menu -- text_menu_suf - string suffix to use for a line of a menu -- animation_in - time for fade / animate in -- animation_out - time for fade / animate out -- border_attach - function(ctx : tbl, src : vid, width, height) -- end -- called on spawn, attach with border vid, inherit -- order and re-order to -1. Nudge the anchor or the -- border / background region itself, your choice. -- image_mask_set(vid, MASK_UNPICKABLE) as well. -- -- cursor_at - function(ctx : tbl, cursor: vid, x, y, width, height) -- end -- Updated when the cursor has moved (and on spawn), -- implement to override default cursor -- -- -- on_finish - function(ctx, entry(=nil)) -- end -- triggered on valid 'select' or on cancel. -- -- returns table: -- attributes: -- anchor : vid -- cursor : vid (unless cursor_at is set) -- max_w : highest width recorded from text groups -- max_h : highest height recorded from text groups -- -- methods: -- step_up -- step_down -- set_index(i) -- trigger -> menu entry -- cancel() -- -- as well as a closure that needs to be invoked to clean up dangling -- resources, useful if the mouse_grab layer is attached. -- spawn_popup = function(menu, options) local res = { step_up = step_up, step_down = step_dn, set_index = set_index, trigger = trigger, cancel = cancel, anchor = null_surface(1, 1), max_w = 0, max_h = 0, index = 1, options = options } -- out of VIDs? if not valid_vid(res.anchor) then return end options = options and options or {} res.animation_in = options.animation_in and options.animation_in or 10; res.animation_out = options.animation_out and options.animation_out or 20; blend_image(res.anchor, 1.0, res.animation_in, INTERP_EXPIN); -- use a copy where eval switches into active local lmenu = {} local active = #menu for _,v in ipairs(menu) do if not v.alias then table.insert(lmenu, tbl_copy(v)); local i = #lmenu lmenu[i].active = true if lmenu[i].eval ~= nil then if lmenu[i].eval == false or (type(lmenu[i].eval) == "function" and lmenu[i].eval() ~= true) then lmenu[i].active = false active = active - 1 end end end end res.menu = lmenu -- no point in providing a menu that can't be selected if active == 0 then return end -- build string table local text_list, symbol_list = menu_to_fmtstr(lmenu, options) if not text_list then return end -- render failure is bad font or out of VIDs, drop the group local vid, lh, width, height, ascent = render_text(text_list) if not valid_vid(vid) then return end res.line_pos = lh res.cursor_h = ascent -- disable mouse handling, we do that for the anchor surface image_mask_set(vid, MASK_UNPICKABLE) local props = image_surface_resolve(vid) res.max_w = res.max_w > props.width and res.max_w or props.width res.max_h = res.max_h + props.height link_image(vid, res.anchor); image_inherit_order(vid, true) show_image(vid) resize_image(res.anchor, res.max_w, res.max_h) local mh = { name = "popup_mouse", own = function(ctx, vid) return vid == res.anchor end, motion = function(ctx, vid, x, y) local props = image_surface_resolve(res.anchor); local row = y - props.y; -- cheap optimization here would be to simply check from < last_n or > last_n -- based on dy from last time, but cursors can be jumpy. local last_i = 1; for i=1,#lh do if row < lh[i] then break; else last_i = i; end end res:set_index(last_i) end, button = function(ctx, vid, ind, act) if (not act or ind > MOUSE_WHEELNX or ind < MOUSE_WHEELPY) then return; end if (ind == MOUSE_WHEELNX or ind == MOUSE_WHEELNY) then res:step_down(); else res:step_up(); end end, click = function(ctx) res:trigger() end }; mouse_addlistener(mh, {"motion", "click", "button"}) if (not options.cursor_at) then local cursor = color_surface(64, 64, 255, 255, 255); link_image(cursor, res.anchor) blend_image(cursor, 0.5) force_image_blend(cursor, BLEND_ADD); image_inherit_order(cursor, true) order_image(cursor, 2) image_mask_set(cursor, MASK_UNPICKABLE) res.cursor = cursor end -- all the other resources are in place, size the anchor surface and -- register it as the mouse handler -- run border attach to allow a custom look and field, typically color -- surface with some shader arranged around if options.border_attach then options.border_attach(res, res.anchor, res.max_w, res.max_h) end local function closure() if mh.name then mouse_droplistener(mh); mh.name = nil end end -- resize the cursor and find the first valid entry res.index = #res.menu res:step_down() return res, closure end -- normal constructor function that returns a table of operations return spawn_popup
bsd-3-clause
tst2005googlecode/fbclient
lua/fbclient/module.lua
2
2062
--[[ Since you opened this file, you might want to know how modules work in fbclient. A typical fbclient module starts with the line: module(...,require'fbclient.module') This does two things: 1) loads this module if it's not loaded already (so the initialization code only happens once) 2) calls the value returned by require(), which is the return value of this module (chunk), which is the return value of pkg.new(globals), which is a function that initializes the module as described in package.lua. NOTE: don't interpret this module by Lua convention as the main module of fbclient, cuz there's no such thing as require'fbclient'. just coudln't find a better name for what this module does. ]] local pkg = require 'fbclient.package' local util = require 'fbclient.util' local alien = require 'alien' local struct = require 'alien.struct' local globals = { --*** varargs select = select, unpack = unpack, --*** tables ipairs = ipairs, pairs = pairs, next = next, table = table, --*** types type = type, --*** numbers tonumber = tonumber, math = math, --*** strings tostring = tostring, string = string, --*** virtualization getmetatable = getmetatable, setmetatable = setmetatable, --rawequal = rawequal, --rawset = rawset, --rawget = rawget, --*** environments getfenv = getfenv, --setfenv = setfenv, --*** errors assert = assert, error = error, xpcall = xpcall, pcall = pcall, print = print, --*** coroutines coroutine = coroutine, --*** interpreter --load = load, --loadstring = loadstring, --loadfile = loadfile, --dofile = dofile, --*** modules require = require, --module = module, package = package, --*** clib --io = io, os = os, --*** gc --collectgarbage = collectgarbage, --gcinfo = gcinfo, --*** debug --debug = debug, --*** unsupported --newproxy = newproxy, --*** alien alien = alien, struct = struct, util = util, --in case you want to be explicit about it } --add all utils to the globals table for k,v in pairs(util) do globals[k]=v end return pkg.new(globals)
mit
Cloudef/darkstar
scripts/globals/abilities/ice_shot.lua
2
3240
----------------------------------- -- Ability: Ice Shot -- Consumes a Ice Card to enhance ice-based debuffs. Deals ice-based magic damage -- Frost Effect: Enhanced DoT and AGI- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/weaponskills"); require("scripts/globals/ability"); ----------------------------------- function onAbilityCheck(player,target,ability) --ranged weapon/ammo: You do not have an appropriate ranged weapon equipped. --no card: <name> cannot perform that action. if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then return 216,0; end if (player:hasItem(2177, 0) or player:hasItem(2974, 0)) then return 0,0; else return 71, 0; end end; function onUseAbility(player,target,ability,action) local params = {}; params.includemab = true; local dmg = (2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG)) * 1 + player:getMod(MOD_QUICK_DRAW_DMG_PERCENT)/100; dmg = addBonusesAbility(player, ELE_ICE, target, dmg, params); dmg = dmg * applyResistanceAbility(player,target,ELE_ICE,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY)); dmg = adjustForTarget(target,dmg,ELE_ICE); local shadowsAbsorbed = 0 if shadowAbsorb(target) then shadowsAbsorbed = 1 end dmg = takeAbilityDamage(target, player, {}, true, dmg, SLOT_RANGED, 1, shadowsAbsorbed, 0, 0, action, nil); if shadowsAbsorbed == 0 then local effects = {}; local counter = 1; local frost = target:getStatusEffect(dsp.effects.FROST); if (frost ~= nil) then effects[counter] = frost; counter = counter + 1; end local threnody = target:getStatusEffect(dsp.effects.THRENODY); if (threnody ~= nil and threnody:getSubPower() == MOD_WINDRES) then effects[counter] = threnody; counter = counter + 1; end local paralyze = target:getStatusEffect(dsp.effects.PARALYSIS); if (paralyze ~= nil) then effects[counter] = paralyze; counter = counter + 1; end if counter > 1 then local effect = effects[math.random(1, counter-1)]; local duration = effect:getDuration(); local startTime = effect:getStartTime(); local tick = effect:getTick(); local power = effect:getPower(); local subpower = effect:getSubPower(); local tier = effect:getTier(); local effectId = effect:getType(); local subId = effect:getSubType(); power = power * 1.2; target:delStatusEffectSilent(effectId); target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier); local newEffect = target:getStatusEffect(effectId); newEffect:setStartTime(startTime); end end local del = player:delItem(2177, 1) or player:delItem(2974, 1) target:updateClaim(player); return dmg; end;
gpl-3.0
kkrishna/gorealis
vendor/git.apache.org/thrift.git/lib/lua/TMemoryBuffer.lua
100
2266
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'TTransport' TMemoryBuffer = TTransportBase:new{ __type = 'TMemoryBuffer', buffer = '', bufferSize = 1024, wPos = 0, rPos = 0 } function TMemoryBuffer:isOpen() return 1 end function TMemoryBuffer:open() end function TMemoryBuffer:close() end function TMemoryBuffer:peak() return self.rPos < self.wPos end function TMemoryBuffer:getBuffer() return self.buffer end function TMemoryBuffer:resetBuffer(buf) if buf then self.buffer = buf self.bufferSize = string.len(buf) else self.buffer = '' self.bufferSize = 1024 end self.wPos = string.len(buf) self.rPos = 0 end function TMemoryBuffer:available() return self.wPos - self.rPos end function TMemoryBuffer:read(len) local avail = self:available() if avail == 0 then return '' end if avail < len then len = avail end local val = string.sub(self.buffer, self.rPos + 1, self.rPos + len) self.rPos = self.rPos + len return val end function TMemoryBuffer:readAll(len) local avail = self:available() if avail < len then local msg = string.format('Attempt to readAll(%d) found only %d available', len, avail) terror(TTransportException:new{message = msg}) end -- read should block so we don't need a loop here return self:read(len) end function TMemoryBuffer:write(buf) self.buffer = self.buffer .. buf self.wPos = self.wPos + string.len(buf) end function TMemoryBuffer:flush() end
apache-2.0
Cloudef/darkstar
scripts/globals/abilities/gauge.lua
7
1345
----------------------------------- -- Ability: Gauge -- Checks to see if an enemy can be charmed. -- Obtained: Beastmaster Level 10 -- Recast Time: 0:30 -- Duration: Instant ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------- function onAbilityCheck(player, target, ability) if (player:getPet() ~= nil ) then return msgBasic.ALREADY_HAS_A_PET,0; else return 0,0; end end; function onUseAbility(player, target, ability) local charmChance = player:getCharmChance(target, false); if (charmChance >= 75) then ability:setMsg(msgBasic.SHOULD_BE_ABLE_CHARM); -- The <player> should be able to charm <target>. elseif (charmChance >= 50) then ability:setMsg(msgBasic.MIGHT_BE_ABLE_CHARM); -- The <player> might be able to charm <target>. elseif (charmChance >= 25) then ability:setMsg(msgBasic.DIFFICULT_TO_CHARM); -- It would be difficult for the <player> to charm <target>. elseif (charmChance >= 1) then ability:setMsg(msgBasic.VERY_DIFFICULT_CHARM); -- It would be very difficult for the <player> to charm <target>. else ability:setMsg(msgBasic.CANNOT_CHARM); -- The <player> cannot charm <target>! end end;
gpl-3.0
Cloudef/darkstar
scripts/zones/Xarcabard/npcs/qm4.lua
5
1138
----------------------------------- -- Area: Xarcabard -- NPC: qm4 (???) -- Involved in Quests: Atop the Highest Mountains (for Boreal Hound) -- !pos -21 -25 -490 112 ----------------------------------- package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Xarcabard/TextIDs"); require("scripts/zones/Xarcabard/MobIDs"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/quests"); function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (not OldSchoolG2 or GetMobByID(BOREAL_HOUND):isDead()) then if (player:getQuestStatus(JEUNO,ATOP_THE_HIGHEST_MOUNTAINS) == QUEST_ACCEPTED and not player:hasKeyItem(TRIANGULAR_FRIGICITE)) then player:addKeyItem(TRIANGULAR_FRIGICITE); player:messageSpecial(KEYITEM_OBTAINED, TRIANGULAR_FRIGICITE); else player:messageSpecial(ONLY_SHARDS); end else player:messageSpecial(ONLY_SHARDS); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
bendeutsch/minetest-sunburn
persistent_player_attributes.lua
1
2936
--[[ Persistent player attributes ]] -- change this to inject into other module local M = sunburn M.persistent_player_attributes = {} local PPA = M.persistent_player_attributes --[[ Helper functions that take care of the conversions *and* the clamping for us ]] local function _count_for_val(value, def) local count = math.floor((value - def.min) / (def.max - def.min) * 65535) if count < 0 then count = 0 end if count > 65535 then count = 65535 end return count end local function _val_for_count(count, def) local value = count / 65535 * (def.max - def.min) + def.min if value < def.min then value = def.min end if value > def.max then value = def.max end return value end -- end helper functions -- the stash of registered attributes PPA.defs = {--[[ name = { name = "mymod_attr1", min = 0, max = 10, default = 5, }, ]]} PPA.read_cache = {--[[ player_name = { attr1 = value1, attr2 = value2, }, ]]} --[[ How to register a new attribute, with named parameters: PPA.register({ name = "mymod_attr1", min = 0, ... }) ]] PPA.register = function(def) PPA.defs[def.name] = { name = def.name, min = def.min or 0.0, max = def.max or 1.0, default = def.default or def.min or 0.0, } end -- The on_joinplayer handler PPA.on_joinplayer = function(player) local inv = player:get_inventory() local player_name = player:get_player_name() PPA.read_cache[player_name] = {} for name, def in pairs(PPA.defs) do inv:set_size(name, 1) if inv:is_empty(name) then -- set default value inv:set_stack(name, 1, ItemStack({ name = ":", count = _count_for_val(def.default, def) })) -- cache default value PPA.read_cache[player_name][name] = def.default end end end minetest.register_on_joinplayer(PPA.on_joinplayer) --[[ get an attribute, procedural style: local attr1 = PPA.get_value(player, "mymod_attr1") ]] PPA.get_value = function(player, name) local player_name = player:get_player_name() if PPA.read_cache[player_name][name] == nil then local def = PPA.defs[name] local inv = player:get_inventory() local count = inv:get_stack(name, 1):get_count() PPA.read_cache[player_name][name] = _val_for_count(count, def) end return PPA.read_cache[player_name][name] end --[[ set an attribute, procedural style: PPA.set_value(player, "mymod_attr1", attr1) ]] PPA.set_value = function(player, name, value) local def = PPA.defs[name] local inv = player:get_inventory() local player_name = player:get_player_name() if value > def.max then value = def.max end if value < def.min then value = def.min end PPA.read_cache[player_name][name] = value inv:set_stack(name, 1, ItemStack({ name = ":", count = _count_for_val(value, def) })) end
lgpl-2.1
Cloudef/darkstar
scripts/zones/Northern_San_dOria/npcs/Danngogg.lua
5
1120
----------------------------------- -- Area: Northern San d'Oria -- NPC: Danngogg -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) player:startEvent(540); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Cloudef/darkstar
scripts/zones/Cape_Teriggan/TextIDs.lua
5
1625
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item> come back again after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6384; -- You cannot obtain the #. Try trading again after sorting your inventory. ITEM_OBTAINED = 6386; -- Obtained: <item>. GIL_OBTAINED = 6387; -- Obtained <number> gil. KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 7705; -- You obtain BEASTMEN_BANNER = 7128; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7548; -- You can't fish here. HOMEPOINT_SET = 11251; -- Home point set! -- Other dialog NOTHING_OUT_OF_ORDINARY = 7685; -- There is nothing out of the ordinary here. -- Conquest CONQUEST = 7215; -- You've earned conquest points! -- ZM4 Dialog SOMETHING_BETTER = 7660; -- Don't you have something better to do right now? CANNOT_REMOVE_FRAG = 7663; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed... ALREADY_OBTAINED_FRAG = 7664; -- You have already obtained this monument's . Try searching for another. FOUND_ALL_FRAGS = 7665; -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine! ZILART_MONUMENT = 7667; -- It is an ancient Zilart monument. -- Other NOTHING_HAPPENS = 119; -- Nothing happens...?Possible Special Code: 00? -- conquest Base CONQUEST_BASE = 7047; -- Tallying conquest results...
gpl-3.0
pablojorge/brainfuck
lua/brainfuck.lua
1
1422
#!/usr/bin/env lua -- Copyright (c) 2016 Francois Perrad local f = arg[1] and assert(io.open(arg[1], 'r')) or io.stdin local src = string.gsub(f:read'*a', '[^><+%-%.,%[%]]', '') local len = string.len(src) f:close() io.stdout:setvbuf'no' local stack = {} local jump = {} local code = {} for pc = 1, len do local opcode = src:sub(pc, pc) code[pc] = opcode if opcode == '[' then stack[#stack+1] = pc elseif opcode == ']' then local target = stack[#stack] stack[#stack] = nil jump[target] = pc jump[pc] = target end end src = nil stack = nil local buffer = setmetatable({}, { __index = function () return 0 -- default value end }) local ptr = 1 local pc = 1 while pc <= len do local opcode = code[pc] if opcode == '>' then ptr = ptr + 1 elseif opcode == '<' then ptr = ptr - 1 elseif opcode == '+' then buffer[ptr] = buffer[ptr] + 1 elseif opcode == '-' then buffer[ptr] = buffer[ptr] - 1 elseif opcode == '.' then io.stdout:write(string.char(buffer[ptr])) elseif opcode == ',' then buffer[ptr] = string.byte(io.stdin:read(1) or '\0') elseif opcode == '[' then if buffer[ptr] == 0 then pc = jump[pc] end elseif opcode == ']' then if buffer[ptr] ~= 0 then pc = jump[pc] end end pc = pc + 1 end
mit
Cloudef/darkstar
scripts/zones/Dragons_Aery/mobs/Nidhogg.lua
4
1926
----------------------------------- -- Area: Dragons Aery -- HNM: Nidhogg ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- function onMobInitialize(mob) end; function onMobSpawn(mob) if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(17408033):setStatus(STATUS_DISAPPEAR); end end; function onMobFight(mob, target) local battletime = mob:getBattleTime(); local twohourTime = mob:getLocalVar("twohourTime"); if (twohourTime == 0) then mob:setLocalVar("twohourTime",math.random(30,90)); end if (battletime >= twohourTime) then mob:useMobAbility(956); -- technically aerial hurricane wing, but I'm using 700 for his two hour --(since I have no inclination to spend millions on a PI to cap one name you never see) mob:setLocalVar("twohourTime",battletime + math.random(60,120)); end end; function onMobDeath(mob, player, isKiller) player:addTitle(NIDHOGG_SLAYER); end; function onMobDespawn(mob) -- Set Nidhogg's Window Open Time if (LandKingSystem_HQ ~= 1) then local wait = 72 * 3600; SetServerVariable("[POP]Nidhogg", os.time() + wait); -- 3 days if (LandKingSystem_HQ == 0) then -- Is time spawn only DisallowRespawn(mob:getID(), true); end end -- Set Fafnir's spawnpoint and respawn time (21-24 hours) if (LandKingSystem_NQ ~= 1) then local Fafnir = mob:getID()-1; SetServerVariable("[PH]Nidhogg", 0); DisallowRespawn(Fafnir, false); UpdateNMSpawnPoint(Fafnir); GetMobByID(Fafnir):setRespawnTime(math.random(75600,86400)); end if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(17408033):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME); end end;
gpl-3.0
rohlem/lua_mods
lpp.lua
1
24445
--EXTENSION replace level long strings in 5.0 (disallowing long strings in layer-2 code, because layer-1 is inescapable) --EXTENSION numeric literal syntax --note: This file is loaded in two "stages", first as plain Lua 5.1-5.3 and then parsed by itself. That's why it might look a bit odd in places. --"imports" [[ local error = error local io = io local io_open = io.open local lua_version = require "lua_version" local pairs = pairs -- local print = print local string = string local string_find = string.find local string_format = string.format local string_len = string.len local string_sub = string.sub local table_concat = table.concat --]] "imports" --parses files, uses loadstring to interpret them and returns the resulting function --this is the "compatibility" version, to be read by the standard Lua interpreter local mode = {nil, nil} local long_string_end_indicator = {nil, nil} local find_masks = {} do local mode_masks = {['default'] = "%-'\"%[", ['long'] = "%]", ['quote string'] = "\\\"", ['apostrophe string'] = "\\'", ['line comment'] = "\n"} local layer_masks = {['line 1'] = "\n", ['inline 1'] = "%)", ['2'] = "$\n%]"} --] to hide layer-2 closing double square brackets from layer-1 code local find_mask = {".-([", nil, nil, "\n])"} --\n to keep track of line_nr for mk, mv in pairs(mode_masks) do find_mask[2] = mv find_masks[mk] = {} for lk, lv in pairs(layer_masks) do find_mask[3] = lv find_masks[mk][lk] = table_concat(find_mask) end end end local write = {nil, nil} local warn_table = {nil, " on line nr ", nil, " on layer ", nil, " with modes ", nil, ", ", nil, nil, nil} local long_string_end_table = {"^", nil, "]"} --[=[ #--[=[ --]=] local function prep_compat(contents) local chunk, next_chunk_index = {"local _pr_,_npi_,_={},1"}, 2 --_prep_result_, _next_pr_index_, temporary for parsing omissible inline layer-1 expressions local begin_index = string_sub(contents, 1, 1) == "#" and string_find(contents, "\n", 2, true) or 1 local last_index = begin_index local layer = 2 local layer_mode = '2' mode[1] = 'default' mode[2] = mode[1] local l1_inline_type, l1_inline_end local parsed_long_string_flag = false local function parse_long_string(index) local _, _2, level_indicator = string_find(contents, "^(=*)%[", index) if _ then long_string_end_indicator[layer] = level_indicator parsed_long_string_flag = _2 - _ return true else parsed_long_string_flag = nil end end write[1] = function(next_chunk_index, start_index, end_index) chunk[next_chunk_index] = string_sub(contents, start_index, end_index) end write[2] = function(next_chunk_index, start_index, end_index) chunk[next_chunk_index] = " _pr_[_npi_]=" chunk[next_chunk_index+1] = string_format("%q", string_sub(contents, start_index, end_index)) end local force_write_flag = false local line_nr = 1 local function warn(assertion, msg, arg) if not assertion then warn_table[1] = msg warn_table[3] = line_nr warn_table[5] = layer_mode warn_table[7] = mode[1] warn_table[9] = mode[2] warn_table[10] = arg and "|" warn_table[11] = arg error(table_concat(warn_table)) end end local last_last_index while true do if last_last_index == last_index then warn(false, "stopped moving") end last_last_index = last_index local current_mode = mode[layer] local start_index, char_index, char = string_find(contents, find_masks[current_mode][layer_mode], last_index) if not start_index then break end -- print("AT ", start_index, "-", char_index, ": ", char) if char == "\\" then if current_mode == 'quote string' or current_mode == 'apostrophe string' then last_index = char_index + 2 --as long as no special characters may appear (and should be ignored) within escapes, we should be all good else warn(false, "non-useful backslash encountered") end else local next_index = char_index + 1 if (current_mode == 'quote string' and char == "\"") or (current_mode == 'apostrophe string' and char == "'") then -- print("closing string!") mode[layer] = 'default' last_index = next_index else local previous_chunk_index, previous_layer = next_chunk_index, layer if char == "\n" then line_nr = line_nr + 1 if current_mode == 'line comment' then mode[layer] = 'default' end if string_sub(contents, next_index, next_index) == "#" then --line layer-1 code warn(layer_mode ~= 'inline l1', "line l1 starting # encountered within inline l1") char_index = char_index + 1 --include \n when writing next_index = next_index + 1 if layer == 1 then next_chunk_index = next_chunk_index + 1 force_write_flag = true --flush to omit "#" else layer_mode, layer = 'line 1', 1 -- print("switching layer: line 1 | 1 ") chunk[next_chunk_index+2] = "_npi_=_npi_+1 " next_chunk_index = next_chunk_index + 3 force_write_flag = true end elseif layer_mode == 'line 1' then warn(layer == 1, "layer_mode = 'line 1', but layer ~= 1") char_index = char_index + 1 --include \n when writing next_chunk_index = next_chunk_index + 1 layer_mode, layer = '2', 2 -- print("switching layer: 2") force_write_flag = true end last_index = next_index elseif char == "$" then warn(layer == 2, "dollar sign encountered within layer-1 code") local start_index start_index, l1_inline_end = string_find(contents, "^%b()", next_index) -- print("l1 inline expression from", start_index, "to", l1_inline_end) if start_index then --layer-1 code local excl_index = start_index+1 local str_sub = string_sub(contents, excl_index, excl_index) l1_inline_type = str_sub ~= "!" and 'omissible' if l1_inline_type then --some form of omissible chunk[next_chunk_index+2] = "_npi_=_npi_+1 _=(" last_index = start_index + 1 else chunk[next_chunk_index+2] = "_npi_=_npi_+2 _pr_[_npi_-1]=" last_index = start_index + 2 end next_chunk_index = next_chunk_index + 3 layer_mode, layer = 'inline 1', 1 -- print("switching layer: inline 1 | 1") force_write_flag = true else warn(current_mode ~= 'default', "dollar sign not followed by parentheses in mode default") last_index = next_index end elseif char == ")" then -- print("char_index", char_index, "l1_inline_end", l1_inline_end) if char_index == l1_inline_end then warn(layer == 1, "l1_inline_end reached within layer-2 code") start_index = start_index + 1 if l1_inline_type then --some form of omissible start_index = start_index + 1 chunk[next_chunk_index+1] = ")if _ then _pr_[_npi_]=_ _npi_=_npi_+1 end " next_chunk_index = next_chunk_index + 2 else --non-omissible next_chunk_index = next_chunk_index + 1 end layer_mode, layer = '2', 2 -- print("switching layer: 2") force_write_flag = true end last_index = next_index elseif char == "-" then warn(current_mode == 'default', "- encountered in non-default mode") if string_sub(contents, next_index, next_index) == "-" then next_index = next_index + 2 if not parse_long_string(next_index) then mode[layer] = 'line comment' last_index = next_index end else last_index = next_index end elseif char == "[" then warn(current_mode == 'default' or current_mode == 'long', "[ encountered in non-default, non-long mode") if not parse_long_string(next_index) then last_index = next_index end elseif char == "]" then last_index = next_index local lsei = long_string_end_indicator[layer] long_string_end_table[2] = lsei if current_mode == 'long' and string_find(contents, table_concat(long_string_end_table), next_index) then mode[layer] = 'default' last_index = next_index + string_len(lsei) + 1 end if layer == 2 and mode[1] == 'long' then local lsei = long_string_end_indicator[1] long_string_end_table[2] = lsei if string_find(contents, table_concat(long_string_end_table), next_index) then -- print("====IN====") char_index = next_index + string_len(lsei) last_index = char_index chunk[next_chunk_index+2] = "_npi_=_npi_+1" next_chunk_index = next_chunk_index + 3 force_write_flag = true else last_index = next_index end end else mode[layer] = (char == "\"" and 'quote string') or (char == "'" and 'apostrophe string') or warn(false, "triggered by non-useful symbol", char) -- print("opening string!") last_index = next_index end if parsed_long_string_flag then mode[layer] = 'long' last_index = next_index + 1 + parsed_long_string_flag parsed_long_string_flag = false end if force_write_flag then -- print("around line ", line_nr, " forced write of ", begin_index, " to ", char_index - 1, " at layer ", previous_layer) write[previous_layer](previous_chunk_index, begin_index, char_index - 1) begin_index = last_index force_write_flag = false end end end end write[layer](next_chunk_index, begin_index, -1) chunk[next_chunk_index+layer] = " return require\"lua_version\".loadstring(table.concat(_pr_))" return lua_version.loadstring(table_concat(chunk)), chunk end local _, file_name = ... local lpp_file = file_name and io_open(file_name) if not lpp_file then lpp_file = debug if lpp_file then lpp_file = lpp_file.getinfo(1).source lpp_file = string_sub(lpp_file, 1, 1) == "@" and io_open(string_sub(lpp_file, 2)) end if not lpp_file then local string_gsub = string.gsub local paths = string_gsub(package.path, "%?", "lpp") for path in lua_version.string_gmatch(paths, "([^;]+);?") do -- ";;" is currently ignored lpp_file = io_open(path) if lpp_file then break end end end end local result = prep_compat(lpp_file:read("*a"))()() io.close(lpp_file) return result --[===[ --[=[ #--]=] --]=] --"imports" [[ local assert = assert local io_close = io.close # local lua_version = require "lua_version" local loadstring = lua_version.loadstring #local package = package local package = package local package_config = package.config local package_loaded = lua_version.package_loaded local package_path = lua_version.package_path local string_gmatch = lua_version.string_gmatch local string_gsub = string.gsub --]] "imports" #local use_goto = lua_version.goto_support and lua_version.label_support #local force_write = use_goto and "goto force_write" or "force_write_flag = true" local function prep(contents) local chunk, next_chunk_index = {"local _pr_,_npi_,_={},1"}, 2 --_prep_result_, _next_pr_index_, temporary for parsing omissible inline layer-1 expressions local begin_index = string_sub(contents, 1, 1) == "#" and string_find(contents, "\n", 2, true) or 1 local last_index = begin_index local layer = 2 local layer_mode = '2' mode[1] = 'default' mode[2] = mode[1] local l1_inline_type, l1_inline_end local parsed_long_string_flag = false local function parse_long_string(index) local _, _2, level_indicator = string_find(contents, "^(=*)%[", index) if _ then long_string_end_indicator[layer] = level_indicator parsed_long_string_flag = _2 - _ return true else parsed_long_string_flag = nil end end write[1] = function(next_chunk_index, start_index, end_index) chunk[next_chunk_index] = string_sub(contents, start_index, end_index) end write[2] = function(next_chunk_index, start_index, end_index) chunk[next_chunk_index] = " _pr_[_npi_]=" chunk[next_chunk_index+1] = string_format("%q", string_sub(contents, start_index, end_index)) end local force_write_flag = false local line_nr = 1 local function warn(assertion, msg, arg) if not assertion then warn_table[1] = msg warn_table[3] = line_nr warn_table[5] = layer_mode warn_table[7] = mode[1] warn_table[9] = mode[2] warn_table[10] = arg and "|" warn_table[11] = arg error(table_concat(warn_table)) end end local last_last_index while true do if last_last_index == last_index then warn(false, "stopped moving") end last_last_index = last_index local current_mode = mode[layer] local start_index, char_index, char = string_find(contents, find_masks[current_mode][layer_mode], last_index) if not start_index then break end -- print("AT ", start_index, "-", char_index, ": ", char) if char == "\\" then if current_mode == 'quote string' or current_mode == 'apostrophe string' then last_index = char_index + 2 --as long as no special characters may appear (and should be ignored) within escapes, we should be all good else warn(false, "non-useful backslash encountered") end else local next_index = char_index + 1 if (current_mode == 'quote string' and char == "\"") or (current_mode == 'apostrophe string' and char == "'") then -- print("closing string!") mode[layer] = 'default' last_index = next_index else local previous_chunk_index, previous_layer = next_chunk_index, layer if char == "\n" then line_nr = line_nr + 1 if current_mode == 'line comment' then mode[layer] = 'default' end if string_sub(contents, next_index, next_index) == "#" then --line layer-1 code warn(layer_mode ~= 'inline l1', "line l1 starting # encountered within inline l1") char_index = char_index + 1 --include \n when writing next_index = next_index + 1 $(use_goto and "last_index = next_index") --skipped if goto is used if layer == 1 then next_chunk_index = next_chunk_index + 1 $(!force_write) --flush to omit "#" else layer_mode, layer = 'line 1', 1 -- print("switching layer: line 1 | 1 ") chunk[next_chunk_index+2] = "_npi_=_npi_+1 " next_chunk_index = next_chunk_index + 3 $(!force_write) end elseif layer_mode == 'line 1' then warn(layer == 1, "layer_mode = 'line 1', but layer ~= 1") $(use_goto and "last_index = next_index") --skipped if goto is used char_index = char_index + 1 --include \n when writing next_chunk_index = next_chunk_index + 1 layer_mode, layer = '2', 2 -- print("switching layer: 2") $(!force_write) end last_index = next_index elseif char == "$" then warn(layer == 2, "dollar sign encountered within layer-1 code") local start_index start_index, l1_inline_end = string_find(contents, "^%b()", next_index) -- print("l1 inline expression from", start_index, "to", l1_inline_end) if start_index then --layer-1 code local excl_index = start_index+1 local str_sub = string_sub(contents, excl_index, excl_index) l1_inline_type = str_sub ~= "!" and 'omissible' if l1_inline_type then --some form of omissible chunk[next_chunk_index+2] = "_npi_=_npi_+1 _=(" last_index = start_index + 1 else chunk[next_chunk_index+2] = "_npi_=_npi_+2 _pr_[_npi_-1]=" last_index = start_index + 2 end next_chunk_index = next_chunk_index + 3 layer_mode, layer = 'inline 1', 1 -- print("switching layer: inline 1 | 1") $(!force_write) else warn(current_mode ~= 'default', "dollar sign not followed by parentheses in mode default") last_index = next_index end elseif char == ")" then -- print("char_index", char_index, "l1_inline_end", l1_inline_end) last_index = next_index if char_index == l1_inline_end then warn(layer == 1, "l1_inline_end reached within layer-2 code") start_index = start_index + 1 if l1_inline_type then --some form of omissible start_index = start_index + 1 chunk[next_chunk_index+1] = ")if _ then _pr_[_npi_]=_ _npi_=_npi_+1 end " next_chunk_index = next_chunk_index + 2 else --non-omissible next_chunk_index = next_chunk_index + 1 end layer_mode, layer = '2', 2 -- print("switching layer: 2") $(!force_write) end elseif char == "-" then warn(current_mode == 'default', "- encountered in non-default mode") if string_sub(contents, next_index, next_index) == "-" then next_index = next_index + 2 if not parse_long_string(next_index) then mode[layer] = 'line comment' last_index = next_index end else last_index = next_index end elseif char == "[" then warn(current_mode == 'default' or current_mode == 'long', "[ encountered in non-default, non-long mode") if not parse_long_string(next_index) then last_index = next_index end elseif char == "]" then last_index = next_index local lsei = long_string_end_indicator[layer] long_string_end_table[2] = lsei if current_mode == 'long' and string_find(contents, table_concat(long_string_end_table), next_index) then mode[layer] = 'default' last_index = next_index + string_len(lsei) + 1 end if layer == 2 and mode[1] == 'long' then local lsei = long_string_end_indicator[1] long_string_end_table[2] = lsei if string_find(contents, table_concat(long_string_end_table), next_index) then -- print("====IN====") char_index = next_index + string_len(lsei) last_index = char_index chunk[next_chunk_index+2] = "_npi_=_npi_+1" next_chunk_index = next_chunk_index + 3 $(!force_write) else last_index = next_index end end else mode[layer] = (char == "\"" and 'quote string') or (char == "'" and 'apostrophe string') or warn(false, "triggered by non-useful symbol", char) -- print("opening string!") last_index = next_index end if parsed_long_string_flag then mode[layer] = 'long' last_index = next_index + 1 + parsed_long_string_flag parsed_long_string_flag = false end $(!use_goto and [[goto no_write ::force_write::]] or [[if force_write_flag then force_write_flag = false]]) -- print("around line ", line_nr, " forced write of ", begin_index, " to ", char_index - 1, " at layer ", previous_layer) write[previous_layer](previous_chunk_index, begin_index, char_index - 1) begin_index = last_index $(!use_goto and "::no_write::" or "end") end end end write[layer](next_chunk_index, begin_index, -1) chunk[next_chunk_index+layer] = " return require\"lua_version\".loadstring(table.concat(_pr_))" return lua_version.loadstring(table_concat(chunk)), chunk end local prep_path = {string_gsub(package_path, "%.lua", ".lpp"), nil, string_gsub(package_path, "%.lua", ".lpp.lua"), nil, package_path} local dir_sep, temp_sep, sub_mark if package_config then dir_sep, temp_sep, sub_mark = string.match(package_config, "^(.-)\n(.-)\n(.-)\n") sub_mark = string_find("$^()%.[]*+-?", sub_mark, 1, true) and "%"..sub_mark or sub_mark else dir_sep, temp_sep, sub_mark = "/", ";", "%?" end local package_path_gmatch_pattern = table_concat({"([^", temp_sep, "]+)", temp_sep, "?"}) --retrieves files by module name local search_function --only done for clarity; not necessary, because layer-1 blocks don't interfer with layer-2 visibility #local package_searchpath = package.searchpath #if not package_searchpath then prep_path[2] = dir_sep prep_path[4] = dir_sep prep_path = table_concat(prep_path) local fnf_table = {"file not found (searchpaths: ", nil, ")"} function search_function(modname) modname = string_gsub(modname, "%.", dir_sep) local paths = string_gsub(prep_path, sub_mark, modname) -- done in advance; assuming temp_sep isn't contained in modname for path in string_gmatch(paths, package_path_gmatch_pattern) do -- ";;" is currently ignored local file, err_msg = io_open(path) if file then return file end end fnf_table[2] = paths return nil, table_concat(fnf_table) end #else prep_path[2] = ";" prep_path[4] = ";" prep_path = table_concat(prep_path) --"imports" [[ local package_searchpath = package.searchpath --]] "imports" function search_function(modname) local file, err_msg = package_searchpath(modname, prep_path) return (file and io_open(file)), err_msg end #end --used to log which modules were prepped and cache the resulting functions local prep_loaded = {} --preps a file by module name and caches and returns the resulting function local function prep_mod(modname) local result = prep_loaded[modname] if result then return result end local file = assert(search_function(modname)) result = prep(file:read("*a")) io_close(file) prep_loaded[modname] = result return result end local function prepquire(modname) local result = package_loaded[modname] if result then return result end result = prep_mod(modname)()() package_loaded[modname] = result ~= nil and result or true return result end #local package_searchers = lua_version.package_searchers #if package_searchers then local function prepquire_file(path) local file = io_open(path) local result = prep(file:read("*a")) io_close(file) return result()() end #local package_searcher = lua_version.require_calls_loader_with_second_argument and "prepquire_file, path" or "function () return prepquire_file(path) end" local searcher_function #if not package_searchpath then function searcher_function(modname) modname = string_gsub(modname, "%.", dir_sep) local paths = string_gsub(prep_path, sub_mark, modname) -- done in advance; assuming temp_sep isn't contained in modname for path in string_gmatch(paths, package_path_gmatch_pattern) do -- ";;" is currently ignored local file, err_msg = io_open(path) if file then io_close(file) return $(!package_searcher) end end fnf_table[2] = paths return nil end #else function searcher_function(modname) local path, err_msg = package_searchpath(modname, prep_path) return path and $(!package_searcher) end #end local package_searchers = lua_version.package_searchers package_searchers[#package_searchers+1] = searcher_function #end return { prep = prep, search_function = search_function, prep_loaded = prep_loaded, prep_mod = prep_mod, prep_path = prep_path, --preps a file, executes the resulting function and caches and returns its result prepquire = prepquire$(package_searchers and [[, searcher_function = searcher_function]]) } --]===]
unlicense
Cloudef/darkstar
scripts/globals/items/bowl_of_yayla_corbasi.lua
2
1229
----------------------------------------- -- ID: 5579 -- Item: bowl_of_yayla_corbasi -- Food Effect: 3Hrs, All Races ----------------------------------------- -- HP 20 -- Dexterity -1 -- Vitality 2 -- HP Recovered While Healing 3 -- MP Recovered While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(dsp.effects.FOOD) == true or target:hasStatusEffect(dsp.effects.FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(dsp.effects.FOOD,0,0,10800,5579); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, -1); target:addMod(MOD_VIT, 2); target:addMod(MOD_HPHEAL, 3); target:addMod(MOD_MPHEAL, 1); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, -1); target:delMod(MOD_VIT, 2); target:delMod(MOD_HPHEAL, 3); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
mehrpouya81/iranspammer
plugins/invite.lua
299
1025
-- Invite other user to the chat group. -- Use !invite name User_name or !invite id id_number -- The User_name is the print_name (there are no spaces but _) do local function callback(extra, success, result) vardump(success) vardump(result) end local function run(msg, matches) local user = matches[2] -- User submitted a user name if matches[1] == "name" then user = string.gsub(user," ","_") end -- User submitted an id if matches[1] == "id" then user = 'user#id'..user end -- The message must come from a chat group if msg.to.type == 'chat' then local chat = 'chat#id'..msg.to.id chat_add_user(chat, user, callback, false) return "Add: "..user.." to "..chat else return 'This isnt a chat group!' end end return { description = "Invite other user to the chat group", usage = { "!invite name [user_name]", "!invite id [user_id]" }, patterns = { "^!invite (name) (.*)$", "^!invite (id) (%d+)$" }, run = run, moderation = true } end
gpl-2.0
jewmin/astd
com.lover.astd.game.ui/lua/module/equip.lua
1
5166
-- ×°±¸Ä£¿é equip = {} equip.null = 1 equip.error = 10 equip.finish = 2 equip.success = 0 equip.getUpgradeInfo = function() local url = "/root/equip!getUpgradeInfo.action" local result = ProtocolMgr():getXml(url, "×°±¸-ÐÅÏ¢") if not result then return equip.null end if not result.CmdSucceed then return equip.error end -- ILogger():logInfo(result.CmdResult.InnerXml) local data = {} local cmdResult = result.CmdResult local xmlNode = cmdResult:SelectSingleNode("/results/ticketnumber") data.ticketnumber = xmlNode and tonumber(xmlNode.InnerText) or 0 local xmlNodeList = cmdResult:SelectNodes("/results/playerequipdto") data.playerequipdtos = {} if xmlNodeList ~= nil then for i = 1, xmlNodeList.Count do local childXmlNode = xmlNodeList:Item(i - 1) local childXmlNodeList = childXmlNode.ChildNodes local playerequipdto = {} for j = 1, childXmlNodeList.Count do local childChildXmlNode = childXmlNodeList:Item(j - 1) if childChildXmlNode.Name == "composite" then playerequipdto.composite = tonumber(childChildXmlNode.InnerText) elseif childChildXmlNode.Name == "equipname" then playerequipdto.equipname = childChildXmlNode.InnerText elseif childChildXmlNode.Name == "generalname" then playerequipdto.generalname = childChildXmlNode.InnerText elseif childChildXmlNode.Name == "monkeylv" then playerequipdto.monkeylv = tonumber(childChildXmlNode.InnerText) elseif childChildXmlNode.Name == "tickets" then playerequipdto.tickets = tonumber(childChildXmlNode.InnerText) elseif childChildXmlNode.Name == "xuli" then playerequipdto.xuli = tonumber(childChildXmlNode.InnerText) elseif childChildXmlNode.Name == "maxxuli" then playerequipdto.maxxuli = tonumber(childChildXmlNode.InnerText) end end table.insert(data.playerequipdtos, playerequipdto) end end return equip.success, data end equip.upgradeMonkeyTao = function(name, composite, num) local url = "/root/equip!upgradeMonkeyTao.action" local data = string.format("composite=%d&num=%d", composite, num) local result = ProtocolMgr():postXml(url, data, "×°±¸-Ç¿»¯ºï×ÓÌ××°") if not result or not result.CmdSucceed then return false end -- ILogger():logInfo(result.CmdResult.InnerXml) local tips = string.format("Ç¿»¯%s³É¹¦", name) local cmdResult = result.CmdResult local xmlNode = cmdResult:SelectSingleNode("/results/baoji") local baoji = xmlNode and tonumber(xmlNode.InnerText) or 0 if baoji > 1 then tips = tips .. string.format("£¬%d±¶±©»÷", baoji) end local xmlNodeList = cmdResult:SelectNodes("/results/addinfo") if xmlNodeList ~= nil then for i = 1, xmlNodeList.Count do local childXmlNode = xmlNodeList:Item(i - 1) local childXmlNodeList = childXmlNode.ChildNodes local addinfo = {} for j = 1, childXmlNodeList.Count do local childChildXmlNode = childXmlNodeList:Item(j - 1) if childChildXmlNode.Name == "name" then addinfo.name = childChildXmlNode.InnerText elseif childChildXmlNode.Name == "val" then addinfo.val = childChildXmlNode.InnerText end end tips = tips .. "£¬" .. string.format("%s+%s", equip.getCarAttrName(addinfo.name), addinfo.val or "δ֪ÊýÖµ") end end ILogger():logInfo(tips) return true end equip.useXuli = function(name, composite) local url = "/root/equip!useXuli.action" local data = string.format("composite=%d", composite) local result = ProtocolMgr():postXml(url, data, "×°±¸-ʹÓÃÐîÁ¦") if not result or not result.CmdSucceed then return false end -- ILogger():logInfo(result.CmdResult.InnerXml) local tips = string.format("%sʹÓÃÐîÁ¦", name) local cmdResult = result.CmdResult local xmlNode = cmdResult:SelectSingleNode("/results/xuliinfo/getevent") local getevent = xmlNode and tonumber(xmlNode.InnerText) or 0 if getevent == 1 then xmlNode = cmdResult:SelectSingleNode("/results/xuliinfo/gethighnum") local gethighnum = xmlNode and tonumber(xmlNode.InnerText) or 0 if gethighnum > 0 then tips = tips .. string.format("£¬ÆÕͨǿ»¯´ÎÊý+%d", gethighnum) end elseif getevent == 2 then xmlNode = cmdResult:SelectSingleNode("/results/xuliinfo/addinfo/val") local val = xmlNode and tonumber(xmlNode.InnerText) or 0 xmlNode = cmdResult:SelectSingleNode("/results/xuliinfo/addinfo/name") if val > 0 then tips = tips .. string.format("£¬%s+%d", equip.getCarAttrName(xmlNode.InnerText), val) end elseif getevent == 3 then xmlNode = cmdResult:SelectSingleNode("/results/xuliinfo/newattr") local newattr = global.split(xmlNode.InnerText, ",") for i, v in ipairs(newattr) do if tonumber(v) > 0 then tips = tips .. string.format("£¬%s+%s", equip.getAttrName(i), v) end end end ILogger():logInfo(tips) return true end equip.getCarAttrName = function(name) if name == "att" then return "ÆÕ¹¥" elseif name == "def" then return "ÆÕ·À" elseif name == "satt" then return "Õ½¹¥" elseif name == "sdef" then return "Õ½·À" elseif name == "stgatt" then return "²ß¹¥" elseif name == "stgdef" then return "²ß·À" elseif name == "hp" then return "±øÁ¦" end end equip.getAttrName = function(num) if num == 1 then return "ͳ" elseif num == 2 then return "ÓÂ" elseif num == 3 then return "ÖÇ" end end
mit
Cloudef/darkstar
scripts/zones/Garlaige_Citadel/npcs/qm18.lua
5
1809
----------------------------------- -- Area: Garlaige Citadel -- NPC: qm18 (??? - Bomb Coal Fragments) -- Involved in Quest: In Defiant Challenge -- !pos -13.425,-1.176,191.669 200 ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Garlaige_Citadel/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1090) == false and player:hasKeyItem(BOMB_COAL_FRAGMENT1) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(BOMB_COAL_FRAGMENT1); player:messageSpecial(KEYITEM_OBTAINED,BOMB_COAL_FRAGMENT1); end if (player:hasKeyItem(BOMB_COAL_FRAGMENT1) and player:hasKeyItem(BOMB_COAL_FRAGMENT2) and player:hasKeyItem(BOMB_COAL_FRAGMENT3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1090, 1); player:messageSpecial(ITEM_OBTAINED, 1090); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1090); end end if (player:hasItem(1090)) then player:delKeyItem(BOMB_COAL_FRAGMENT1); player:delKeyItem(BOMB_COAL_FRAGMENT2); player:delKeyItem(BOMB_COAL_FRAGMENT3); end end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
fgprodigal/RayUI
Interface/AddOns/RayUI/libs/cargBags/mixins-add/itemkeys/basic.lua
2
1704
--[[ LICENSE cargBags: An inventory framework addon for World of Warcraft Copyright (C) 2010 Constantin "Cargor" Schomburg <xconstruct@gmail.com> cargBags is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. cargBags 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 cargBags; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. DESCRIPTION: A few simple item keys, mostly ones resulting through pattern matching ]] ---------------------------------------------------------- -- Load RayUI Environment ---------------------------------------------------------- RayUI:LoadEnv("Bags") local cargBags = _cargBags -- Returns the numeric item id (12345) cargBags.itemKeys["id"] = function(i) return i.link and tonumber(i.link:match("item:(%d+)")) end -- Returns the type of the parent bag cargBags.itemKeys["bagType"] = function(i) return select(2, GetContainerNumFreeSlots(i.bagID)) end -- Returns the item string (12345:0:0:0) cargBags.itemKeys["string"] = function(i) return i.link and i.link:match("item:(%d+:%d+:%d+:%d+)") end cargBags.itemKeys["stats"] = function(i) if(not i.link or not GetItemStats) then return end local stats = GetItemStats(i.link) i.stats = stats return stats end
mit
MinetestForFun/server-minetestforfun
mods/framedglass/init.lua
10
4388
-- Minetest 0.4.7 mod: framedglass minetest.register_craft({ output = 'framedglass:wooden_framed_glass 4', recipe = { {'default:glass', 'default:glass', 'default:stick'}, {'default:glass', 'default:glass', 'default:stick'}, {'default:stick', 'default:stick', ''}, } }) minetest.register_craft({ output = 'framedglass:steel_framed_glass 4', recipe = { {'default:glass', 'default:glass', 'default:steel_ingot'}, {'default:glass', 'default:glass', 'default:steel_ingot'}, {'default:steel_ingot', 'default:steel_ingot', ''}, } }) minetest.register_craft({ output = 'framedglass:wooden_framed_obsidian_glass 4', recipe = { {'default:obsidian_glass', 'default:obsidian_glass', 'default:stick'}, {'default:obsidian_glass', 'default:obsidian_glass', 'default:stick'}, {'default:stick', 'default:stick', ''}, } }) minetest.register_craft({ output = 'framedglass:steel_framed_obsidian_glass 4', recipe = { {'default:obsidian_glass', 'default:obsidian_glass', 'default:steel_ingot'}, {'default:obsidian_glass', 'default:obsidian_glass', 'default:steel_ingot'}, {'default:steel_ingot', 'default:steel_ingot', ''}, } }) minetest.register_node("framedglass:wooden_framed_glass", { description = "Wooden-framed Glass", drawtype = "glasslike_framed_optional", tiles = {"framedglass_woodenglass_face_streaks_frame.png","framedglass_glass_face_streaks.png"}, paramtype = "light", sunlight_propagates = true, groups = {cracky=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_glass_defaults(), }) minetest.register_node("framedglass:steel_framed_glass", { description = "Steel-framed Glass", drawtype = "glasslike_framed_optional", tiles = {"framedglass_steelglass_face_streaks_frame.png","framedglass_glass_face_streaks.png"}, paramtype = "light", sunlight_propagates = true, groups = {cracky=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_glass_defaults(), }) minetest.register_node("framedglass:wooden_framed_obsidian_glass", { description = "Wooden-framed Obsidian Glass", drawtype = "glasslike_framed_optional", tiles = {"framedglass_woodenglass_face_clean_frame.png","framedglass_glass_face_clean.png"}, paramtype = "light", sunlight_propagates = true, groups = {cracky=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_glass_defaults(), }) minetest.register_node("framedglass:steel_framed_obsidian_glass", { description = "Steel-framed Obsidian Glass", drawtype = "glasslike_framed_optional", tiles = {"framedglass_steelglass_face_clean_frame.png","framedglass_glass_face_clean.png"}, paramtype = "light", sunlight_propagates = true, groups = {cracky=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_glass_defaults(), }) function add_coloured_framedglass(name, desc, dye) minetest.register_node( "framedglass:steel_framed_obsidian_glass"..name, { description = "Steel-framed "..desc.." Obsidian Glass", tiles = {"framedglass_".. name.. "glass_frame.png", "framedglass_".. name.. "glass.png"}, drawtype = "glasslike_framed_optional", paramtype = "light", sunlight_propagates = true, is_ground_content = true, use_texture_alpha = true, groups = {cracky=3}, sounds = default.node_sound_glass_defaults(), }) minetest.register_craft({ type = "shapeless", output = "framedglass:steel_framed_obsidian_glass"..name, recipe = { "framedglass:steel_framed_glass", "group:basecolor_white", dye } }) end add_coloured_framedglass ("red","Red","group:basecolor_red") add_coloured_framedglass ("green","Green","group:basecolor_green") add_coloured_framedglass ("blue","Blue","group:basecolor_blue") add_coloured_framedglass ("cyan","Cyan","group:basecolor_cyan") add_coloured_framedglass ("darkgreen","Dark Green","group:unicolor_dark_green") add_coloured_framedglass ("violet","Violet","group:excolor_violet") add_coloured_framedglass ("pink","Pink","group:unicolor_light_red") add_coloured_framedglass ("yellow","Yellow","group:basecolor_yellow") add_coloured_framedglass ("orange","Orange","group:basecolor_orange") add_coloured_framedglass ("brown","Brown","group:unicolor_dark_orange") add_coloured_framedglass ("white","White","group:basecolor_white") add_coloured_framedglass ("grey","Grey","group:basecolor_grey") add_coloured_framedglass ("darkgrey","Dark Grey","group:excolor_darkgrey") add_coloured_framedglass ("black","Black","group:basecolor_black")
unlicense
Cloudef/darkstar
scripts/zones/Fort_Karugo-Narugo_[S]/npcs/Indescript_Markings.lua
2
1951
---------------------------------- -- Area: Fort Karugo Narugo [S] -- NPC: Indescript Markings -- Type: Quest -- @zone 96 -- !pos -63 -75 4 ----------------------------------- package.loaded["scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/npc_util"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local loafersQuestProgress = player:getVar("AF_SCH_BOOTS"); player:delStatusEffect(dsp.effects.SNEAK); -- SCH AF Quest - Boots if (loafersQuestProgress > 0 and loafersQuestProgress < 3 and player:hasKeyItem(RAFFLESIA_DREAMSPIT) == false) then player:addKeyItem(RAFFLESIA_DREAMSPIT); player:messageSpecial(KEYITEM_OBTAINED, RAFFLESIA_DREAMSPIT); player:setVar("AF_SCH_BOOTS", loafersQuestProgress + 1); -- Move the markings around local positions = { [1] = {-72.612, -28.5, 671.24}, -- G-5 NE [2] = {-158, -61, 268}, -- G-7 [3] = {-2, -52, 235}, -- H-8 [4] = {224, -28, -22}, -- I-10 [5] = {210, -42, -78}, -- I-9 [6] = {-176, -37, 617}, -- G-5 SW [7] = {29, -13, 710} -- H-5 }; local newPosition = npcUtil.pickNewPosition(npc:getID(), positions); npc:setPos(newPosition.x, newPosition.y, newPosition.z); -- player:PrintToPlayer("Markings moved to position index " .. newPosition); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Cloudef/darkstar
scripts/zones/Kazham/npcs/Rauteinot.lua
5
2783
----------------------------------- -- Area: Kazham -- NPC: Rauteinot -- Starts and Finishes Quest: Missionary Man -- @zone 250 -- !pos -42 -10 -89 ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Kazham/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("MissionaryManVar") == 1 and trade:hasItemQty(1146,1) == true and trade:getItemCount() == 1) then player:startEvent(139); -- Trading elshimo marble end end; function onTrigger(player,npc) MissionaryMan = player:getQuestStatus(OUTLANDS,MISSIONARY_MAN); MissionaryManVar = player:getVar("MissionaryManVar"); if (MissionaryMan == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 3) then player:startEvent(137,0,1146); -- Start quest "Missionary Man" elseif (MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 1) then player:startEvent(138,0,1146); -- During quest (before trade marble) "Missionary Man" elseif (MissionaryMan == QUEST_ACCEPTED and (MissionaryManVar == 2 or MissionaryManVar == 3)) then player:startEvent(140); -- During quest (after trade marble) "Missionary Man" elseif (MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 4) then player:startEvent(141); -- Finish quest "Missionary Man" elseif (MissionaryMan == QUEST_COMPLETED) then player:startEvent(142); -- New standard dialog else player:startEvent(136); -- Standard dialog end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 137 and option == 1) then player:addQuest(OUTLANDS,MISSIONARY_MAN); player:setVar("MissionaryManVar",1); elseif (csid == 139) then player:setVar("MissionaryManVar",2); player:addKeyItem(RAUTEINOTS_PARCEL); player:messageSpecial(KEYITEM_OBTAINED,RAUTEINOTS_PARCEL); player:tradeComplete(); elseif (csid == 141) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4728); else player:setVar("MissionaryManVar",0); player:delKeyItem(SUBLIME_STATUE_OF_THE_GODDESS); player:addItem(4728); player:messageSpecial(ITEM_OBTAINED,4728); player:addFame(WINDURST,30); player:completeQuest(OUTLANDS,MISSIONARY_MAN); end end end;
gpl-3.0
tst2005googlecode/fbclient
lua/fbclient/decimal_ldecnumber.lua
2
2119
--[=[ ldecnumber binding for decnumber decimal number support df(lo,hi,scale) -> d; to be used with getdecimal() sdf(d,scale) -> lo,hi; to be used with setdecimal() decnumber_meta -> ldecNumber.number_metatable isdecnumber(x) -> true|false; the decnumber library should provide this but since it doesn't... xsqlvar:getdecnumber() -> d xsqlvar:setdecnumber(d) xsqlvar:set(d), extended to support decnumber-type decimals xsqlvar:get() -> d, extended to support decnumber-type decimals USAGE: just require this module if you have ldecnumber installed. LIMITATIONS: - assumes 2's complement signed int64 format (no byte order assumption though). ]=] module(...,require 'fbclient.module') local decNumber = require 'ldecNumber' local xsqlvar_class = require('fbclient.xsqlvar').xsqlvar_class decnumber_meta = decNumber.number_metatable -- convert the lo,hi dword pairs of a 64bit integer into a decimal number and scale it down. function df(lo,hi,scale) return decNumber.fma(hi,2^32,lo):scaleb(scale) -- translation: (hi*2^32+lo)*10^scale end -- scale up a decimal number and convert it into the corresponding lo,hi dword pairs of its int64 representation. function sdf(d,scale) d = d:scaleb(-scale) -- translation: d*10^-scale -- TODO: find a way to avoid temporary string creation: this is embarrasing and humiliating. -- TODO: find a faster way to divide than mod() and floor() which are combinations of multiple functions. local lo,hi = tonumber(d:mod(2^32):tostring()), tonumber(d:floor(2^32):tostring()) return lo,hi end function xsqlvar_class:getdecnumber() return self:getdecimal(df) end function xsqlvar_class:setdecnumber(d) self:setdecimal(d,sdf) end function isdecnumber(p) return getmetatable(p) == decnumber_meta end xsqlvar_class:add_set_handler( function(self,p,typ,opt) if isdecnumber(p) and (typ == 'int16' or typ == 'int32' or typ == 'int64') then self:setdecnumber(p) return true end end ) xsqlvar_class:add_get_handler( function(self,typ,opt) if typ == 'int16' or typ == 'int32' or typ == 'int64' then return true,self:getdecnumber() end end )
mit
MinetestForFun/server-minetestforfun
mods/colormachine/init.lua
8
95030
--[[ color chooser for unifieddyes Copyright (C) 2013 Sokomine This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] -- Version 0.6 -- Changelog: -- 23.05.15 As all dyes can be crafted into other dyes, only white dye is consumed - provided the -- other dyes needed for the crafting chain are stored. -- 22.05.15 Added support for new homedecor meshnodes. -- Added support for nodes that use composed textures (by settig composed=1) -- Added support for myroofs: https://forum.minetest.net/viewtopic.php?f=11&t=11416&p=172034 -- Added support for mydeck: https://forum.minetest.net/viewtopic.php?f=9&t=11729 -- Added support for mycorners: https://forum.minetest.net/viewtopic.php?f=11&t=11363 -- Added support for mymulch: https://forum.minetest.net/viewtopic.php?f=9&t=11780 -- Added support for clothing: https://forum.minetest.net/viewtopic.php?f=9&t=11362&p=179077 -- Added better handling of diffrent pages for all those blocks in the blocktype menu. -- 17.09.14 Added a modified version of Krocks paintroller from his paint_roller mod. -- Added additional storage area for dyes (works like a chest for now) -- 03.09.14 Added a second block type menu. -- Updated dependency list. -- Added support for homedecor kitchen chairs, beds and bathroom tiles. Changed sorting order of blocks. -- 11.06.14 Added support for clstone; see https://forum.minetest.net/viewtopic.php?f=9&t=9257 -- Changed dye source for white dye from stone to clay as stone can now be colored. -- Added support for colorcubes; see https://forum.minetest.net/viewtopic.php?f=9&t=9486 -- Updated support for new sea modpack; see https://forum.minetest.net/viewtopic.php?f=11&t=4627 -- Adjusted support for hardenedclay; see https://forum.minetest.net/viewtopic.php?f=9&t=8232 -- Added support for new blox blocks; see https://forum.minetest.net/viewtopic.php?id=1960#p24748 -- Made the formspec a bit wider in order to account for all the new blocks. -- 12.03.14 Added support for colouredstonebricks. See https://forum.minetest.net/viewtopic.php?f=9&t=8784 -- Modified support for hardenedclay due to progress in that mod. -- 13.02.14 Added support for chests and locked chests from the kerova mod. -- Added support for hardenedclay mod (to a degree; that mod needs to be fixed first) -- Added optional obj_postfix support where blocknames are like MODNAME:PREFIX_COLOR_POSTFIX -- 01.01.14 Added support for plasticbox mod -- 25.08.13 Added support for framedglass from technic. -- Added support for shells_dye (lightglass) from the sea mod. -- 24.08.13 Changed mainmenu so that it hopefully gets more intuitive. -- Added support for coloredblocks (two-colored blocks). -- Changed name of superglowglass to super_glow_glass for current moreblocks. -- Added config option for new stained_glass version. -- 02.08.13 In creative mode, no dyes are consumed, and an entire stack can be painted at once. -- Added some more labels in the main menu to make it easier to understand. -- 22.07.13 Added textures provided by Vanessae -- fixed a bug concerning normal dyes (when unifieddyes is not installed) -- adds a function to check ownership of a node; taken from VanessaEs homedecor mod colormachine = {}; colormachine.colors = { "red", "orange", "yellow", "lime", "green", "aqua", "cyan", "skyblue", "blue", "violet", "magenta", "redviolet" } -- set this to 0 if you're using that branch of stained_glass where the node names correspond to those of unified_dyes local stained_glass_exception = 0; -- the names of suitable sources of that color (note: this does not work by group!); -- you can add your own color sources here if you want colormachine.basic_dye_sources = { "flowers:rose", "flowers:tulip", "flowers:dandelion_yellow", "", "default:cactus", "", "", "", -- no lime, no aqua, no cyan, no skyblue "flowers:geranium", "flowers:viola", "", "", -- no magenta, no redviolet "default:clay_lump", "", "", "", "default:coal_lump" }; -- if flowers is not installed colormachine.alternate_basic_dye_sources = { "default:apple", "default:desert_stone", "default:sand", "", "default:cactus", "", "", "", "default:leaves", "", "", "" , "default:clay_lump", "", "", "", "default:coal_lump" }; colormachine.dye_mixes = { red = {}, -- base color orange = {1,3}, -- red + yellow yellow = {}, -- base color lime = {3,5}, -- yellow + green green = {3,9}, -- yellow + blue aqua = {5,7}, -- green + cyan cyan = {5,9}, -- green + blue skyblue = {7,9}, -- cyan + blue blue = {}, -- base color violet = {9,11}, -- blue + magenta magenta = {9,1}, -- blue + red redviolet = {11,1}, -- magenta + red white = {}, -- base color lightgrey = {13,15}, -- white + grey grey = {13,17}, -- black + white darkgrey = {15,17}, -- grey + black black = {}, -- base color } -- construct the formspec for the color selector colormachine.prefixes = { 'light_', '', 'medium_', 'dark_' }; -- grey colors are named slightly different colormachine.grey_names = { 'white', 'lightgrey', 'grey', 'darkgrey', 'black' }; -- practical for handling of the dyes colormachine.colors_and_greys = {}; for i,v in ipairs( colormachine.colors ) do colormachine.colors_and_greys[ i ] = v; end for i,v in ipairs( colormachine.grey_names ) do colormachine.colors_and_greys[ #colormachine.colors + i ] = v; end -- defines the order in which blocks are shown -- nr: the diffrent block types need to be ordered by some system; the number defines that order -- modname: some mods define more than one type of colored blocks; the modname is needed -- for checking if the mod is installed and for creating colored blocks -- shades: some mods (or parts thereof) do not support all possible shades -- grey_shades: some mods support only some shades of grey (or none at all) -- u: if set to 1, use full unifieddyes-colors; if set to 0, use only normal dye/wool colors -- descr: short description of nodes of that type for the main menu -- block: unpainted basic block -- add: item names are formed by <modname>:<add><colorname> (with colorname beeing variable) -- names for the textures are formed by <index><colorname><png> mostly (see colormachine.translate_color_name(..)) colormachine.data = { -- the dyes as such unifieddyes_ = { nr=1, modname='unifieddyes', shades={1,0,1,1,1,1,1,1}, grey_shades={1,1,1,1,1}, u=1, descr="ufdye", block="dye:white", add="", p=1 }, -- coloredwood: sticks not supported (they are only craftitems) coloredwood_wood_ = { nr=2, modname='coloredwood', shades={1,0,1,1,1,1,1,1}, grey_shades={1,1,1,1,1}, u=1, descr="planks", block="default:wood", add="wood_", p=2 }, coloredwood_fence_ = { nr=3, modname='coloredwood', shades={1,0,1,1,1,1,1,1}, grey_shades={1,1,1,1,1}, u=1, descr="fence", block="default:fence_wood", add="fence_", p=2}, -- unifiedbricks: clay lumps and bricks not supported (they are only craftitems) unifiedbricks_clayblock_ = { nr=4, modname='unifiedbricks', shades={1,0,1,1,1,1,1,1}, grey_shades={1,1,1,1,1}, u=1, descr="clay", block="default:clay", add="clayblock_",p=1 }, unifiedbricks_brickblock_ = { nr=5, modname='unifiedbricks', shades={1,0,1,1,1,1,1,1}, grey_shades={1,1,1,1,1}, u=1, descr="brick", block="default:brick", add="brickblock_",p=1}, -- the multicolored bricks come in fewer intensities (only 3 shades) and support only 3 insted of 5 shades of grey unifiedbricks_multicolor_ = { nr=6, modname='unifiedbricks', shades={1,0,0,0,1,0,1,0}, grey_shades={0,1,1,1,0}, u=1, descr="mbrick", block="default:brick", add="multicolor_",p=1}, hardenedclay_ = { nr=3.5, modname='hardenedclay', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="hclay", block="hardenedclay:hardened_clay_white", add="hardened_clay_", p=16}, colouredstonebricks_ = { nr=3.6, modname='colouredstonebricks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="cbrick", block="default:stonebrick", add="", p=1}, clstone_stone_ = { nr=3.7, modname='clstone', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="clstone",block="default:stone", add="", p=1, obj_postfix='_stone' }, colorcubes_1_ = { nr=3.8, modname='colorcubes', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="ccubes",block="default:stone", add="", p=1, obj_postfix='_single' }, colorcubes_4_ = { nr=3.9, modname='colorcubes', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="ccube4",block="default:stone", add="", p=1, obj_postfix='_tiled' }, colorcubes_inward_ = { nr=3.91,modname='colorcubes', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="ccubei",block="default:stone", add="", p=1, obj_postfix='_inward' }, colorcubes_window_ = { nr=3.93,modname='colorcubes', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="ccubew",block="default:stone", add="", p=1, obj_postfix='_window' }, -- stained_glass: has a "faint" and "pastel" version as well (which are kind of additional shades used only by this mod) -- no shades of grey for the glass stained_glass_ = { nr=7, modname='stained_glass', shades={1,0,1,1,1,1,1,1}, grey_shades={0,0,0,0,0}, u=1, descr="glass", block="moreblocks:super_glow_glass", add="",p=2}, stained_glass_faint_ = { nr=8, modname='stained_glass', shades={0,0,1,0,0,0,0,0}, grey_shades={0,0,0,0,0}, u=1, descr="fglass", block="moreblocks:super_glow_glass", add="",p=2}, stained_glass_pastel_ = { nr=9, modname='stained_glass', shades={0,0,1,0,0,0,0,0}, grey_shades={0,0,0,0,0}, u=1, descr="pglass", block="moreblocks:super_glow_glass", add="",p=2}, -- use 9.5 to insert it between stained glass and cotton framedglass_ = { nr=9.5, modname='framedglass', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="fglass", block="framedglass:steel_framed_obsidian_glass", add="steel_framed_obsidian_glass",p=1}, -- sea-modpack shells_dye_ = { nr=9.6, modname='shells_dye', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="lglass", block="shells_dye:whitelightglass", add="",p=1 }, -- TODO shells_dye:whitelightglass seaglass_seaglass_ = {nr=9.61, modname='seaglass', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="seagls", block="seaglass:seaglass", add="seaglass_", p=1}, seacobble_seacobble_ = {nr=9.62, modname='seacobble', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=1, descr="seacob", block="seacobble:seacobble", add="seacobble_", p=1}, seastone_seastone_ = {nr=9.63, modname='seastone', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=1, descr="seasto", block="seastone:seastone", add="seastone_", p=1}, seastonebrick_seastonebrick_={nr=9.64,modname='seastonebrick',shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=1, descr="seastb", block="seastonebrick:seastonebrick", add="seastonebrick_", p=1}, seagravel_seagravel_ = {nr=9.65, modname='seagravel', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=1, descr="seagrv", block="seagravel:seagravel", add="seagravel_", p=1}, -- cotton: cotton_ = { nr=10, modname='cotton', shades={1,0,1,1,1,1,1,1}, grey_shades={1,1,1,1,1}, u=1, descr="cotton", block="cotton:white", add="", p=8 }, -- normal wool (from minetest_gmae) - does not support all colors from unifieddyes wool_ = { nr=11, modname='wool', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="wool", block="wool:white", add="", p=16 }, -- normal dye mod (from minetest_game) - supports as many colors as the wool mod dye_ = { nr=12, modname='dye', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="dye", block="dye:white", add="", p=1 }, -- beds_bed_top_top_ = { nr=13, modname='beds', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,1,0,1}, u=0, descr="beds", block="beds:bed_white", add="bed_bottom_",p=1}, lrfurn_armchair_front_ = { nr=14, modname='lrfurn', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,1,0,1}, u=0, descr="armchair",block="lrfurn:armchair_white", add="armchair_",p=1, composed=1 }, lrfurn_sofa_right_front_ = { nr=15, modname='lrfurn', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,1,0,1}, u=0, descr="sofa", block="lrfurn:longsofa_white", add="sofa_right_",p=1, composed=1 }, lrfurn_longsofa_middle_front_= { nr=16, modname='lrfurn', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,1,0,1}, u=0, descr="longsofa",block="lrfurn:sofa_white", add="longsofa_right_",p=1, composed=1 }, -- grey variants do not seem to exist, even though the textures arethere (perhaps nobody wants a grey flag!) flags_ = { nr=17, modname='flags', shades={0,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=1, descr="flags", block="flags:white", add="", p=3 }, blox_stone_ = { nr=18, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="SnBlox", block="default:stone", add="stone", p=2 }, blox_quarter_ = { nr=19, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="S4Blox", block="default:stone", add="quarter", p=4 }, blox_checker_ = { nr=20, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="S8Blox", block="default:stone", add="checker", p=4 }, blox_diamond_ = { nr=21, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="SDBlox", block="default:stone", add="diamond", p=3}, blox_cross_ = { nr=22, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="SXBlox", block="default:stone", add="cross", p=6 }, blox_square_ = { nr=23, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="SQBlox", block="default:stone", add="square", p=4 }, blox_loop_ = { nr=24, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="SLBlox", block="default:stone", add="loop", p=4 }, blox_corner_ = { nr=25, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="SCBlox", block="default:stone", add="corner", p=6 }, blox_wood_ = { nr=26, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="WnBlox", block="default:wood", add="wood", p=2 }, blox_quarter_wood_ = { nr=27, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="W4Blox", block="default:wood", add="quarter_wood",p=4 }, blox_checker_wood_ = { nr=28, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="W8Blox", block="default:wood", add="checker_wood",p=4}, blox_diamond_wood_ = { nr=29, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="WDBlox", block="default:wood", add="diamond_wood",p=4}, blox_cross_wood_ = { nr=29.1, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="WXBlox", block="default:wood", add="cross_wood",p=4}, blox_loop_wood_ = { nr=29.3, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="WLBlox", block="default:wood", add="loop_wood",p=4}, blox_corner_wood_ = { nr=29.4, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="WCBlox", block="default:wood", add="corner_wood",p=4}, blox_cobble_ = { nr=30, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="CnBlox", block="default:cobble", add="cobble",p=2 }, blox_quarter_cobble_ = { nr=30.1, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="C4Blox", block="default:cobble", add="quarter_cobble",p=4 }, blox_checker_cobble_ = { nr=30.2, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="C8Blox", block="default:cobble", add="checker_cobble",p=4}, blox_diamond_cobble_ = { nr=30.3, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="CDBlox", block="default:cobble", add="diamond_cobble",p=4}, blox_cross_cobble_ = { nr=30.4, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="CXBlox", block="default:cobble", add="cross_cobble",p=4}, blox_loop_cobble_ = { nr=30.6, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="CLBlox", block="default:cobble", add="loop_cobble",p=4}, blox_corner_cobble_ = { nr=30.7, modname='blox', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,1}, u=0, descr="CCBlox", block="default:cobble", add="corner_cobble",p=4}, homedecor_window_shutter_ = { nr=16.1, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="homedec", block="homedecor:shutter_oak", add="shutter_",p=16,composed=1}, forniture_armchair_top_ = { nr=16.2, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={0,0,0,0,1}, u=0, descr="armchair", block="homedecor:armchair_black", add="armchair_",p=1,composed=1}, forniture_kitchen_chair_sides_ = {nr=16.3, modname='homedecor',shades={1,0,1,0,0,0,1,0}, grey_shades={0,0,0,0,1}, u=0, descr="kchair", block="homedecor:chair", add="chair_",p=1,composed=1}, homedecor_bed_ = {nr=16.4, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="hbed", block="homedecor:bed_darkgrey_regular", add="bed_",p=1, obj_postfix='_regular', composed=1}, homedecor_bed_kingsize_ = {nr=16.45, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="hbedk", block="homedecor:bed_darkgrey_kingsize", add="bed_",p=1, obj_postfix='_kingsize', composed=1}, homedecor_bathroom_tiles_ = {nr=16.5, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="htiles", block="homedecor:tiles_1", add="tiles_",p=1,composed=1}, homedecor_curtain_ = { nr=16.6, modname='homedecor', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,0}, u=0, descr="curtain", block="homedecor:curtain_white", add="curtain_",composed=1}, homedecor_curtain_open_ = { nr=16.61, modname='homedecor', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,0}, u=0, descr="ocurtain", block="homedecor:curtain_open_white", add="curtain_open_", composed=1}, homedecor_desk_lamp_ = { nr=16.62, modname='homedecor', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,0}, u=0, descr="dlamp", block="homedecor:desk_lamp_blue", add="desk_lamp_", composed=1}, homedecor_table_lamp_ = { nr=16.63, modname='homedecor', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,0}, u=0, descr="tlamp", block="homedecor:table_lamp_white_off", add="table_lamp_", composed=1, obj_postfix='_off'}, homedecor_standing_lamp_ = { nr=16.64, modname='homedecor', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,0}, u=0, descr="slamp", block="homedecor:standing_lamp_white_off", add="standing_lamp_", composed=1, obj_postfix='_off'}, lavalamp_ = { nr=16.644, modname='lavalamp', shades={1,0,1,0,0,0,0,0}, grey_shades={1,0,0,0,0}, u=0, descr="lavalamp", block="lavalamp:blue", add="", composed=1}, homedecor_table_ = { nr=16,645,modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,0,0}, u=0, descr="htable", block="homedecor:table", add="table_", composed=1}, homedecor_book_ = { nr=16.65, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,0,0}, u=0, descr="hbook", block="default:book", add="book_", composed=1}, homedecor_bottle_ = { nr=16.66, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,0}, u=0, descr="hbottle", block="vessels:glass_bottle", add="bottle_", composed=1}, homedecor_welcome_mat_ = { nr=16.67, modname='homedecor', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,0,0}, u=0, descr="hwmat", block="homedecor:welcome_mat_grey", add="welcome_mat_", composed=1}, plasticbox_ = { nr=16.7, modname='plasticbox', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="plastic", block="plasticbox:plasticbox", add="plasticbox_",p=16}, kerova_chest_front_ = { nr=16.8, modname='kerova', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="kerova", block="default:chest", add="chest_",p=16}, kerova_chest_lock_ = { nr=16.9, modname='kerova', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="kerolo", block="default:chest_locked", add="chest_", obj_postfix='_locked',p=16}, coloredblocks_red_ = { nr=34, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_red", block="coloredblocks:white_white", add="red_",p=1}, coloredblocks_yellow_ = { nr=35, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_yel", block="coloredblocks:white_white", add="yellow_",p=1}, coloredblocks_green_ = { nr=36, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_gre", block="coloredblocks:white_white", add="green_",p=1}, coloredblocks_cyan_ = { nr=37, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_cya", block="coloredblocks:white_white", add="cyan_",p=1}, coloredblocks_blue_ = { nr=38, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_blu", block="coloredblocks:white_white", add="blue_",p=1}, coloredblocks_magenta_ = { nr=39, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_mag", block="coloredblocks:white_white", add="magenta_",p=1}, coloredblocks_brown_ = { nr=40, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_bro", block="coloredblocks:white_white", add="brown_",p=1}, coloredblocks_white_ = { nr=41, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_whi", block="coloredblocks:white_white", add="white_",p=1}, coloredblocks_black_ = { nr=42, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_bla", block="coloredblocks:white_white", add="black_",p=1}, --[[ coloredblocks_red_ = { nr=34, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_red", block="coloredblocks:red", add="red_",p=1}, coloredblocks_yellow_ = { nr=35, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_yel", block="coloredblocks:yellow", add="yellow_",p=1}, coloredblocks_green_ = { nr=36, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_gre", block="coloredblocks:green", add="green_",p=1}, coloredblocks_cyan_ = { nr=37, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_cya", block="coloredblocks:cyan", add="cyan_",p=1}, coloredblocks_blue_ = { nr=38, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_blu", block="coloredblocks:blue", add="blue_",p=1}, coloredblocks_magenta_ = { nr=39, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_mag", block="coloredblocks:magenta", add="magenta_",p=1}, coloredblocks_brown_ = { nr=40, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_bro", block="coloredblocks:brown", add="brown_",p=1}, coloredblocks_white_ = { nr=41, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_whi", block="coloredblocks:white", add="",p=1}, coloredblocks_black_ = { nr=42, modname='coloredblocks', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,0,0,1}, u=0, descr="cb_bla", block="coloredblocks:black", add="black_",p=1}, --]] clothing_inv_hat_ = { nr=43, modname='clothing', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="clhat", block="clothing:hat_white", add="hat_",p=1}, clothing_inv_shirt_ = { nr=44, modname='clothing', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="clshirt", block="clothing:shirt_white", add="shirt_",p=1}, clothing_inv_pants_ = { nr=45, modname='clothing', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="clpants", block="clothing:pants_white", add="pants_",p=1}, clothing_inv_cape_ = { nr=46, modname='clothing', shades={1,0,1,0,0,0,1,0}, grey_shades={1,0,1,1,1}, u=0, descr="clcape", block="clothing:cape_white", add="cape_",p=1}, } local mydeck_names = {'deck_boards','deck_beam', 'deck_joists','deck_joists_side','deck_joists_end','deck_joists_side_end','deck_joists_endr','deck_joists_side_endr', 'beam','beam_wbracket', 'joists_beam','joists_beam_wbracket','joists_side_beam','joists_side_beam_wbracket', 'deck_joists_beam','deck_joists_beam_wbracket','deck_joists_side_beam','deck_joists_side_beam_wbracket', 'joists','joists_side','joists_end','joists_side_end','joists_endr','joists_side_endr', 'lattice','pile_wpost','post', 'rail','rail_corner','rail_icorner', 'stairs','stairsb','stairs_ocorner','stairs_icorner','stairs_railr','stairs_raill','stairs_railr_end','stairs_raill_end'}; for i,v in ipairs( mydeck_names ) do colormachine.data[ v..'s_' ] = { nr= 47.0 + 1/100*i, modname='mydeck', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="myd"..tostring(i), block="mydeck:"..v, add=v.."s_", composed=1, p=1}; end mydeck_names = nil; local myroofs_names = {'', '_bundle', '_icorner','_ocorner', '_round_bundle', '_round_long', '_round_long_icorner', '_round_long_ocorner', '_long', '_long_icorner', '_long_ocorner'}; for i,v in ipairs( myroofs_names ) do colormachine.data[ 'myroofs'..v..'_' ] = { nr= 48.0 + 1/100*i, modname='myroofs', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="myr"..tostring(i), block="myroofs:asphalt_shingle_grey"..v, add='asphalt_shingle_', obj_postfix=v, composed=1, p=1}; end myroof_names = nil; local mycorner_names = {'wood','stone','stonebrick'} local mycorner_materials = { 'default_sandstone','default_clay','default_cobble','default_stone', 'default_desert_stone','default_wood','default_pinewood','default_brick', 'default_desert_cobble','default_junglewood','default_mossycobble', 'default_sandstone_brick','default_desert_stone_brick','default_stone_brick'}; for i,v in ipairs( mycorner_names ) do colormachine.data[ 'corners_'..v..'_' ] = { nr= 49.0 + 1/100*i, modname='mycorners', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="myc"..v, block="mycorners:corner_"..v..'_white', add='corner_'..v..'_', p=1}; for j,m in ipairs( mycorner_materials ) do colormachine.data[ 'cornerblock_'..m..'_'..v..'_' ] = { nr= 49.5 + 1/100*i + 1/1000*j, modname='mycorners', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="myc"..tostring(j)..v, block="mycorners:cornerblock_"..m..'_'..v..'_white', add='cornerblock_'..m..'_'..v..'_', composed=1, p=1}; end end mycorner_materials = nil; mycorner_names = nil; colormachine.data[ 'mymulch_' ] = { nr= 50, modname='mymulch', shades={1,0,1,0,0,0,1,0}, grey_shades={1,1,1,1,1}, u=0, descr="mymulch", block="mymulch:mulch_tan", add='mulch_', composed=1, p=1}; colormachine.ordered = {} -- the function that creates the color chooser based on the textures of the nodes offered (texture names have to start with m_prefix) colormachine.generate_form = function( m_prefix ) local form = "size["..tostring( #colormachine.colors+2 )..",10]".."label[5,0;Select a color:]".. "label[5,8.2;Select a color or]".. "button[7,8.2;2,1;abort;abort selection]".. "label[0.3,1;light]"; -- not all mods offer all shades (and some offer even more) local supported = colormachine.data[ m_prefix ].shades; if( supported[2]==0 ) then form = form.. "label[0.3,2;normal]".. "label[0.3,4;medium]".. "label[0.3,6;dark]"; else form = form.. "label[0.3,3;normal]".. "label[0.3,5;medium]".. "label[0.3,7;dark]"; end for x,basecolor in ipairs( colormachine.colors ) do local p_offset = 1; form = form.."label["..tostring(x)..",0.5;"..tostring( basecolor ).."]"; for y,pre in ipairs( colormachine.prefixes ) do if( supported[ y * 2-1 ]==1 ) then form = form..colormachine.print_color_image( nil, m_prefix, tostring( pre )..tostring( basecolor ), x, y*2-1, -1, x, p_offset, 0 ); end p_offset = p_offset + 1; -- these only exist in unifieddyes and need no translation if( supported[ y * 2 ]==1 ) then form = form..colormachine.print_color_image( nil, m_prefix, tostring( pre )..tostring( basecolor )..'_s50', x, y*2, -1, x, p_offset, 0 ); end -- the first row does not always hold all colors if( y >1 or supported[ y * 2 ]==1) then p_offset = p_offset + 1; end end end -- shades of grey form = form.. "label[" ..tostring( #colormachine.colors+1 )..",0.5;grey]"; for i,gname in ipairs( colormachine.grey_names ) do if( colormachine.data[ m_prefix ].grey_shades[ i ]==1 ) then form = form..colormachine.print_color_image( nil, m_prefix, gname, -1, -1, i, tostring( #colormachine.colors+1 ), tostring( i+1 ), 0 ); end end return form; end colormachine.decode_color_name = function( meta, new_color ) -- decode the color codes local liste = new_color:split( "_" ); if( #liste < 1 or #liste > 3 ) then liste = {'white'}; end -- perhaps it's one of the grey colors? for i,v in ipairs( colormachine.grey_names ) do if( v == liste[1] ) then if( meta ) then meta:set_string('selected_shade', -1 ); -- grey-shade meta:set_string('selected_grey_shade', i ); meta:set_string('selected_color', -1 ); -- we selected grey meta:set_string('selected_name', new_color ); return new_color; else return { s=-1, g=i, c=-1 }; end end end if( #liste < 1 ) then if( meta ) then return meta:get_string('selected_name'); else return nil; end end local selected_shade = 2; -- if no other shade is selected, use plain color local vgl = liste[1]..'_'; for i,v in ipairs( colormachine.prefixes ) do if( v == vgl or v== liste[1]) then selected_shade = i; table.remove( liste, 1 ); -- this one has been done end end if( #liste < 1 ) then if( meta ) then return meta:get_string('selected_name'); else return nil; end end local selected_color = -1; for i,v in ipairs( colormachine.colors ) do if( v == liste[1] ) then selected_color = i; table.remove( liste, 1 ); -- the color has been selected end end -- the color was not found! error! keep the old color if( selected_color == -1 ) then if( meta ) then return meta:get_string('selected_name'); else return nil; end end if( #liste > 0 and liste[1]=='s50') then selected_shade = selected_shade * 2; else selected_shade = selected_shade * 2 - 1; end if( meta ) then meta:set_string('selected_shade', selected_shade ); -- grey-shade meta:set_string('selected_grey_shade', -1 ); meta:set_string('selected_color', selected_color ); -- we selected grey meta:set_string('selected_name', new_color ); return new_color; else return { s=selected_shade, g=-1, c= selected_color }; end end -- returns "" if the item does not exist; -- wrapper for colormachine.translate_color_name(..) colormachine.print_color_image = function( meta, k, new_color, c, s, g, pos_x, pos_y, change_link ) local translated_node_name = colormachine.translate_color_name( meta, k, new_color, c, s, g, 1 ); local translated_color = colormachine.translate_color_name( meta, k, new_color, c, s, g, 0 ); if( not( translated_color )) then if( translated_node_name and minetest.registered_items[ translated_node_name ] ) then if( minetest.registered_items[ translated_node_name ].inventory_image ) then translated_color = minetest.registered_items[ translated_node_name ].inventory_image; elseif( minetest.registered_items[ translated_node_name ].wield_image ) then translated_color = minetest.registered_items[ translated_node_name ].wield_image; end end end if( not( translated_color )) then return ""; end -- local translated_node_name = colormachine.translate_color_name( meta, k, new_color, c, s, g, 1 ); if( not( translated_node_name )) then return ""; end -- a node or craftitem of that name does not exist if( not( minetest.registered_items[ translated_node_name ]) and not( minetest.registered_craftitems[ translated_node_name ])) then --print("NOT FOUND: "..tostring( translated_node_name ).." image_button["..tostring(pos_x)..","..tostring(pos_y)..";1,1;"..translated_color..";"..tostring(link).."; ]"); return ""; end -- switch to the color selector for that blocktype local link = new_color; if( change_link==1 ) then link = k; end if( colormachine.data[ k ].composed ) then return "item_image_button["..tostring(pos_x)..","..tostring(pos_y)..";1,1;"..translated_node_name..";"..tostring(link).."; ]"; else return "image_button["..tostring(pos_x)..","..tostring(pos_y)..";1,1;"..translated_color..";"..tostring(link).."; ]"; end end -- returns the translated name of the color if necessary (wool/normal dye is named differently than unifieddyes); -- either meta or c, s and g together need to be given -- mode==0: return texture name -- mode==1: return object name for itemstacks etc colormachine.translate_color_name = function( meta, k, new_color, c, s, g, as_obj_name ) if( meta ~= nil ) then c = tonumber(meta:get_string('selected_color')); s = tonumber(meta:get_string('selected_shade')); g = tonumber(meta:get_string('selected_grey_shade')); end -- is this special shade supported at all? if( ( g > 0 and colormachine.data[k].grey_shades[ g ] ~= 1 ) or ( g == -1 and colormachine.data[k].shades[ s ] ~= 1 )) then return nil; end local k_orig = k; -- unifieddyes_ does not supply all colors if( k == 'unifieddyes_' and ( (g==-1 and s==3 and (as_obj_name==1 or not(c==4 or c==6 or c==8 or c==12 or c==13 ))) or (g==-1 and s==1 and c==1 ) -- pink or (g==-1 and s==7 and c==5 ) -- dark brown or g==1 or g==3 or g==4 or g==5 )) then k = 'dye_'; end if( k=='homedecor_bathroom_tiles_' and as_obj_name==1 ) then if( g==1 or new_color==colormachine.grey_names[1]) then return 'homedecor:tiles_1'; elseif( g==3 or new_color==colormachine.grey_names[3]) then return 'homedecor:tiles_2'; elseif( g==4 or new_color==colormachine.grey_names[4]) then return 'homedecor:tiles_4'; elseif( g==5 or new_color==colormachine.grey_names[5]) then return 'homedecor:tiles_3'; elseif( new_color == 'dark_orange' ) then return 'homedecor:tiles_tan'; end end if( colormachine.data[k].modname=='myroofs' and as_obj_name==1 ) then if( g==5 or new_color == 'black' ) then return "myroofs:asphalt_shingle_hd_asphalt"..(colormachine.data[k].postfix or ''); elseif( new_color=='orange') then return "myroofs:asphalt_shingle_hd_terracotta"..(colormachine.data[k].postfix or ''); elseif( new_color=='dark_orange') then return "myroofs:asphalt_shingle_hd_wood"..(colormachine.data[k].postfix or ''); end end if( (k=='homedecor_book_' or k=='homedecor_bottle_' or k=='homedecor_welcome_mat_' ) and as_obj_name==1) then if( new_color == 'dark_orange' ) then new_color = 'brown'; return 'homedecor:'..colormachine.data[k].add..'brown'..(colormachine.data[k].postfix or ''); end end if( k=='homedecor_table_' and as_obj_name==1 and new_color=='dark_orange' ) then return 'homedecor:'..colormachine.data[k].add..'mahogany'..(colormachine.data[k].postfix or ''); end if( k=='homedecor_bed_' and as_obj_name==1 and g==4 ) then return 'homedecor:bed_darkgrey_regular'; end -- this does break the namescheme... if( k=='unifieddyes_' and g==2 and as_obj_name==1 ) then return 'dye:light_grey'; end -- beds and sofas are available in less colors if( g==-1 and (c==7 or c==11) and (k=='beds_bed_top_top_' or k=='lrfurn_sofa_right_front_' or k=='lrfurn_armchair_front_' or k=='lrfurn_longsofa_middle_front_' )) then return nil; end -- blox has its own naming scheme - but at least the colors supported are of a simple kind (no shades, no lower saturation) if( colormachine.data[k].modname == 'blox' ) then local color_used = ""; if( s==1 and c==1 ) then color_used = 'pink'; -- in blox, this is called "pink"; normally "light_red" elseif( g>-1 ) then color_used = colormachine.grey_names[ g ]; elseif( s ~= 3 ) then return nil; -- only normal saturation supported elseif( c==10 ) then color_used = 'purple'; -- purple and violet are not the same, but what shall we do? elseif( c==4 or c==6 or c==8 or c>10 ) then return nil; -- these colors are not supported elseif( c > 0 ) then color_used = colormachine.colors[ c ]; end if( as_obj_name == 1 ) then return 'blox:'..( color_used )..( colormachine.data[k].add ); else return 'blox_'..( color_used )..( colormachine.data[k].add )..'.png'; end end local postfix = '.png'; local prefix = k; -- we want the object name, i.e. default:brick, and not default_brick.png (all with colors inserted...): if( as_obj_name == 1 ) then postfix = ''; prefix = colormachine.data[ k ].modname..":"..colormachine.data[ k ].add; -- stained_glass needs an exception here because it uses a slightly different naming scheme if( colormachine.data[ k ].modname == 'stained_glass' and stained_glass_exception==1) then if( g>0 ) then return nil; -- no grey values for them end local h_trans = {yellow=1, lime=2, green=3, aqua=4, cyan=5, skyblue=6, blue=7, violet=8, magenta=9, redviolet=10, red=11,orange=12}; local h = h_trans[ colormachine.colors[c] ]; local b = ""; local sat = ""; if( k == 'stained_glass_' ) then prefix = "stained_glass:"..(colormachine.colors[c]).."_"; if( s==1 or s==2) then b = "8"; -- light elseif( s==3 or s==4) then b = "5"; -- normal elseif( s==5 or s==6) then b = "4"; -- medium elseif( s==7 or s==8) then b = "3"; -- dark end prefix = prefix.."_"; sat = "7"; if( s==2 or s==4 or s==6 or s==8 ) then -- saturation sat = "6"; end if( s==1 ) then sat = ""; end return "stained_glass:" .. (h) .. "_" .. (b) .. "_" .. (sat); elseif( k == 'stained_glass_faint_' ) then return "stained_glass:"..(h).."_91"; elseif( k == 'stained_glass_pastel_' ) then return "stained_glass:"..(h).."_9"; end end end -- homedecors names are slightly different.... if( k == 'homedecor_window_shutter_' ) then if( s==1 and new_color=='light_blue' ) then -- only light blue is supported return prefix..'light_blue'..postfix; elseif( new_color=='dark_green' ) then return prefix..'forest_green'..postfix; -- no more light colors, no more cyan or mangenta available; no normal green or blue elseif( s==1 or c==7 or c==11 or c==5 or c==9 ) then return nil; elseif( new_color=='dark_orange' ) then return prefix..'mahogany'..postfix; elseif( new_color=='orange' ) then return prefix..'oak'..postfix; end end if( k=='cotton_' and new_color=='grey') then new_color = 'mediumgrey'; end if( k=='framedglass_' and as_obj_name ~= 1) then postfix = 'glass.png'; end if( k=='shells_dye_' ) then if( as_obj_name == 1 ) then postfix = 'lightglass'; else postfix = 'lightglass.png'; end end if( k=='homedecor_bed_' ) then if( as_obj_name == 1 ) then --postfix = '_foot'; else postfix = '_inv.png'; end end -- those have split textures... if( colormachine.data[k].modname == 'coloredblocks') then -- we are looking for the image name if( prefix==k ) then if( new_color == 'dark_orange') then new_color = 'brown'; end -- show the top of the blocks in the individual formspec if( not(meta) ) then return 'coloredblocks_'..new_color..postfix; end -- show the side view in the main menu return string.sub(k, 1, string.len( k )-1)..'half'..postfix; -- TODO --[[ if( new_color == 'dark_orange') then new_color = 'brown'; end return 'coloredblocks_'..new_color..postfix; elseif( new_color..'_' == colormachine.data[k].add ) then prefix = 'coloredblocks:'; --]] end end if( colormachine.data[k].modname == 'plasticbox' and new_color == 'dark_green') then return prefix..'darkgreen'..postfix; end -- some mods need additional data be added after the color name if( as_obj_name == 1 and colormachine.data[k].obj_postfix ) then postfix = (colormachine.data[k].obj_postfix) ..postfix; end -- normal dyes (also used for wool) use a diffrent naming scheme if( colormachine.data[k].u == 0) then if( new_color == 'darkgrey' and k ~= 'framedglass_') then return prefix..'dark_grey'..postfix; elseif( new_color == 'dark_orange' ) then return prefix..'brown'..postfix; elseif( new_color == 'dark_green' ) then return prefix..new_color..postfix; elseif( new_color == 'light_red' ) then return prefix..'pink'..postfix; -- lime, aqua, skyblue and redviolet do not exist as standard wool/dye colors elseif( g == -1 and (c==4 or c==6 or c==8 or c==12) and k_orig ~= 'unifieddyes_') then return nil; -- all other colors of normal dye/wool exist only in normal shade elseif( g == -1 and s~= 3 and k_orig ~= 'unifieddyes_') then return nil; -- colors that are the same in both systems and need no special treatment else return prefix..new_color..postfix; end end return prefix..new_color..postfix; end -- if a block is inserted, the name of its color is very intresting (for removing color or for setting that color) -- (kind of the inverse of translate_color_name) colormachine.get_color_from_blockname = function( mod_name, block_name ) local bname = mod_name..":"..block_name; local found = {}; for k,v in pairs( colormachine.data ) do if( mod_name == v.modname ) then table.insert( found, k ); end end if( #found < 1 ) then return { error_code ="Sorry, this block is not supported by the spray booth.", found_name = "", blocktype = ""}; end -- another case of special treatment needed; at least the color is given in the tiles if( mod_name =='stained_glass' and stained_glass_exception==1) then local original_node = minetest.registered_items[ bname ]; if( original_node ~= nil ) then local tile = original_node.tiles[1]; local liste2 = string.split( tile, "%."); block_name = liste2[1]; end end -- this mod does not seperate modname and objectname well enough :-( Naming scheme:- steel_framed_obsidian_glassCOLOR if( mod_name =='framedglass' ) then block_name = string.sub( block_name, 28 ); end if( mod_name =='shells_dye' ) then block_name = string.sub( block_name, 1, string.len( block_name )-string.len( 'lightglass') ); end -- blox uses its own naming scheme if( mod_name =='blox' ) then -- the color can be found in the description local original_node = minetest.registered_items[ bname ]; if( original_node ~= nil ) then local bloxdescr = original_node.description; -- bloxparts[1] will be filled with the name of the color: local bloxparts = string.split( bloxdescr, " "); -- now extract the blocktype information if( bloxparts ~= nil and #bloxparts > 0 ) then -- we split with the color name local found_name = bloxparts[1]; local blocktype = 'blox_'..string.sub( block_name, string.len( found_name )+1 )..'_'; -- handle pink and purple if( found_name == 'pink' ) then found_name = 'light_red'; elseif( found_name == 'purple' ) then found_name = 'violet'; end return { error_code = nil, found_name = found_name, -- the name of the color blocktype = blocktype }; -- the blocktype end end -- if this point is reached, the decoding of the blox-block-name has failed return { error_code = "Error: Failed to decode color of this blox-block.", found_name = "", blocktype = "" }; end -- homedecors names are slightly different.... if( mod_name == 'homedecor' ) then -- change the blockname to the expected color if( block_name == 'shutter_forest_green' ) then block_name = 'shutter_dark_green'; elseif( block_name == 'shutter_mahogany' ) then block_name = 'shutter_dark_orange'; -- this is the default, unpainted one..which can also be considered as "orange" in the menu -- elseif( blockname == 'shutter_oak' ) then -- block_name = 'shutter_orange'; end end if( mod_name == 'plasticbox' and block_name == 'plasticbox_darkgreen' ) then block_name = 'plasticbox_dark_green'; end -- even cotton needs an exception... if( mod_name == 'cotton' and block_name=='mediumgrey' ) then block_name = 'grey'; end local blocktype = ''; -- some mods may have a postfix to their modname (which is pretty annoying) for _,k in ipairs( found ) do if( colormachine.data[k].obj_postfix ) then local l = string.len( colormachine.data[k].obj_postfix); if( string.len( block_name ) > l and string.sub( block_name, -1*l ) == colormachine.data[k].obj_postfix ) then block_name = string.sub( block_name, 1, (-1*l)-1 ); blocktype = k; end end end -- try to analyze the name of this color; this works only if the block follows the color scheme local liste = string.split( block_name, "_" ); local curr_index = #liste; -- handle some special wool- and dye color names -- dark_grey <-> darkgrey if( #liste > 1 and liste[ curr_index ]=='grey' and liste[ curr_index - 1 ] == 'dark' ) then curr_index = curr_index - 1; liste[ curr_index ] = 'darkgrey'; -- brown <=> dark_orange elseif( #liste > 0 and liste[ curr_index ]=='brown' ) then liste[ curr_index ] = 'dark'; table.insert( liste, 'orange' ); curr_index = curr_index + 1; -- pink <=> light_red elseif( #liste > 0 and liste[ curr_index ]=='pink' ) then liste[ curr_index ] = 'light'; table.insert( liste, 'red' ); curr_index = curr_index + 1; end -- find out the saturation - either "s50" or omitted local sat = 0; if( curr_index > 1 and liste[ curr_index ] == "s50" ) then sat = 1; curr_index = curr_index - 1; end -- the next value will be the color local c = 0; if( curr_index > 0 ) then for i,v in ipairs( colormachine.colors ) do if( c==0 and curr_index > 0 and v == liste[ curr_index ] ) then c = i; curr_index = curr_index - 1; end end end local g = -1; -- perhaps we are dealing with a grey value if( curr_index > 0 and c==0 ) then for i,v in ipairs(colormachine.grey_names ) do if( g==-1 and curr_index > 0 and v == liste[ curr_index ] ) then g = i; c = -1; curr_index = curr_index - 1; end end end -- determine the real shade; 3 stands for normal local s = 3; if( curr_index > 0 and g==-1 and c~=0) then if( liste[ curr_index ] == 'light' ) then s = 1; curr_index = curr_index - 1; elseif( liste[ curr_index ] == 'medium' ) then s = 5; curr_index = curr_index - 1; elseif( liste[ curr_index ] == 'dark' ) then s = 7; curr_index = curr_index - 1; end end local found_name = ""; if( g ~= -1 ) then found_name = colormachine.grey_names[ g ]; elseif( c > 0 ) then found_name = colormachine.prefixes[ math.floor((s+1)/2) ] .. colormachine.colors[ c ]; if( sat==1 ) then s = s+1; found_name = found_name.."_s50"; end end -- for blocks that do not follow the naming scheme - the color cannot be decoded if( g==-1 and c==0 ) then return { error_code ="This is a colored block: "..tostring( bname )..".", found_name = "", blocktype = ""}; end -- identify the block type/subname local add = ""; if( curr_index > 0 ) then for k,v in pairs( colormachine.data ) do -- prefix and postfix have to fit if( curr_index > 0 and add=="" and mod_name == v.modname and (liste[ curr_index ].."_") == v.add -- if a postfix exists, we did check for that before and set blocktype accordingly and( not( blocktype ) or blocktype=='' or blocktype==k)) then add = v.add; blocktype = k; curr_index = curr_index - 1; end end end if( not( blocktype ) or blocktype == '' ) then blocktype = found[1]; end if( curr_index > 0 and #liste>0 and liste[1]=='chair' and blocktype == 'homedecor_bed_' ) then return { error_code = nil, found_name = found_name, blocktype = 'forniture_kitchen_chair_sides_'}; end if( curr_index > 0 ) then local k_help = ''; for i=1, curr_index do k_help = k_help..liste[i]..'_'; end if( colormachine.data[ k_help ]) then blocktype = k_help; else print( 'colormachine: ERROR: leftover name parts for '..tostring( bname )..": "..minetest.serialize( liste )); end end return { error_code = nil, found_name = found_name, blocktype = blocktype}; end -- if the player has selected a color, show all blocks in that color colormachine.blocktype_menu = function( meta, new_color, page ) page = tonumber( page ); local per_line = 13; local anz_lines = 3; local per_page = anz_lines * per_line; local start_at_offset = per_page * page; new_color = colormachine.decode_color_name( meta, new_color ); -- keep the same size as with the color selector local form = "size["..tostring( #colormachine.colors+2 )..",10]".."label[5,0;Select a blocktype:]".. "label[0.2,1.2;name]".. "label[0.2,2.2;unpainted]".. "label[0.2,3.2;colored]".. "button[1,0.5;4,1;dye_management;Manage stored dyes]".. "button[5,0.5;4,1;main_menu;Back to main menu]"; local x = 1; local y = 2; for i,k in ipairs( colormachine.ordered ) do -- only installed mods are of intrest if( k ~= nil and colormachine.data[ k ].installed == 1 and i > start_at_offset and i <= (start_at_offset + per_page)) then -- that particular mod may not offer this color form = form.."button["..tostring(x)..","..tostring(y-0.8).. ";1,1;"..k..";"..colormachine.data[k].descr.."]".. "item_image["..tostring(x)..","..tostring(y )..";1,1;"..colormachine.data[k].block.."]"; local button = colormachine.print_color_image( meta, k, new_color, nil, nil, nil, tostring(x), tostring(y+1), 1);-- translated_color as return value for button if( button ~= "" ) then form = form..button; else form = form.."button[".. tostring(x)..","..tostring(y+1)..";1,1;"..k..";n/a]"; end x = x+1; if( x>per_line ) then x = 1; y = y+anz_lines; if( y < 2+anz_lines*3 ) then form = form.. "label[0.2,"..tostring(y-1)..".2;name]".. "label[0.2,"..tostring(y )..".2;unpainted]".. "label[0.2,"..tostring(y+1)..".2;colored]"; end end end end if( #colormachine.ordered > per_page ) then local max_page_nr = math.ceil( #colormachine.ordered/per_page ); -- add page number form = form.."field[20,20;0.1,0.1;page;;"..math.floor( start_at_offset/(3*13) ).."]".. "label[10.2,0.5;"..tostring( page+1 ).."/"..tostring( max_page_nr ).."]"; if( page and page>0 ) then form = form.. "button[9.0,0.5;0.5,0.5;first_page;"..minetest.formspec_escape("1|<").."]".. "button[9.6,0.5;0.5,0.5;prev_page;"..tostring(page)..minetest.formspec_escape("<").."]"; end if( not( page ) or page+1 < max_page_nr ) then form = form.. "button[10.8,0.5;0.5,0.5;next_page;"..minetest.formspec_escape(">")..tostring( math.min( page+2, max_page_nr )).."]".. "button[11.4,0.5;0.5,0.5;last_page;"..minetest.formspec_escape(">|")..tostring( max_page_nr ).."]"; end end return form; end -- this function tries to figure out which block type was inserted and how the color can be decoded colormachine.main_menu_formspec = function( pos, option ) local i = 0; local k = 0; local v = 0; local form = "size[14.5,9]".. "list[current_player;main;1,5;8,4;]".. -- TODO -- "label[3,0.2;Spray booth main menu]".. "button[6.5,0.25;3,1;dye_management;Manage stored dyes]".. "button[6.5,0.75;3,1;blocktype_menu;Show supported blocks]".. "label[3,0.0;1. Input - Insert material to paint:]".. "list[current_name;input;4.5,0.5;1,1;]".. "label[9.3,-0.5;Additional storage for dyes:]".. "list[current_name;extrastore;9.3,0;5,9]"; if( minetest.setting_getbool("creative_mode") ) then form = form.."label[0.5,0.25;CREATIVE MODE:]".."label[0.5,0.75;no dyes or input consumed]"; end local meta = minetest.get_meta(pos); local inv = meta:get_inventory(); -- display the name of the color the machine is set to form = form.."label[1.0,4.3;Current painting color:]".. "label[3.5,4.3;"..(meta:get_string('selected_name') or "?" ).."]".. -- display the owner name "label[7,4.3;Owner: "..(meta:get_string('owner') or "?" ).."]"; if( inv:is_empty( "input" )) then form = form.."label[2.2,3.0;Insert block to be analyzed.]"; return form; end local stack = inv:get_stack( "input", 1); local bname = stack:get_name(); -- lets find out if this block is one of the unpainted basic blocks calling for paint local found = {}; for k,v in pairs( colormachine.data ) do if( bname == v.block and colormachine.data[ k ].installed==1) then table.insert( found, k ); end end -- make sure all output fields are empty for i = 1, inv:get_size( "output" ) do inv:set_stack( "output", i, "" ); end local anz_blocks = stack:get_count(); -- a block that can be colored if( #found > 0 ) then local out_offset = 3.5-math.floor( #found / 2 ); if( out_offset < 0 ) then out_offset = 0; end local anz_found = 0; local p_values = {}; -- how many blocks can be colored with one pigment? for i,v in ipairs( found ) do if( i <= inv:get_size( "output" )) then -- offer the description-link form = form.."button["..tostring(out_offset+i)..","..tostring(1.45)..";1,1;"..v..";"..colormachine.data[v].descr.."]"; -- when clicking here, the color selection menu for that blocktype is presented local button = colormachine.print_color_image( meta, v, meta:get_string('selected_name'), nil, nil, nil, tostring(out_offset+i), tostring(2.0),1 ); if( button ~= "" ) then local block_name = colormachine.translate_color_name( meta, v, meta:get_string('selected_name'), nil, nil, nil, 1 ); -- one pigment is enough for factor blocks: local factor = colormachine.data[ v ].p; if( not( factor )) then factor = 1.0; end -- how many of these blocks can we actually paint? local can_be_painted = 0; if( not( minetest.setting_getbool("creative_mode") )) then can_be_painted = colormachine.calc_dyes_needed( meta, inv, math.ceil( anz_blocks / factor ), 0 ); else can_be_painted = 99; -- an entire stack can be painted in creative mode end inv:set_stack( "output", i, block_name.." "..tostring( math.min( can_be_painted * factor, anz_blocks ))); p_values[ i ] = factor; form = form..button; else inv:set_stack( "output", i, "" ); -- form = form.."button[" ..tostring(2+i)..","..tostring(2.5)..";1,1;"..v..";"..colormachine.data[v].descr.."]"; form = form.."button[".. tostring(out_offset+i)..","..tostring(2.0)..";1,1;"..v..";n/a]"; end anz_found = anz_found + 1; end end -- so that we can determine the factor when taking blocks from the output slots meta:set_string('p_values', minetest.serialize( p_values )); -- this color was not supported if( anz_found == 0 ) then form = form.."label[2.2,3.0;Block is not available in that color.]"; return form; end form = form.."label[3.0,1.2;2. Select color for any style:]".. "label[3.0,2.9;3. Take output (determines style):]".. "list[current_name;output;"..tostring(out_offset+1)..",3.5;"..tostring( anz_found )..",1;]"; return form; end -- end of handling of blocks that can be colored -- get the modname local parts = string.split(bname,":"); if( #parts < 2 ) then form = form.."label[2.2,3.0;ERROR! Failed to analyze the name of this node: "..tostring(bname).."]"; return form; end -- it may be a dye source for i,v in ipairs( colormachine.basic_dye_sources ) do -- we have found the right color! if( bname == v ) then form = form.."label[2.2,3.0;This is a dye source.]".. "button[6,3.0;3,1;turn_into_dye;Add to internal dye storage]"; return form; end end -- it is possible that we are dealing with an already painted block - in that case we have to dertermie the color local found_color_data = colormachine.get_color_from_blockname( parts[1], parts[2] ); if( found_color_data.error_code ~= nil ) then form = form.."label[2.2,3.0;"..found_color_data.error_code..".]"; return form; end -- the previous analyse was necessary in order to determine which block we ought to use if( option == 'remove_paint' ) then -- actually remove the paint from the inv:set_stack( "input", 1, colormachine.data[ found_color_data.blocktype ].block.." "..tostring( anz_blocks )); -- update display (we changed the input!) return colormachine.main_menu_formspec(pos, "analyze"); end if( option == 'adapt_color' ) then -- actually change the color colormachine.decode_color_name( meta, found_color_data.found_name ); -- default color changed - update the menu return colormachine.main_menu_formspec(pos, "analyze"); end -- print color name; select as input color / remove paint form = form.."label[2.2,3.0;This is: "..tostring( found_color_data.found_name )..".]".. "button[6,3.5;3,1;remove_paint;Remove paint]"; if( found_color_data.found_name ~= meta:get_string( 'selected_name' )) then form = form.."button[6,2.6;3,1;adapt_color;Set as new color]"; else form = form.."label[5.5,2.0;This is the selected color.]"; end return form; end -- returns a list of all blocks that can be created by applying dye_node_name to the basic node of old_node_name colormachine.get_node_name_painted = function( old_node_name, dye_node_name ) local possible_blocks = {}; local unpainted_block = ""; local old_dye = ""; for k,v in pairs( colormachine.data ) do if( old_node_name == v.block and colormachine.data[ k ].installed==1) then table.insert( possible_blocks, k ); unpainted_block = old_node_name; end end if( unpainted_block == "" ) then local parts = string.split(old_node_name,":"); if( #parts < 2 ) then return; end found_color_data_block = colormachine.get_color_from_blockname( parts[1], parts[2] ); if( found_color_data_block.error_code ~= nil ) then return; end unpainted_block = colormachine.data[ found_color_data_block.blocktype ].block; old_dye = found_color_data_block.found_name; -- figure out how the dye this block was painted with was called local cdata = colormachine.decode_color_name( nil, old_dye ); if( cdata ) then old_dye = colormachine.translate_color_name( nil, 'unifieddyes_', old_dye, cdata.c, cdata.s, cdata.g, 1 ); if( not( old_dye ) or old_dye == '' ) then old_dye = colormachine.translate_color_name( nil, 'dye_', old_dye, cdata.c, cdata.s, cdata.g, 1 ); end else old_dye = ''; end end if( unpainted_block ~= "" and #possible_blocks < 1 ) then for k,v in pairs( colormachine.data ) do if( unpainted_block == v.block and colormachine.data[ k ].installed==1) then table.insert( possible_blocks, k ); end end end -- remove paint if( not( dye_node_name ) or dye_node_name == "") then return {possible={unpainted_block},old_dye = old_dye}; end -- decode dye name parts = string.split(dye_node_name,":"); if( #parts < 2 ) then return; end local found_color_data_color = colormachine.get_color_from_blockname( parts[1], parts[2] ); if( found_color_data_color.error_code ~= nil ) then return; end local dye_name = found_color_data_color.found_name; local cdata = colormachine.decode_color_name( nil, dye_name ); if( not( cdata )) then return; end -- find out for which block types/patterns this unpainted block is the basic one local found = {}; for _,k in ipairs( possible_blocks ) do local new_block_name = colormachine.translate_color_name( nil, k, dye_name, cdata.c, cdata.s, cdata.g, 1 ); table.insert( found, new_block_name ); end if( #found < 1 ) then return; end return { possible=found, old_dye = old_dye }; end colormachine.check_owner = function( pos, player ) -- only the owner can put something in local meta = minetest.get_meta(pos); if( meta:get_string('owner') ~= player:get_player_name() ) then minetest.chat_send_player( player:get_player_name(), "This spray booth belongs to "..tostring( meta:get_string("owner")).. ". If you want to use one, build your own!"); return 0; end return 1; end colormachine.allow_inventory_access = function(pos, listname, index, stack, player, mode) -- only specific slots accept input or output if( (mode=="put" and listname ~= "input" and listname ~= "refill" and listname ~= "dyes" ) or (mode=="take" and listname ~= "input" and listname ~= "refill" and listname ~= "dyes" and listname ~= "output" and listname ~= "paintless" )) then if( listname == "extrastore" ) then local parts = string.split(stack:get_name(),":"); if( #parts > 1 and (parts[1]=='unifieddyes' or parts[1]=='dye')) then return stack:get_count(); end end return 0; end local stack_name = stack:get_name(); -- the dyes are a bit special - they accept only powder of the correct name if( listname == "dyes" and stack_name ~= ("dye:".. colormachine.colors_and_greys[ index ]) and stack_name ~= ("unifieddyes:"..colormachine.colors_and_greys[ index ]) and (stack_name ~= "dye:light_grey" or colormachine.colors_and_greys[ index ]~="lightgrey" ) and (stack_name ~= "dye:dark_grey" or colormachine.colors_and_greys[ index ]~="darkgrey" ) ) then minetest.chat_send_player( player:get_player_name(), 'You can only store dye powders of the correct color here.'); return 0; end if( not( colormachine.check_owner( pos, player ))) then return 0; end -- let's check if that type of input is allowed here if( listname == "refill" ) then local str = stack:get_name(); for i,v in ipairs( colormachine.basic_dye_sources ) do if( str == v and v ~= "") then return stack:get_count(); end end minetest.chat_send_player( player:get_player_name(), 'Please insert dye sources as listed below here (usually plants)!'); return 0; end return stack:get_count(); end colormachine.on_metadata_inventory_put = function( pos, listname, index, stack, player ) local meta = minetest.get_meta(pos); local inv = meta:get_inventory(); -- nothing to do if onnly a dye was inserted if( listname == "dyes" ) then return; end -- an unprocessed color pigment was inserted if( listname == "refill" ) then local str = stack:get_name(); for i,v in ipairs( colormachine.basic_dye_sources ) do -- we have found the right color! if( str == v ) then local count = stack:get_count(); -- how much free space do we have in the destination stack? local dye_stack = inv:get_stack( "dyes", i); local free = math.floor(dye_stack:get_free_space()/4); if( free < 1 ) then minetest.chat_send_player( player:get_player_name(), 'Sorry, the storage for that dye is already full.'); return 0; end if( count < free ) then free = count; end -- consume the inserted material - no more than the input slot can handle inv:remove_item(listname, stack:get_name().." "..tostring( free )); color_name = colormachine.colors_and_greys[ i ]; -- add four times that much to the storage if( i==4 or i==6 or i==8 or i==12 or i==14 ) then if( colormachine.data[ 'unifieddyes_' ].installed == 0 ) then minetest.chat_send_player( player:get_player_name(), 'Sorry, this color requires unifieddyes (which is not installed).'); return 0; end inv:set_stack( "dyes", i, ("unifieddyes:"..color_name).." "..tostring( free*4 + dye_stack:get_count()) ); else inv:set_stack( "dyes", i, ("dye:" ..color_name).." "..tostring( free*4 + dye_stack:get_count()) ); end end end minetest.chat_send_player( player:get_player_name(), 'Please insert dye sources as listed below here (usually plants)!'); return 0; end if( listname == "input" ) then -- update the main menu accordingly meta:set_string( 'formspec', colormachine.main_menu_formspec( pos, "analyze" )); return; end end colormachine.on_metadata_inventory_take = function( pos, listname, index, stack, player ) local meta = minetest.get_meta(pos); local inv = meta:get_inventory(); if( listname == "output" ) then -- in creative mode, no pigments are consumed if( minetest.setting_getbool("creative_mode") ) then -- update the main menu meta:set_string( 'formspec', colormachine.main_menu_formspec( pos, "analyze" )); return; end -- consume color for painted blocks local str = meta:get_string( 'p_values' ); local p = 1; -- color more than one block with one pigment if( str and str ~= "" ) then local p_values = minetest.deserialize( str ); if( index and p_values[ index ] ) then p = p_values[ index ]; end end local amount_needed = math.ceil( stack:get_count() / p ); local amount_done = colormachine.calc_dyes_needed( meta, inv, amount_needed, 1 ); --print( ' NEEDED: '..tostring( amount_needed )..' DONE: '..tostring( amount_done )); -- TODO if( amount_done > amount_needed ) then -- TODO: leftover color - how to handle? end -- calculate how much was taken local anz_taken = stack:get_count(); local anz_present = inv:get_stack("input",1):get_count(); anz_present = anz_present - anz_taken; if( anz_present <= 0 ) then inv:set_stack( "input", 1, "" ); -- everything used up else inv:set_stack( "input", 1, inv:get_stack("input",1):get_name().." "..tostring( anz_present )); end -- the main menu needs to be updated as well meta:set_string( 'formspec', colormachine.main_menu_formspec( pos, "analyze" )); return; end if( listname == "input" ) then -- update the main menu accordingly meta:set_string( 'formspec', colormachine.main_menu_formspec( pos, "analyze" )); return; end end -- calculate which dyes are needed colormachine.calc_dyes_needed = function( meta, inv, amount_needed, do_consume ) local form = ""; -- display the name of the currently selected color form = form.."label[8,0.2;"..( meta:get_string( "selected_name" ) or "?" ).."]"; local s = tonumber(meta:get_string('selected_shade' )); local g = tonumber(meta:get_string('selected_grey_shade' )); local c = tonumber(meta:get_string('selected_color' )); local needed = {}; -- we are dealing with a grey value if( g > -1 ) then needed[ colormachine.grey_names[ g ]] = 1; -- we are dealing with a normal color else -- one pigment of the selected color (to get started) needed[ colormachine.colors[ c ]] = 1; -- handle saturation if( s==1 ) then needed[ "white" ]=1; -- light -- elseif( s==3 ) then -- normal color - no changes needed elseif( s==4 ) then needed[ "white" ]=2; needed[ "black" ] =1; -- normal, low saturation elseif( s==5 ) then needed[ "black" ] =1; -- medium dark elseif( s==6 ) then needed[ "white" ]=1; needed[ "black" ] =1; -- medium dark, low saturation elseif( s==7 ) then needed[ "black" ] =2; -- dark elseif( s==8 ) then needed[ "white" ]=1; needed[ "black" ] =2; -- dark, low saturation end end local anz_pigments = 0; for i,v in pairs( needed ) do anz_pigments = anz_pigments + v; end -- n: portions of *mixtures* needed local n = 1; -- if the colors are to be consumed, we need to calculate how many we actually need -- (one mixutre consists of anz_pigments pigments each) if( amount_needed > 0) then n = math.ceil( amount_needed / anz_pigments ); local min_found = 10000; -- high number that cannot be reached -- now we need to check how many pigments of each color we have for i,v in ipairs( colormachine.colors_and_greys ) do if( needed[ v ] and needed[ v ]> 0 ) then -- find out how many blocks of this type we can actually color local stack = inv:get_stack( "dyes", i ); local found = math.floor( stack:get_count() / needed[ v ]); if( found < min_found ) then min_found = found; -- save the new minimum end end end -- we do not have enough pigments if( min_found < n ) then n = min_found; end end local need_white = math.ceil( amount_needed / anz_pigments ); -- the machine does have the required colors stored if( n > 0 ) then local stack_white= inv:get_stack( "dyes", 13 ); local anz_white = stack_white:get_count(); n = math.min( anz_white, need_white ); end -- return how many *could* be colored if( amount_needed > 0 and do_consume ~= 1 ) then return n*anz_pigments; end needed = {}; needed[ "white" ] = n; for i,v in ipairs( colormachine.colors_and_greys ) do if( needed[ v ] and needed[ v ]> 0 ) then -- show how many pigments of this color are needed for the selected mixture -- normal color if( i <= #colormachine.colors ) then form = form.."label["..tostring(i+0.2)..",2.2;" ..needed[ v ].."x]".. "label["..tostring(i+0.2)..",0.6;" ..needed[ v ].."x]"; -- grey value else form = form.."label[11.3,"..tostring(i-#colormachine.colors+4.2)..";"..needed[ v ].."x]".. "label[13.3,"..tostring(i-#colormachine.colors+4.2)..";"..needed[ v ].."x]"; end -- actually consume the color pigment if( amount_needed > 0 and n > 0 ) then local stack = inv:get_stack( "dyes", i ); local found = stack:get_count(); --print( ' CONSUMED '..math.floor( n * needed[ v ] )..' of '..tostring( stack:get_name())); if( found > math.floor( n * needed[ v ] )) then inv:set_stack( "dyes", i, stack:get_name()..' '..tostring( math.max( 1, found - math.floor( n * needed[ v ] )))); else inv:set_stack( "dyes", i, "" ); end end end end -- in case pigments where consumed, return how many blocks where colored successfully if( amount_needed > 0 and n > 0 ) then --print('Successfully colored: '..tostring( n*anz_pigments )); return n*anz_pigments; end -- else return the formspec addition with the information how many of which pigment is needed return form; end -- this adds the name of the current color and the amount of needed dyes to the formspec colormachine.get_individual_dye_management_formspec = function( meta, inv ) local form = colormachine.dye_management_formspec; -- just add information how many pigments of each color are needed form = form .. colormachine.calc_dyes_needed( meta, inv, 0, 0 ) return form; end -- mix two colors colormachine.mix_colors = function( inv, i, sender ) local farbe = colormachine.colors_and_greys[ i ]; local mix = colormachine.dye_mixes[ farbe ]; -- in case the color cannot be mixed if( not( mix ) or #mix < 2 ) then return; end local stack1 = inv:get_stack( "dyes", mix[1] ); local stack2 = inv:get_stack( "dyes", mix[2] ); local stack3 = inv:get_stack( "dyes", i ); if( stack3:get_free_space() > 1 -- we need space for two and stack1:get_count() > 0 and stack2:get_count() > 0 ) then inv:set_stack( "dyes", mix[1], stack1:get_name()..' '..( stack1:get_count()-1)); inv:set_stack( "dyes", mix[2], stack2:get_name()..' '..( stack2:get_count()-1)); -- handle light/dark grey if( farbe=='lightgrey' ) then farbe = 'light_grey'; elseif( farbe=='darkgrey' ) then farbe = 'dark_grey'; end -- dye or unifieddyes? local name = 'dye:'..farbe; if( not( minetest.registered_craftitems[ name ])) then name = 'unifieddyes:'..farbe; end -- print errormessage or add the mixed dye pigment if( not( minetest.registered_craftitems[ name ])) then minetest.chat_send_player( sender:get_player_name(), '[colormachine] ERROR: color '..tostring( farbe )..' could not be mixed (craftitem '..tostring(name)..' not found)'); else inv:set_stack( "dyes", i, name..' '..( stack3:get_count() + 2 )); -- two pigments mixed -> we get two pigments result end elseif( stack3:get_free_space() > 1 ) then minetest.chat_send_player( sender:get_player_name(), 'Need '..colormachine.colors_and_greys[ mix[1] ]..' and '.. colormachine.colors_and_greys[ mix[2] ]..' in order to mix '..farbe..'.'); end end -- this generates the formspec for all supported mods and the general colormachine.dye_management_formspec colormachine.init = function() local liste = {}; -- create formspecs for all machines for k,v in pairs( colormachine.data ) do if( minetest.get_modpath( colormachine.data[ k ].modname ) ~= nil ) then -- generate the formspec for that machine colormachine.data[ k ].formspec = colormachine.generate_form( k ); -- remember that the mod is installed colormachine.data[ k ].installed = 1; -- this is helpful for getting an ordered list later -- liste[ colormachine.data[ k ].nr ] = k; table.insert( liste, k ); else -- the mod is not installed colormachine.data[ k ].installed = 0; end end table.sort( liste, function(a,b) return colormachine.data[a].nr < colormachine.data[b].nr end); colormachine.ordered = liste; -- if no flowers are present, take dye sources from default (so we only have to depend on dyes) if( minetest.get_modpath( "flowers") == nil ) then for i,v in ipairs( colormachine.alternate_basic_dye_sources ) do colormachine.basic_dye_sources[ i ] = colormachine.alternate_basic_dye_sources[ i ]; end end local form = "size[14,10]".. "list[current_player;main;1,5;8,4;]".. "label[1,0.2;"..minetest.formspec_escape('Insert dye sources here -->').."]".. "list[current_name;refill;4,0;1,1;]".. "label[6,0.2;Selected color:]".. "label[0.1,1;sources:]".. "label[0.1,2;dyes:]".. "label[0.1,3;storage:]".. "button[1,4;4,1;main_menu;Back to main menu]".. "button[5,4;4,1;blocktype_menu;Show supported blocks]".. "list[current_name;dyes;1,3;"..tostring(#colormachine.colors)..",1;]".. -- normal colors -- remaining fields of the dyes inventory: grey colors, arranged vertically -- (not enough space for the "dyes" label) "label[0.1,0.6;need:]".. "label[9.3,4.5;need:]".. "label[10,4.5;sources:]".. "label[12,4.5;storage:]".. "list[current_name;dyes;12,5;1,"..tostring(#colormachine.grey_names)..";"..tostring(#colormachine.colors).."]"; local needed = {}; -- align colors horizontal for i,k in ipairs( colormachine.colors ) do local prefix = 'dye:'; if( i==4 or i==6 or i==8 or i==12 or i==14 ) then if( colormachine.data[ 'unifieddyes_' ].installed == 1 ) then prefix = 'unifieddyes:'; else prefix = ""; end end if( prefix ~= "" ) then local source = colormachine.basic_dye_sources[ i ]; if( source ~= "" ) then form = form.."item_image["..tostring(i)..",1;1,1;"..source.."]"; -- even those colors may be additionally mixed if( #colormachine.dye_mixes[ colormachine.colors_and_greys[ i ] ] == 2 ) then form = form.. "button["..tostring(i-0.1)..",1.9;0.8,0.2;mix_"..colormachine.colors_and_greys[ i ]..";mix]"; end -- a color that can be mixed elseif( #colormachine.dye_mixes[ colormachine.colors_and_greys[ i ] ] == 2 ) then local mixes = colormachine.dye_mixes[ colormachine.colors_and_greys[ i ] ]; local source1 = 'dye:'..colormachine.colors_and_greys[ mixes[1] ]; local source2 = 'dye:'..colormachine.colors_and_greys[ mixes[2] ]; form = form.."item_image["..tostring(i )..",1.0;1,1;"..source1.."]".. "item_image["..tostring(i+0.3)..",1.3;1,1;"..source2.."]".. "button["..tostring(i-0.1)..",1.9;0.8,0.2;mix_"..colormachine.colors_and_greys[ i ]..";mix]"; end form = form.. "item_image["..tostring(i)..",2;1,1;"..tostring( prefix..colormachine.colors[ i ] ).."]".. "label["..tostring(i)..",3.6;" ..tostring( colormachine.colors_and_greys[ i ] ).."]"; else form = form.."label["..tostring(i+0.2)..",3;n/a]"; end end -- align grey-values vertical for i,k in ipairs( colormachine.grey_names ) do if( i ~= 2 or colormachine.data[ 'unifieddyes_' ].installed == 1 ) then local source = colormachine.basic_dye_sources[ #colormachine.colors + i ]; if( source and source ~= "" ) then form = form.."item_image[10,"..tostring(i+4)..";1,1;"..source.."]"; elseif( #colormachine.dye_mixes[ colormachine.colors_and_greys[ #colormachine.colors + i ] ] == 2 ) then local mixes = colormachine.dye_mixes[ colormachine.colors_and_greys[ #colormachine.colors + i ] ]; local source1 = 'dye:'..colormachine.colors_and_greys[ mixes[1] ]; local source2 = 'dye:'..colormachine.colors_and_greys[ mixes[2] ]; form = form.."item_image[10.0,"..tostring(i+4.0)..";1,1;"..source1.."]".. "item_image[10.3,"..tostring(i+4.3)..";1,1;"..source2.."]".. "button[9.8," ..tostring(i+4.9)..";0.8,0.2;mix_"..colormachine.colors_and_greys[ #colormachine.colors + i ]..";mix]"; end local dye_name = 'dye:'..k; -- lightgrey exists only in unifieddyes if( i== 2 ) then if( colormachine.data[ 'unifieddyes_' ].installed == 1 ) then dye_name = 'unifieddyes:lightgrey_paint'; --'unifieddyes:'..k; else dye_name = ''; end -- darkgrey is called slightly diffrent elseif( i==4 ) then dye_name = 'dye:dark_grey'; end if( dye_name ~= "" ) then form = form.. "item_image[11,"..tostring(i+4)..";1,1;"..tostring( dye_name ).."]".. "label[ 12.9,"..tostring(i+4)..";" ..tostring( colormachine.colors_and_greys[ #colormachine.colors + i ] ).."]"; end else form = form.."label[12.2,"..tostring(i+4)..";n/a]"; end end colormachine.dye_management_formspec = form; end -- delay initialization so that modules are hopefully loaded minetest.after( 0, colormachine.init ); -- flowers: 6 basic colors + black + white -- unifieddyes: dye pulver -- coloredwood: wood, fence - skip sticks! -- unifiedbricks: clay blocks, brick blocks (skip individual clay lumps and bricks!) -- multicolor: 3 shades, usual amount of colors -- cotton: (by jordach) probably the same as coloredwood -- -- stained_glass: 9 shades/intensities minetest.register_node("colormachine:colormachine", { description = "spray booth", tiles = { "colormachine_top.png", "colormachine_bottom.png", "colormachine_side.png", "colormachine_side.png", "colormachine_side.png", "colormachine_front.png", }, paramtype2 = "facedir", groups = {cracky=2}, legacy_facedir_simple = true, on_construct = function(pos) local meta = minetest.get_meta(pos); meta:set_string('selected_shade', 3 ); -- grey-shade meta:set_string('selected_grey_shade', 1 ); meta:set_string('selected_color', -1 ); -- we selected grey meta:set_string('selected_name', 'white' ); meta:set_string('owner', '' ); -- protect input from getting stolen local inv = meta:get_inventory(); inv:set_size("input", 1); -- input slot for blocks that are to be painted inv:set_size("refill", 1); -- input slot for plants and other sources of dye pigments inv:set_size("output", 14); -- output slot for painted blocks - up to 8 alternate coloring schems supported (blox has 8 for stone!) inv:set_size("paintless", 1); -- output slot for blocks with paint scratched off inv:set_size("dyes", 18); -- internal storage for the dye powders inv:set_size("extrastore",5*9); -- additional storage for dyes --meta:set_string( 'formspec', colormachine.blocktype_menu( meta, 'white' )); meta:set_string( 'formspec', colormachine.main_menu_formspec(pos, "analyze") ); end, after_place_node = function(pos, placer) local meta = minetest.get_meta(pos); meta:set_string( "owner", ( placer:get_player_name() or "" )); meta:set_string( "infotext", "Spray booth (owned by "..( meta:get_string( "owner" ) or "" )..")"); end, on_receive_fields = function(pos, formname, fields, sender) if( not( colormachine.check_owner( pos, sender ))) then return 0; end -- remember the page we where at if( not( fields.page )) then fields.page = 0; end local meta = minetest.env:get_meta(pos); for k,v in pairs( fields ) do if( k == 'main_menu' ) then meta:set_string( 'formspec', colormachine.main_menu_formspec(pos, "analyze") ); return; elseif( k == 'remove_paint' ) then meta:set_string( 'formspec', colormachine.main_menu_formspec(pos, "remove_paint") ); return; elseif( k == 'adapt_color' ) then meta:set_string( 'formspec', colormachine.main_menu_formspec(pos, "adapt_color") ); return; elseif( k == 'turn_into_dye' ) then local inv = meta:get_inventory(); local stack = inv:get_stack( 'input', 1 ); -- move into refill slot inv:set_stack( 'refill', 1, stack ); -- empty input slot inv:set_stack( 'input', 1, '' ); -- process the dye colormachine.on_metadata_inventory_put( pos, 'refill', 1, stack, sender ) -- call dye management forpsec to show result meta:set_string( 'formspec', colormachine.get_individual_dye_management_formspec( meta, inv )); return; elseif( k == 'dye_management' ) then local inv = meta:get_inventory(); meta:set_string( 'formspec', colormachine.get_individual_dye_management_formspec( meta, inv )); return; elseif( colormachine.data[ k ] ) then -- remember the page we where at meta:set_string( 'formspec', colormachine.data[ k ].formspec.. "field[20,20;0.1,0.1;page;;"..tostring(fields.page).."]" ); return; elseif( k=='key_escape') then -- nothing to do else local inv = meta:get_inventory(); -- perhaps we ought to mix colors for i,f in ipairs( colormachine.colors_and_greys ) do if( k==("mix_"..f )) then colormachine.mix_colors( inv, i, sender ); local inv = meta:get_inventory(); meta:set_string( 'formspec', colormachine.get_individual_dye_management_formspec( meta, inv )); return; -- formspec remains the dye-management one end end -- if no input is present, show the block selection menu if( k=="blocktype_menu" or inv:is_empty( "input" ) or k=='first_page' or k=='prev_page' or k=='next_page' or k=='last_page') then if( not( fields.page ) or k=='first_page') then fields.page = 0; elseif( k=='prev_page') then fields.page = math.max(0,fields.page-1); elseif( k=='next_page') then fields.page = math.min(fields.page+1, math.ceil(#colormachine.ordered/(3*13)-1)); elseif( k=='last_page') then fields.page = math.ceil(#colormachine.ordered/(3*13)-1); end meta:set_string( 'formspec', colormachine.blocktype_menu( meta, k, fields.page )); else -- else set the selected color and go back to the main menu colormachine.decode_color_name( meta, k ); meta:set_string( 'formspec', colormachine.main_menu_formspec(pos, "analyze").. "field[20,20;0.1,0.1;page;;"..tostring(fields.page).."]" ); end end end end, -- there is no point in moving inventory around allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) return 0; end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) return colormachine.allow_inventory_access(pos, listname, index, stack, player, "put" ); end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) return colormachine.allow_inventory_access(pos, listname, index, stack, player, "take" ); end, on_metadata_inventory_put = function(pos, listname, index, stack, player) return colormachine.on_metadata_inventory_put( pos, listname, index, stack, player ); end, on_metadata_inventory_take = function(pos, listname, index, stack, player) return colormachine.on_metadata_inventory_take( pos, listname, index, stack, player ); end, can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() if( not( colormachine.check_owner( pos, player ))) then return 0; end if( not( inv:is_empty("input")) or not( inv:is_empty("refill"))) then minetest.chat_send_player( player:get_player_name(), "Please remove the material in the input- and/or refill slot first!"); meta:set_string( 'formspec', colormachine.blocktype_menu( meta, meta:get_string('selected_name'), 0)); return false; end if( not( inv:is_empty("dyes"))) then minetest.chat_send_player( player:get_player_name(), "Please remove the stored dyes first!"); meta:set_string( 'formspec', colormachine.blocktype_menu( meta, meta:get_string('selected_name'), 0 )); return false; end return true end }) minetest.register_craft({ output = 'colormachine:colormachine', recipe = { { 'default:gold_ingot', 'default:glass', 'default:gold_ingot', }, { 'default:mese', 'default:glass', 'default:mese' }, { 'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot' } } }) dofile( minetest.get_modpath('colormachine')..'/paint_roller.lua');
unlicense
jdsfhsdbf65/test
plugins/anti_spam.lua
191
5291
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Save stats on Redis if msg.to.type == 'channel' then -- User is on channel local hash = 'channel:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end if msg.to.type == 'user' then -- User is on chat local hash = 'PM:'..msg.from.id redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is on or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id local chat = msg.to.id local whitelist = "whitelist" local is_whitelisted = redis:sismember(whitelist, user) -- Ignore mods,owner and admins if is_momod(msg) then return msg end if is_whitelisted == true then return msg end local receiver = get_receiver(msg) if msg.to.type == 'user' then local max_msg = 7 * 1 print(msgs) if msgs >= max_msg then print("Pass2") send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.") savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.") block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end end if kicktable[user] == true then return end delete_msg(msg.id, ok_cb, false) kick_user(user, chat) local username = msg.from.username local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", "") if msg.to.type == 'chat' or msg.to.type == 'channel' then if username then savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked") else savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nStatus: User kicked") end end -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) if msg.from.username ~= nil then username = msg.from.username else username = "---" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") local GBan_log = 'GBan_log' local GBan_log = data[tostring(GBan_log)] for k,v in pairs(GBan_log) do log_SuperGroup = v gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)" --send it to log group/channel send_large_msg(log_SuperGroup, gban_text) end end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
agpl-3.0
tst2005googlecode/fbclient
lua/fbclient/sql_formatting.lua
2
4751
module(...,require 'fbclient.module') local sql = require 'fbclient.sql' --[==[ --source: LangRef.pdf CREATE TABLE table [EXTERNAL [FILE] ’filespec’] (<col_def> [, <col_def> | <tconstraint> …]); <col_def> = col {<datatype> | COMPUTED [BY] (<expr>) | domain} [DEFAULT {literal | NULL | USER}] [NOT NULL] [<col_constraint>] [COLLATE collation] <datatype> = {SMALLINT | INTEGER | FLOAT | DOUBLE PRECISION}[<array_dim>] | (DATE | TIME | TIMESTAMP}[<array_dim>] | {DECIMAL | NUMERIC} [(precision [, scale])] [<array_dim>] | {CHAR | CHARACTER | CHARACTER VARYING | VARCHAR} [(int)] [<array_dim>] [CHARACTER SET charname] | {NCHAR | NATIONAL CHARACTER | NATIONAL CHAR} [VARYING] [(int)] [<array_dim>] | BLOB [SUB_TYPE {int | subtype_name}] [SEGMENT SIZE int] [CHARACTER SET charname] | BLOB [(seglen [, subtype])]<array_dim> = [[x:]y [, [x:]y …]] <expr> = A valid SQL expression that results in a single value. <col_constraint> = [CONSTRAINT constraint] { UNIQUE | PRIMARY KEY | REFERENCES other_table [(other_col [, other_col …])] [ON DELETE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] [ON UPDATE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] | CHECK (<search_condition>)} <tconstraint> = [CONSTRAINT constraint] {{PRIMARY KEY | UNIQUE} (col [, col …]) | FOREIGN KEY (col [, col …]) REFERENCES other_table [ON DELETE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] [ON UPDATE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] | CHECK (<search_condition>)} <search_condition> = <val> <operator> {<val> | (<select_one>)} | <val> [NOT] BETWEEN <val> AND <val> | <val> [NOT] LIKE <val> [ESCAPE <val>] | <val> [NOT] IN (<val> [, <val> …] | <select_list>) | <val> IS [NOT] NULL | <val> {>= | <=} | <val> [NOT] {= | < | >} | {ALL | SOME | ANY} (<select_list>) | EXISTS (<select_expr>) | SINGULAR (<select_expr>) | <val> [NOT] CONTAINING <val> | <val> [NOT] STARTING [WITH] <val> | (<search_condition>) | NOT <search_condition> | <search_condition> OR <search_condition> | <search_condition> AND <search_condition> <val> = { col [<array_dim>] | :variable | <constant> | <expr> | <function> | udf ([<val> [, <val> …]]) | NULL | USER | RDB$DB_KEY | ? } [COLLATE collation] <constant> = num | 'string' | charsetname 'string' <function> = COUNT (* | [ALL] <val> | DISTINCT <val>) | SUM ([ALL] <val> | DISTINCT <val>) | AVG ([ALL] <val> | DISTINCT <val>) | MAX ([ALL] <val> | DISTINCT <val>) | MIN ([ALL] <val> | DISTINCT <val>) | CAST (<val> AS <datatype>) | UPPER (<val>) | GEN_ID (generator, <val>) <operator> = {= | < | > | <= | >= | !< | !> | <> | !=} <select_one> = SELECT on a single column; returns exactly one value. <select_list> = SELECT on a single column; returns zero or more values. <select_expr> = SELECT on a list of values; returns zero or more values. ]==] function create_table(tab) --[[ <col_def> = col {<datatype> | COMPUTED [BY] (<expr>) | domain} [DEFAULT {literal | NULL | USER}] [NOT NULL] [<col_constraint>] [COLLATE collation] ]] local function col_def(name, field) local function col_type() --{<datatype> | COMPUTED [BY] (<expr>) | domain} return K(field.type) or C(K'COMPUTED BY (', E(field.computed_by_expr), ')') or (field.domain and or computed_by() or field.domain end --[[ <col_constraint> = [CONSTRAINT constraint] { UNIQUE | PRIMARY KEY | REFERENCES other_table [(other_col [, other_col …])] [ON DELETE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] [ON UPDATE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] | CHECK (<search_condition>)} ]] local function constraint() return -- end return C(' ', N(name), col_type(), CO(' ', C(' ', K'DEFAULT', E(field.default)), --TODO: field.default -> K'USER' C(' ', field.not_null, K'NOT NULL') constraint(), C(' ', K'COLLATE', N(field.collate)) ) ) end return sql.run(function() return C(' ', K'CREATE TABLE', N(tab.name), '(\n\t', I(col_def, tab.fields, ',\n\t'), '\n)') end) end function create_table_ast() local constraint = CO( K'CONSTRAINT'..N'constraint', --[[ <col_constraint> = [CONSTRAINT constraint] { UNIQUE | PRIMARY KEY | REFERENCES other_table [(other_col [, other_col …])] [ON DELETE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] [ON UPDATE {NO ACTION|CASCADE|SET DEFAULT|SET NULL}] | CHECK (<search_condition>)} ]] local col_type = KV'type' / K'COMPUTED BY ('..E'computed_by_expr'..')' / N'domain' ) local col_def = N'name'..col_type.. O(K'DEFAULT'..E'default').. --TODO: field.default -> K'USER' O(B'not_null'..K'NOT NULL').. O(constraint).. O(K'COLLATE'..N'collate') return sql.ast(function() return K'CREATE TABLE'..N'name'..'(\n\t'..I(col_def, 'fields', ',\n\t')..'\n)' end) end
mit
Cloudef/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5c5.lua
5
1688
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Gate: Magical Gizmo -- Involved In Mission: The Horutoto Ruins Experiment -- !pos 419 0 -27 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 1) then player:startEvent(42); else player:showText(npc,DOOR_FIRMLY_CLOSED); end return 1; end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 42) then player:setVar("MissionStatus",2); -- Generate a random value to use for the next part of the mission -- where you have to examine 6 Magical Gizmo's, each of them having -- a number from 1 to 6 (Remember, setting 0 deletes the var) local random_value = math.random(1,6); player:setVar("MissionStatus_rv",random_value); -- 'rv' = random value player:setVar("MissionStatus_op1",1); player:setVar("MissionStatus_op2",1); player:setVar("MissionStatus_op3",1); player:setVar("MissionStatus_op4",1); player:setVar("MissionStatus_op5",1); player:setVar("MissionStatus_op6",1); end end;
gpl-3.0
Cloudef/darkstar
scripts/zones/Port_San_dOria/npcs/Coullave.lua
5
1658
----------------------------------- -- Area: Port San d'Oria -- NPC: Coullave -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) player:showText(npc,COULLAVE_SHOP_DIALOG); local stock = { 0x1020,4445,1, --Ether 0x43a1,1107,1, --Grenade 0x30a8,552,1, --Hachimaki 0x3128,833,1, --Kenpogi 0x32a8,424,1, --Kyahan 0x1010,837,1, --Potion 0x31a8,458,1, --Tekko 0x3228,666,1, --Sitabaki 0x02c0,96,2, --Bamboo Stick 0x1037,736,2, --Echo Drops 0x1034,290,3, --Antidote 0x1036,2387,3, --Eye Drops 0x349d,1150,3} --Leather Ring showNationShop(player, NATION_SANDORIA, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
fgprodigal/RayUI
Interface/AddOns/RayUI/libs/oUF/elements/phaseindicator.lua
3
2272
--[[ # Element: Phasing Indicator Toggles the visibility of an indicator based on the unit's phasing relative to the player. ## Widget PhaseIndicator - Any UI widget. ## Notes A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set. ## Examples -- Position and size local PhaseIndicator = self:CreateTexture(nil, 'OVERLAY') PhaseIndicator:SetSize(16, 16) PhaseIndicator:SetPoint('TOPLEFT', self) -- Register it with oUF self.PhaseIndicator = PhaseIndicator --]] local _, ns = ... local oUF = ns.oUF local function Update(self, event) local element = self.PhaseIndicator --[[ Callback: PhaseIndicator:PreUpdate() Called before the element has been updated. * self - the PhaseIndicator element --]] if(element.PreUpdate) then element:PreUpdate() end local isInSamePhase = UnitInPhase(self.unit) if(isInSamePhase) then element:Hide() else element:Show() end --[[ Callback: PhaseIndicator:PostUpdate(isInSamePhase) Called after the element has been updated. * self - the PhaseIndicator element * isInSamePhase - indicates whether the element is hidden (boolean) --]] if(element.PostUpdate) then return element:PostUpdate(isInSamePhase) end end local function Path(self, ...) --[[ Override: PhaseIndicator.Override(self, event, ...) Used to completely override the internal update function. * self - the parent object * event - the event triggering the update (string) * ... - the arguments accompanying the event --]] return (self.PhaseIndicator.Override or Update) (self, ...) end local function ForceUpdate(element) return Path(element.__owner, 'ForceUpdate') end local function Enable(self) local element = self.PhaseIndicator if(element) then element.__owner = self element.ForceUpdate = ForceUpdate self:RegisterEvent('UNIT_PHASE', Path, true) if(element:IsObjectType('Texture') and not element:GetTexture()) then element:SetTexture([[Interface\TargetingFrame\UI-PhasingIcon]]) end return true end end local function Disable(self) local element = self.PhaseIndicator if(element) then element:Hide() self:UnregisterEvent('UNIT_PHASE', Path) end end oUF:AddElement('PhaseIndicator', Path, Enable, Disable)
mit
Warboss-rus/wargameengine
WargameEngine/WargameEngine/WargameEngine/Killteam/Chaos.lua
1
2527
races["Chaos"] = { racename = "Chaos", units = { ["Chaos Marine"] = { SupportedWeapons = { "Bolter", "Melta gun", "Heavy Bolter" }, Cost = 15, RangedWeapon = "Bolter", MeleeWeapon = "Knife", Model = "CSM.wbm", WS = 4, BS = 4, T = 4, Attacks = 1, Sv = 3, InvSv = 7, MovementSpeed = 6 }, ["Raptor"] = { SupportedWeapons = { "Bolt-pistol" }, Cost = 20, RangedWeapon = "Bolt-pistol", MeleeWeapon = "Knife", Model = "raptor.wbm", WS = 4, BS = 4, T = 4, Attacks = 3, Sv = 3, InvSv = 7, MovementSpeed = 12 }, ["Chaos Terminator"] = { SupportedWeapons = { "Power Fist", "Lightning claws" }, Cost = 40, RangedWeapon = "Combi Bolter", MeleeWeapon = "Power Fist", Model = "Chaos_terminator_SB+PF.wbm", WS = 4, BS = 4, T = 4, Attacks = 2, Sv = 2, InvSv = 5, MovementSpeed = 6 }, }, weapons = { ["Knife"] = { S = 4, Melee = true, Cost = 0, MeleeAP = 7, Model = "", AdditionalAttacks = 0, NoRanged = false, RerollFailed2Wound = false }, ["Power Fist"] = { S = 8, Melee = true, Cost = 0, MeleeAP = 2, Model = "Chaos_terminator_SB+PF.wbm", AdditionalAttacks = 0, NoRanged = false, RerollFailed2Wound = false }, ["Lightning claws"] = { S = 4, Melee = true, Cost = 0, MeleeAP = 3, Model = "Chaos_terminator_LC.wbm", AdditionalAttacks = 2, NoRanged = true, RerollFailed2Wound = true }, ["none"] = { Range = 0, Melee = false, Cost = 0, Model = "", S = 0, AP = 0, Type = "", Shots = 0 }, ["Bolter"] = { Range = 24, Melee = false, Cost = 0, Model = "CSM.wbm", S = 4, AP = 5, Type = "RapidFire", Shots = 2 }, ["Heavy Bolter"] = { Range = 36, Melee = false, Cost = 10, Model = "CSM_HB.wbm", S = 5, AP = 4, Type = "Heavy", Shots = 3 }, ["Melta gun"] = { Range = 12, Melee = false, Cost = 15, Model = "CSM_melta.wbm", S = 8, AP = 1, Type = "Assault", Shots = 1 }, ["Bolt-pistol"] = { Range = 12, Melee = false, Cost = 0, Model = "", S = 4, AP = 5, Type = "Pistol", Shots = 1 }, ["Combi Bolter"] = { Range = 24, Melee = false, Cost = 0, Model = "", S = 4, AP = 5, Type = "Assault", Shots = 2 } } }
gpl-3.0
KarlKode/dotfiles
hammerspoon/hammerspoon.symlink/yabai_old.lua
1
1230
local socket = require("hs.socket") local module = {} module.sockFile = string.format("/tmp/yabai_%s.socket", os.getenv("USER")) module.sockTimeout = 5 module.send = function(fn, ...) assert( type(fn) == "function" or (getmetatable(fn) or {}).__call, "callback must be a function or object with __call metamethod" ) local args = table.pack(...) local message = "" for i = 1, args.n, 1 do message = message .. tostring(args[i]) .. string.char(0) end message = message .. string.char(0) local mySocket = socket.new() local results = "" mySocket:setTimeout(module.sockTimeout or -1):connect(module.sockFile, function() mySocket:write(message, function(_) mySocket:setCallback(function(data, _) results = results .. data -- having to do this is annoying; investigate module to see if we can -- add a method to get bytes of data waiting to be read if mySocket:connected() then mySocket:read("\n") else fn(results) end end) mySocket:read("\n") end) end) end return module
mit
coderstudy/luarocks
src/luarocks/path_cmd.lua
18
2345
--- @module luarocks.path_cmd -- Driver for the `luarocks path` command. local path_cmd = {} local util = require("luarocks.util") local deps = require("luarocks.deps") local cfg = require("luarocks.cfg") path_cmd.help_summary = "Return the currently configured package path." path_cmd.help_arguments = "" path_cmd.help = [[ Returns the package path currently configured for this installation of LuaRocks, formatted as shell commands to update LUA_PATH and LUA_CPATH. --bin Adds the system path to the output --append Appends the paths to the existing paths. Default is to prefix the LR paths to the existing paths. --lr-path Exports the Lua path (not formatted as shell command) --lr-cpath Exports the Lua cpath (not formatted as shell command) --lr-bin Exports the system path (not formatted as shell command) On Unix systems, you may run: eval `luarocks path` And on Windows: luarocks path > "%temp%\_lrp.bat" && call "%temp%\_lrp.bat" && del "%temp%\_lrp.bat" ]] --- Driver function for "path" command. -- @return boolean This function always succeeds. function path_cmd.run(...) local flags = util.parse_flags(...) local deps_mode = deps.get_deps_mode(flags) local lr_path, lr_cpath, lr_bin = cfg.package_paths() local path_sep = cfg.export_path_separator if flags["lr-path"] then util.printout(util.remove_path_dupes(lr_path, ';')) return true elseif flags["lr-cpath"] then util.printout(util.remove_path_dupes(lr_cpath, ';')) return true elseif flags["lr-bin"] then util.printout(util.remove_path_dupes(lr_bin, path_sep)) return true end if flags["append"] then lr_path = package.path .. ";" .. lr_path lr_cpath = package.cpath .. ";" .. lr_cpath lr_bin = os.getenv("PATH") .. path_sep .. lr_bin else lr_path = lr_path.. ";" .. package.path lr_cpath = lr_cpath .. ";" .. package.cpath lr_bin = lr_bin .. path_sep .. os.getenv("PATH") end util.printout(cfg.export_lua_path:format(util.remove_path_dupes(lr_path, ';'))) util.printout(cfg.export_lua_cpath:format(util.remove_path_dupes(lr_cpath, ';'))) if flags["bin"] then util.printout(cfg.export_path:format(util.remove_path_dupes(lr_bin, path_sep))) end return true end return path_cmd
mit
CaptainCN/QCEditor
cocos2d/cocos/scripting/lua-bindings/auto/api/DrawNode.lua
2
8444
-------------------------------- -- @module DrawNode -- @extend Node -- @parent_module cc -------------------------------- -- Draw an line from origin to destination with color. <br> -- param origin The line origin.<br> -- param destination The line destination.<br> -- param color The line color.<br> -- js NA -- @function [parent=#DrawNode] drawLine -- @param self -- @param #vec2_table origin -- @param #vec2_table destination -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- @overload self, vec2_table, vec2_table, vec2_table, vec2_table, color4f_table -- @overload self, vec2_table, vec2_table, color4f_table -- @function [parent=#DrawNode] drawRect -- @param self -- @param #vec2_table p1 -- @param #vec2_table p2 -- @param #vec2_table p3 -- @param #vec2_table p4 -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- @overload self, vec2_table, float, float, unsigned int, color4f_table -- @overload self, vec2_table, float, float, unsigned int, float, float, color4f_table -- @function [parent=#DrawNode] drawSolidCircle -- @param self -- @param #vec2_table center -- @param #float radius -- @param #float angle -- @param #unsigned int segments -- @param #float scaleX -- @param #float scaleY -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- -- @function [parent=#DrawNode] setLineWidth -- @param self -- @param #float lineWidth -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- js NA -- @function [parent=#DrawNode] onDrawGLPoint -- @param self -- @param #mat4_table transform -- @param #unsigned int flags -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- draw a dot at a position, with a given radius and color. <br> -- param pos The dot center.<br> -- param radius The dot radius.<br> -- param color The dot color. -- @function [parent=#DrawNode] drawDot -- @param self -- @param #vec2_table pos -- @param #float radius -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- draw a segment with a radius and color. <br> -- param from The segment origin.<br> -- param to The segment destination.<br> -- param radius The segment radius.<br> -- param color The segment color. -- @function [parent=#DrawNode] drawSegment -- @param self -- @param #vec2_table from -- @param #vec2_table to -- @param #float radius -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- Get the color mixed mode.<br> -- lua NA -- @function [parent=#DrawNode] getBlendFunc -- @param self -- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc) -------------------------------- -- js NA -- @function [parent=#DrawNode] onDraw -- @param self -- @param #mat4_table transform -- @param #unsigned int flags -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- @overload self, vec2_table, float, float, unsigned int, bool, color4f_table -- @overload self, vec2_table, float, float, unsigned int, bool, float, float, color4f_table -- @function [parent=#DrawNode] drawCircle -- @param self -- @param #vec2_table center -- @param #float radius -- @param #float angle -- @param #unsigned int segments -- @param #bool drawLineToCenter -- @param #float scaleX -- @param #float scaleY -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- Draws a quad bezier path.<br> -- param origin The origin of the bezier path.<br> -- param control The control of the bezier path.<br> -- param destination The destination of the bezier path.<br> -- param segments The number of segments.<br> -- param color Set the quad bezier color. -- @function [parent=#DrawNode] drawQuadBezier -- @param self -- @param #vec2_table origin -- @param #vec2_table control -- @param #vec2_table destination -- @param #unsigned int segments -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- js NA -- @function [parent=#DrawNode] onDrawGLLine -- @param self -- @param #mat4_table transform -- @param #unsigned int flags -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- draw a triangle with color. <br> -- param p1 The triangle vertex point.<br> -- param p2 The triangle vertex point.<br> -- param p3 The triangle vertex point.<br> -- param color The triangle color.<br> -- js NA -- @function [parent=#DrawNode] drawTriangle -- @param self -- @param #vec2_table p1 -- @param #vec2_table p2 -- @param #vec2_table p3 -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- Set the color mixed mode.<br> -- code<br> -- When this function bound into js or lua,the parameter will be changed<br> -- In js: var setBlendFunc(var src, var dst)<br> -- endcode<br> -- lua NA -- @function [parent=#DrawNode] setBlendFunc -- @param self -- @param #cc.BlendFunc blendFunc -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- Clear the geometry in the node's buffer. -- @function [parent=#DrawNode] clear -- @param self -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- Draws a solid rectangle given the origin and destination point measured in points.<br> -- The origin and the destination can not have the same x and y coordinate.<br> -- param origin The rectangle origin.<br> -- param destination The rectangle destination.<br> -- param color The rectangle color.<br> -- js NA -- @function [parent=#DrawNode] drawSolidRect -- @param self -- @param #vec2_table origin -- @param #vec2_table destination -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- -- @function [parent=#DrawNode] getLineWidth -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Draw a point.<br> -- param point A Vec2 used to point.<br> -- param pointSize The point size.<br> -- param color The point color.<br> -- js NA -- @function [parent=#DrawNode] drawPoint -- @param self -- @param #vec2_table point -- @param #float pointSize -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- Draw a cubic bezier curve with color and number of segments<br> -- param origin The origin of the bezier path.<br> -- param control1 The first control of the bezier path.<br> -- param control2 The second control of the bezier path.<br> -- param destination The destination of the bezier path.<br> -- param segments The number of segments.<br> -- param color Set the cubic bezier color. -- @function [parent=#DrawNode] drawCubicBezier -- @param self -- @param #vec2_table origin -- @param #vec2_table control1 -- @param #vec2_table control2 -- @param #vec2_table destination -- @param #unsigned int segments -- @param #color4f_table color -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- creates and initialize a DrawNode node.<br> -- return Return an autorelease object. -- @function [parent=#DrawNode] create -- @param self -- @return DrawNode#DrawNode ret (return value: cc.DrawNode) -------------------------------- -- -- @function [parent=#DrawNode] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table transform -- @param #unsigned int flags -- @return DrawNode#DrawNode self (return value: cc.DrawNode) -------------------------------- -- -- @function [parent=#DrawNode] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#DrawNode] DrawNode -- @param self -- @return DrawNode#DrawNode self (return value: cc.DrawNode) return nil
mit
CaptainCN/QCEditor
cocos2d/cocos/scripting/lua-bindings/auto/api/ProgressTimer.lua
2
6239
-------------------------------- -- @module ProgressTimer -- @extend Node -- @parent_module cc -------------------------------- -- Initializes a progress timer with the sprite as the shape the timer goes through -- @function [parent=#ProgressTimer] initWithSprite -- @param self -- @param #cc.Sprite sp -- @return bool#bool ret (return value: bool) -------------------------------- -- Return the Reverse direction.<br> -- return If the direction is Anti-clockwise,it will return true. -- @function [parent=#ProgressTimer] isReverseDirection -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- This allows the bar type to move the component at a specific rate.<br> -- Set the component to 0 to make sure it stays at 100%.<br> -- For example you want a left to right bar but not have the height stay 100%.<br> -- Set the rate to be Vec2(0,1); and set the midpoint to = Vec2(0,.5f).<br> -- param barChangeRate A Vec2. -- @function [parent=#ProgressTimer] setBarChangeRate -- @param self -- @param #vec2_table barChangeRate -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- Percentages are from 0 to 100.<br> -- return Percentages. -- @function [parent=#ProgressTimer] getPercentage -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Set the sprite as the shape. <br> -- param sprite The sprite as the shape. -- @function [parent=#ProgressTimer] setSprite -- @param self -- @param #cc.Sprite sprite -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- Change the percentage to change progress. <br> -- return A Type -- @function [parent=#ProgressTimer] getType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- The image to show the progress percentage, retain. <br> -- return A sprite. -- @function [parent=#ProgressTimer] getSprite -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- Midpoint is used to modify the progress start position.<br> -- If you're using radials type then the midpoint changes the center point.<br> -- If you're using bar type then the midpoint changes the bar growth.<br> -- it expands from the center but clamps to the sprites edge so:<br> -- you want a left to right then set the midpoint all the way to Vec2(0,y).<br> -- you want a right to left then set the midpoint all the way to Vec2(1,y).<br> -- you want a bottom to top then set the midpoint all the way to Vec2(x,0).<br> -- you want a top to bottom then set the midpoint all the way to Vec2(x,1).<br> -- param point A Vec2 point. -- @function [parent=#ProgressTimer] setMidpoint -- @param self -- @param #vec2_table point -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- Returns the BarChangeRate.<br> -- return A barChangeRate. -- @function [parent=#ProgressTimer] getBarChangeRate -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Set the Reverse direction.<br> -- param value If value is false it will clockwise,if is true it will Anti-clockwise. -- @function [parent=#ProgressTimer] setReverseDirection -- @param self -- @param #bool value -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- Returns the Midpoint. <br> -- return A Vec2. -- @function [parent=#ProgressTimer] getMidpoint -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Set the initial percentage values. <br> -- param percentage The initial percentage values. -- @function [parent=#ProgressTimer] setPercentage -- @param self -- @param #float percentage -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- Set the ProgressTimer type. <br> -- param type Is an Type. -- @function [parent=#ProgressTimer] setType -- @param self -- @param #int type -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- Creates a progress timer with the sprite as the shape the timer goes through.<br> -- param sp The sprite as the shape the timer goes through.<br> -- return A ProgressTimer. -- @function [parent=#ProgressTimer] create -- @param self -- @param #cc.Sprite sp -- @return ProgressTimer#ProgressTimer ret (return value: cc.ProgressTimer) -------------------------------- -- -- @function [parent=#ProgressTimer] setAnchorPoint -- @param self -- @param #vec2_table anchorPoint -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- -- @function [parent=#ProgressTimer] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table transform -- @param #unsigned int flags -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- -- @function [parent=#ProgressTimer] setColor -- @param self -- @param #color3b_table color -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- -- @function [parent=#ProgressTimer] getColor -- @param self -- @return color3b_table#color3b_table ret (return value: color3b_table) -------------------------------- -- -- @function [parent=#ProgressTimer] setOpacity -- @param self -- @param #unsigned char opacity -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) -------------------------------- -- -- @function [parent=#ProgressTimer] getOpacity -- @param self -- @return unsigned char#unsigned char ret (return value: unsigned char) -------------------------------- -- js ctor -- @function [parent=#ProgressTimer] ProgressTimer -- @param self -- @return ProgressTimer#ProgressTimer self (return value: cc.ProgressTimer) return nil
mit
CaptainCN/QCEditor
cocos2d/cocos/scripting/lua-bindings/script/extension/DeprecatedExtensionEnum.lua
62
1410
if nil == cc.Control then return end _G.kCCControlStepperPartMinus = cc.CONTROL_STEPPER_PART_MINUS _G.kCCControlStepperPartPlus = cc.CONTROL_STEPPER_PART_PLUS _G.kCCControlStepperPartNone = cc.CONTROL_STEPPER_PART_NONE _G.CCControlEventTouchDown = cc.CONTROL_EVENTTYPE_TOUCH_DOWN _G.CCControlEventTouchDragInside = cc.CONTROL_EVENTTYPE_DRAG_INSIDE _G.CCControlEventTouchDragOutside = cc.CONTROL_EVENTTYPE_DRAG_OUTSIDE _G.CCControlEventTouchDragEnter = cc.CONTROL_EVENTTYPE_DRAG_ENTER _G.CCControlEventTouchDragExit = cc.CONTROL_EVENTTYPE_DRAG_EXIT _G.CCControlEventTouchUpInside = cc.CONTROL_EVENTTYPE_TOUCH_UP_INSIDE _G.CCControlEventTouchUpOutside = cc.CONTROL_EVENTTYPE_TOUCH_UP_OUTSIDE _G.CCControlEventTouchCancel = cc.CONTROL_EVENTTYPE_TOUCH_CANCEL _G.CCControlEventValueChanged = cc.CONTROL_EVENTTYPE_VALUE_CHANGED _G.CCControlStateNormal = cc.CONTROL_STATE_NORMAL _G.CCControlStateHighlighted = cc.CONTROL_STATE_HIGH_LIGHTED _G.CCControlStateDisabled = cc.CONTROL_STATE_DISABLED _G.CCControlStateSelected = cc.CONTROL_STATE_SELECTED _G.kCCScrollViewDirectionHorizontal = cc.SCROLLVIEW_DIRECTION_HORIZONTAL _G.kCCScrollViewDirectionVertical = cc.SCROLLVIEW_DIRECTION_VERTICAL _G.kCCTableViewFillTopDown = cc.TABLEVIEW_FILL_TOPDOWN _G.kCCTableViewFillBottomUp = cc.TABLEVIEW_FILL_BOTTOMUP
mit
ScegfOd/wesnoth
data/ai/micro_ais/micro_ai_self_data.lua
7
3920
-- This set of functions provides a consistent way of storing Micro AI variables -- in the AI's persistent data variable. These need to be stored inside -- a [micro_ai] tag, so that they are bundled together for a given Micro AI -- together with an ai_id= key. Their existence can then be checked when setting -- up another MAI. Otherwise other Micro AIs used in the same scenario might -- work incorrectly or not at all. -- Note that, ideally, we would delete these [micro_ai] tags when a Micro AI is -- deleted, but that that is not always possible as deletion can happen on -- another side's turn, while the data variable is only accessible during -- the AI turn. -- Note that, with this method, there can only ever be one of these tags for each -- Micro AI (but of course several when there are several Micro AIs for the -- same side). -- For the time being, we only allow key=value style variables. local H = wesnoth.require "lua/helper.lua" local micro_ai_self_data = {} function micro_ai_self_data.modify_mai_self_data(self_data, ai_id, action, vars_table) -- Modify data [micro_ai] tags -- @ai_id (string): the id of the Micro AI -- @action (string): "delete", "set" or "insert" -- @vars_table: table of key=value pairs with the variables to be set or inserted -- if this is set for @action="delete", then only the keys in @vars_table are deleted, -- otherwise the entire [micro_ai] tag is deleted -- Always delete the respective [micro_ai] tag, if it exists local existing_table for i,mai in ipairs(self_data, "micro_ai") do if (mai[1] == "micro_ai") and (mai[2].ai_id == ai_id) then if (action == "delete") and vars_table then for k,_ in pairs(vars_table) do mai[2][k] = nil end return end existing_table = mai[2] table.remove(self_data, i) break end end -- Then replace it, if the "set" action is selected -- or add the new keys to it, overwriting old ones with the same name, if action == "insert" if (action == "set") or (action == "insert") then local tag = { "micro_ai" } if (not existing_table) or (action == "set") then -- Important: we need to make a copy of the input table, not use it! tag[2] = {} for k,v in pairs(vars_table) do tag[2][k] = v end tag[2].ai_id = ai_id else for k,v in pairs(vars_table) do existing_table[k] = v end tag[2] = existing_table end table.insert(self_data, tag) end end function micro_ai_self_data.delete_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "delete", vars_table) end function micro_ai_self_data.insert_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "insert", vars_table) end function micro_ai_self_data.set_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "set", vars_table) end function micro_ai_self_data.get_mai_self_data(self_data, ai_id, key) -- Get the content of the data [micro_ai] tag for the given @ai_id -- Return value: -- - If tag is found: value of key if @key parameter is given, otherwise -- table of key=value pairs (including the ai_id key) -- - If no such tag is found: nil (if @key is set), otherwise empty table for mai in H.child_range(self_data, "micro_ai") do if (mai.ai_id == ai_id) then if key then return mai[key] else return mai end end end -- If we got here, no corresponding tag was found -- Return empty table; or nil if @key was set if (not key) then return {} end end return micro_ai_self_data
gpl-2.0
ignacio/luarocks
src/luarocks/install.lua
15
8077
--- Module implementing the LuaRocks "install" command. -- Installs binary rocks. --module("luarocks.install", package.seeall) local install = {} package.loaded["luarocks.install"] = install local path = require("luarocks.path") local repos = require("luarocks.repos") local fetch = require("luarocks.fetch") local util = require("luarocks.util") local fs = require("luarocks.fs") local deps = require("luarocks.deps") local manif = require("luarocks.manif") local remove = require("luarocks.remove") local cfg = require("luarocks.cfg") install.help_summary = "Install a rock." install.help_arguments = "{<rock>|<name> [<version>]}" install.help = [[ Argument may be the name of a rock to be fetched from a repository or a filename of a locally available rock. --keep Do not remove previously installed versions of the rock after installing a new one. This behavior can be made permanent by setting keep_other_versions=true in the configuration file. --only-deps Installs only the dependencies of the rock. ]]..util.deps_mode_help() --- Install a binary rock. -- @param rock_file string: local or remote filename of a rock. -- @param deps_mode: string: Which trees to check dependencies for: -- "one" for the current default tree, "all" for all trees, -- "order" for all trees with priority >= the current default, "none" for no trees. -- @return (string, string) or (nil, string, [string]): Name and version of -- installed rock if succeeded or nil and an error message followed by an error code. function install.install_binary_rock(rock_file, deps_mode) assert(type(rock_file) == "string") local name, version, arch = path.parse_name(rock_file) if not name then return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'." end if arch ~= "all" and arch ~= cfg.arch then return nil, "Incompatible architecture "..arch, "arch" end if repos.is_installed(name, version) then repos.delete_version(name, version) end local rollback = util.schedule_function(function() fs.delete(path.install_dir(name, version)) fs.remove_dir_if_empty(path.versions_dir(name)) end) local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version)) if not ok then return nil, err, errcode end local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version)) if err then return nil, "Failed loading rockspec for installed package: "..err, errcode end if deps_mode == "none" then util.printerr("Warning: skipping dependency checks.") else ok, err, errcode = deps.check_external_deps(rockspec, "install") if err then return nil, err, errcode end end -- For compatibility with .rock files built with LuaRocks 1 if not fs.exists(path.rock_manifest_file(name, version)) then ok, err = manif.make_rock_manifest(name, version) if err then return nil, err end end if deps_mode ~= "none" then ok, err, errcode = deps.fulfill_dependencies(rockspec, deps_mode) if err then return nil, err, errcode end end ok, err = repos.deploy_files(name, version, repos.should_wrap_bin_scripts(rockspec)) if err then return nil, err end util.remove_scheduled_function(rollback) rollback = util.schedule_function(function() repos.delete_version(name, version) end) ok, err = repos.run_hook(rockspec, "post_install") if err then return nil, err end ok, err = manif.update_manifest(name, version, nil, deps_mode) if err then return nil, err end local license = "" if rockspec.description.license then license = ("(license: "..rockspec.description.license..")") end local root_dir = path.root_dir(cfg.rocks_dir) util.printout() util.printout(name.." "..version.." is now installed in "..root_dir.." "..license) util.remove_scheduled_function(rollback) return name, version end --- Installs the dependencies of a binary rock. -- @param rock_file string: local or remote filename of a rock. -- @param deps_mode: string: Which trees to check dependencies for: -- "one" for the current default tree, "all" for all trees, -- "order" for all trees with priority >= the current default, "none" for no trees. -- @return (string, string) or (nil, string, [string]): Name and version of -- the rock whose dependencies were installed if succeeded or nil and an error message -- followed by an error code. function install.install_binary_rock_deps(rock_file, deps_mode) assert(type(rock_file) == "string") local name, version, arch = path.parse_name(rock_file) if not name then return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'." end if arch ~= "all" and arch ~= cfg.arch then return nil, "Incompatible architecture "..arch, "arch" end local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version)) if not ok then return nil, err, errcode end local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version)) if err then return nil, "Failed loading rockspec for installed package: "..err, errcode end ok, err, errcode = deps.fulfill_dependencies(rockspec, deps_mode) if err then return nil, err, errcode end util.printout() util.printout("Succesfully installed dependencies for " ..name.." "..version) return name, version end --- Driver function for the "install" command. -- @param name string: name of a binary rock. If an URL or pathname -- to a binary rock is given, fetches and installs it. If a rockspec or a -- source rock is given, forwards the request to the "build" command. -- If a package name is given, forwards the request to "search" and, -- if returned a result, installs the matching rock. -- @param version string: When passing a package name, a version number -- may also be given. -- @return boolean or (nil, string, exitcode): True if installation was -- successful, nil and an error message otherwise. exitcode is optionally returned. function install.run(...) local flags, name, version = util.parse_flags(...) if type(name) ~= "string" then return nil, "Argument missing. "..util.see_help("install") end local ok, err = fs.check_command_permissions(flags) if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end if name:match("%.rockspec$") or name:match("%.src%.rock$") then util.printout("Using "..name.."... switching to 'build' mode") local build = require("luarocks.build") return build.run(name, util.forward_flags(flags, "local", "keep", "deps-mode", "only-deps")) elseif name:match("%.rock$") then if flags["only-deps"] then ok, err = install.install_binary_rock_deps(name, deps.get_deps_mode(flags)) else ok, err = install.install_binary_rock(name, deps.get_deps_mode(flags)) end if not ok then return nil, err end local name, version = ok, err if (not flags["only-deps"]) and (not flags["keep"]) and not cfg.keep_other_versions then local ok, err = remove.remove_other_versions(name, version, flags["force"]) if not ok then util.printerr(err) end end return name, version else local search = require("luarocks.search") local results, err = search.find_suitable_rock(search.make_query(name:lower(), version)) if err then return nil, err elseif type(results) == "string" then local url = results util.printout("Installing "..url.."...") return install.run(url, util.forward_flags(flags)) else util.printout() util.printerr("Could not determine which rock to install.") util.title("Search results:") search.print_results(results) return nil, (next(results) and "Please narrow your query." or "No results found.") end end end return install
mit
alexschrod/freedink-lua
lua-scripts/s1-mh-f.lua
1
2522
function talk() if global.wizard_see > 3 then return end player:freeze() local cs = cutscene.create_cutscene(200) local function whoosh(x, y) local mcrap = dink.create_sprite(x, y, brain.KILL_SEQ_DONE, 167, 1) mcrap.seq = 167 dink.playsound(24, 22052, 0, nil, false) end cs:add_command("whoosh", whoosh) cs:add_participant("d", player) cs:add_participant("l", current_sprite, "9") cs:command("ass", {"d", "l"}, { { "Hey, it's a scroll from Phoenix!", "Who?!", "Let's see what he has to say..." }, { "Dear player,", "Thank you for testing my Lua version of the original", "Dink Smallwood quest.", "I did not see it worth the while to re-code the whole quest", "so the Lua story ends here.", "If you have not done so already", "make sure you take a look at the Lua scripts that came with", "this special version of Dink Smallwood, and feel free to", "compare them with the original DinkC scripts, to see for", "yourself which script language you prefer the most.", "I have obviously chosen Lua, which is my reason for", "bothering to implement support for it in the first place.", "Thanks again for playing, feel free to leave me comments,", "suggestions and bugs in my Dink Network forum thread(s),", "or at the Lua Dink github page (should be linked to from", "all relevant discussion threads.)" }, { "Huh. I've never read such gibberish. And who is Phoenix?", "Oh wait, there's a little more text", "on the other side of the letter." }, { "P.S. Why don't you try to write some Lua-driven", "Dink adventure yourself? I've tried documenting the", "differences and new features as best I can on the", "github-associated Wiki.", "You will now be teleported to the Operating System." }, { "What in the world is this Phoenix person talking about?", "I've never heard of this Lua or github. I do see my name", "in there, though... DinkC, Dink Network.", "This kinda creeps me out. And what is an Operating System?", } }) player:say("Hey! What's going on?!") whoosh(player.x, player.y + 20) dink.wait(200) whoosh(player.x, player.y - 20) dink.wait(200) whoosh(player.x + 20, player.y) dink.wait(200) whoosh(player.x - 20, player.y) dink.wait(200) whoosh(player.x, player.y) dink.wait(200) dink.fade_down(); dink.kill_game(); end
gpl-3.0
deplinenoise/tundra
scripts/tundra/syntax/dotnet.lua
28
3090
module(..., package.seeall) local util = require "tundra.util" local nodegen = require "tundra.nodegen" local depgraph = require "tundra.depgraph" local _csbase_mt = nodegen.create_eval_subclass { DeclToEnvMappings = { References = "CSLIBS", RefPaths = "CSLIBPATH", }, } local _csexe_mt = nodegen.create_eval_subclass({ Label = "CSharpExe $(@)", Suffix = "$(CSPROGSUFFIX)", Action = "$(CSCEXECOM)" }, _csbase_mt) local _cslib_mt = nodegen.create_eval_subclass({ Label = "CSharpLib $(@)", Suffix = "$(CSLIBSUFFIX)", Action = "$(CSCLIBCOM)" }, _csbase_mt) local csSourceExts = { ".cs" } local csResXExts = { ".resx" } local function setup_refs_from_dependencies(env, dep_nodes, deps) local dll_exts = { env:interpolate("$(CSLIBSUFFIX)") } local refs = {} local parent_env = env:get_parent() for _, x in util.nil_ipairs(dep_nodes) do if x.Keyword == "CSharpLib" then local outputs = {} local dag = x:get_dag(parent_env) deps[#deps + 1] = dag dag:insert_output_files(refs, dll_exts) end end for _, r in ipairs(refs) do env:append("CSLIBS", r) end end local function setup_resources(generator, env, assembly_name, resx_files, pass) local result_files = {} local deps = {} local i = 1 for _, resx in util.nil_ipairs(resx_files) do local basename = path.get_filename_base(resx) local result_file = string.format("$(OBJECTDIR)/_rescompile/%s.%s.resources", assembly_name, basename) result_files[i] = result_file deps[i] = depgraph.make_node { Env = env, Pass = pass, Label = "resgen $(@)", Action = "$(CSRESGEN)", InputFiles = { resx }, OutputFiles = { result_file }, } env:append("CSRESOURCES", result_file) i = i + 1 end return result_files, deps end function _csbase_mt:create_dag(env, data, deps) local sources = data.Sources local resources = data.Resources or {} for _, r in util.nil_ipairs(resources) do env:append("CSRESOURCES", r) end sources = util.merge_arrays_2(sources, resources) setup_refs_from_dependencies(env, data.Depends, deps) return depgraph.make_node { Env = env, Pass = data.Pass, Label = self.Label, Action = self.Action, InputFiles = sources, OutputFiles = { nodegen.get_target(data, self.Suffix, self.Prefix) }, Dependencies = util.uniq(deps), } end do local csblueprint = { Name = { Required = true, Help = "Set output (base) filename", Type = "string", }, Sources = { Required = true, Help = "List of source files", Type = "source_list", ExtensionKey = "DOTNET_SUFFIXES", }, Resources = { Help = "List of resource files", Type = "source_list", ExtensionKey = "DOTNET_SUFFIXES_RESOURCE", }, Target = { Help = "Override target location", Type = "string", }, } nodegen.add_evaluator("CSharpExe", _csexe_mt, csblueprint) nodegen.add_evaluator("CSharpLib", _cslib_mt, csblueprint) end
mit
CaptainCN/QCEditor
cocos2d/cocos/scripting/lua-bindings/auto/api/ParticleSystem3D.lua
6
5418
-------------------------------- -- @module ParticleSystem3D -- @extend Node,BlendProtocol -- @parent_module cc -------------------------------- -- remove affector by index -- @function [parent=#ParticleSystem3D] removeAffector -- @param self -- @param #int index -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- resume particle -- @function [parent=#ParticleSystem3D] resumeParticleSystem -- @param self -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- remove all particle affector -- @function [parent=#ParticleSystem3D] removeAllAffector -- @param self -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- add particle affector -- @function [parent=#ParticleSystem3D] addAffector -- @param self -- @param #cc.Particle3DAffector affector -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- particle system play control -- @function [parent=#ParticleSystem3D] startParticleSystem -- @param self -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- is enabled -- @function [parent=#ParticleSystem3D] isEnabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- return particle render -- @function [parent=#ParticleSystem3D] getRender -- @param self -- @return Particle3DRender#Particle3DRender ret (return value: cc.Particle3DRender) -------------------------------- -- set emitter for particle system, can set your own particle emitter -- @function [parent=#ParticleSystem3D] setEmitter -- @param self -- @param #cc.Particle3DEmitter emitter -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- -- @function [parent=#ParticleSystem3D] isKeepLocal -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Enables or disables the system. -- @function [parent=#ParticleSystem3D] setEnabled -- @param self -- @param #bool enabled -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- get particle quota -- @function [parent=#ParticleSystem3D] getParticleQuota -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- override function -- @function [parent=#ParticleSystem3D] getBlendFunc -- @param self -- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc) -------------------------------- -- pause particle -- @function [parent=#ParticleSystem3D] pauseParticleSystem -- @param self -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- get particle playing state -- @function [parent=#ParticleSystem3D] getState -- @param self -- @return int#int ret (return value: int) -------------------------------- -- get alive particles count -- @function [parent=#ParticleSystem3D] getAliveParticleCount -- @param self -- @return int#int ret (return value: int) -------------------------------- -- set particle quota -- @function [parent=#ParticleSystem3D] setParticleQuota -- @param self -- @param #unsigned int quota -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- override function -- @function [parent=#ParticleSystem3D] setBlendFunc -- @param self -- @param #cc.BlendFunc blendFunc -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- set particle render, can set your own particle render -- @function [parent=#ParticleSystem3D] setRender -- @param self -- @param #cc.Particle3DRender render -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- stop particle -- @function [parent=#ParticleSystem3D] stopParticleSystem -- @param self -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- -- @function [parent=#ParticleSystem3D] setKeepLocal -- @param self -- @param #bool keepLocal -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- override function -- @function [parent=#ParticleSystem3D] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table transform -- @param #unsigned int flags -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- override function -- @function [parent=#ParticleSystem3D] update -- @param self -- @param #float delta -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) -------------------------------- -- -- @function [parent=#ParticleSystem3D] ParticleSystem3D -- @param self -- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D) return nil
mit
ld-test/hotswap-lfs
src/hotswap/ev.lua
11
1130
local posix = require "posix" local ev = require "ev" local xxhash = require "xxhash" local Hotswap = getmetatable (require "hotswap") local Ev = {} function Ev.new (t) return Hotswap.new { new = Ev.new, observe = Ev.observe, loop = t and t.loop or ev.Loop.default, observed = {}, hashes = {}, seed = 0x5bd1e995, } end function Ev:observe (name, filename) if self.observed [name] then return end do local file = assert (io.open (filename, "r")) self.hashes [name] = xxhash.xxh32 (file:read "*all", self.seed) file:close () end local hotswap = self local current = filename repeat local stat = ev.Stat.new (function () local file = assert (io.open (filename, "r")) local hash = xxhash.xxh32 (file:read "*all", self.seed) file:close () if hash ~= self.hashes [name] then hotswap.loaded [name] = nil hotswap.try_require (name) end end, current) self.observed [current] = stat stat:start (hotswap.loop) current = posix.readlink (current) until not current end return Ev.new ()
mit
Starfox64/FoxedBot
addons/foxedbot/lua/foxedbot/sv_callbacks.lua
1
5325
--[[ The OnChat callback is called whenever a message should be printed in chat. ]]-- FoxedBot.addCallback("OnChat", function( data ) net.Start("FoxedBot_Chat") net.WriteTable(data) net.Send(player.GetAll()) end) --[[ The OnAnnounce callback is called whenever an announcement should be printed on screen. ]]-- FoxedBot.addCallback("OnAnnounce", function( data ) net.Start("FoxedBot_Announce") net.WriteString(data.message) net.Send(player.GetAll()) end) --[[ The GetPlayers callback sends a list of players to the person who requested it. ]]-- FoxedBot.addCallback("GetPlayers", function( data ) local text = "Server "..FoxedBot.ServerID.."'s players:" for _, ply in pairs(player.GetAll()) do text = text.."\n "..ply:UserID()..". "..ply:Name() end FoxedBot.sendMessage(data.steamID, text) end) --[[ The OnRCON callback is called whenever a console command should be ran. ]]-- FoxedBot.addCallback("OnRCON", function( data ) game.ConsoleCommand(data.command.."\n") FoxedBot.sendMessage(data.steamID, data.command.." has been executed on server "..FoxedBot.ServerID..".") end) --[[ The OnKick callback is called whenever a player should be kicked. ]]-- FoxedBot.addCallback("OnKick", function( data ) local ply = FoxedBot.findPlayer(data.name) if ply then ply:Kick(data.reason) FoxedBot.sendMessage(data.steamID, ply:Name().." was kicked from server "..FoxedBot.ServerID..".") end end) --[[ The OnKickID callback is called whenever a player should be kicked using their UserID(). ]]-- FoxedBot.addCallback("OnKickID", function( data ) local ply for _, v in pairs(player.GetAll()) do if v:UserID() == data.userID then ply = v break end end if ply then ply:Kick(data.reason) FoxedBot.sendMessage(data.steamID, ply:Name().." was kicked from server "..FoxedBot.ServerID..".") end end) --[[ The OnBan callback is called whenever a player should be banned. ]]-- FoxedBot.addCallback("OnBan", function( data ) local ply = FoxedBot.findPlayer(data.name) if ply then if FoxedBot.BanAddon == "ulx" then if ulx then ulx.ban(nil, ply, data.time, data.reason) else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use ULX, couldn't find it.") return end elseif FoxedBot.BanAddon == "evolve" then if evolve then evolve:Ban(ply:UniqueID(), data.time, data.reason, 0) else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use Evolve, couldn't find it.") return end elseif FoxedBot.BanAddon == "moderator" then if moderator then moderator.BanPlayer(ply:SteamID(), data.reason, data.time) else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use Moderator, couldn't find it.") return end else ply:Ban(data.time, true) end FoxedBot.sendMessage(data.steamID, ply:Name().." was banned from server "..FoxedBot.ServerID..".") end end) --[[ The OnBanID callback is called whenever a player should be banned using his SteamID. ]]-- FoxedBot.addCallback("OnBanID", function( data ) if FoxedBot.BanAddon == "ulx" then if ulx then ulx.banid(nil, data.target, data.time, data.reason) else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use ULX, couldn't find it.") return end elseif FoxedBot.BanAddon == "evolve" then if evolve then local uid = evolve:UniqueIDByProperty("SteamID", data.target) if uid then evolve:Ban(uid, data.time, data.reason, 0) end else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use Evolve, couldn't find it.") return end elseif FoxedBot.BanAddon == "moderator" then if moderator then moderator.BanPlayer(data.target, data.reason, data.time) else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use Moderator, couldn't find it.") return end else game.ConsoleCommand("kickid "..data.target.." Banned: "..data.reason.."\n") game.ConsoleCommand("banid "..data.time.." "..data.target.."\n") game.ConsoleCommand("writeid\n") end FoxedBot.sendMessage(data.steamID, data.target.." was banned from server "..FoxedBot.ServerID..".") end) --[[ The OnBanID callback is called whenever a player should be banned using his SteamID. ]]-- FoxedBot.addCallback("OnUnban", function( data ) if FoxedBot.BanAddon == "ulx" then if ulx then ulx.unban(nil, data.target) else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use ULX, couldn't find it.") return end elseif FoxedBot.BanAddon == "evolve" then if evolve then local uid = evolve:UniqueIDByProperty("SteamID", data.target) if uid then evolve:UnBan(uid, 0) end else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use Evolve, couldn't find it.") return end elseif FoxedBot.BanAddon == "moderator" then if moderator then moderator.RemoveBan(data.target) else FoxedBot.sendMessage(data.steamID, "Server "..FoxedBot.ServerID.." attempted to use Moderator, couldn't find it.") return end else game.ConsoleCommand("removeid "..data.target..";writeid\n") end FoxedBot.sendMessage(data.steamID, data.target.." was unbanned from server "..FoxedBot.ServerID..".") end)
gpl-2.0
joshua-meng/Util
luaexeclib/modulization.lua
1
5396
local string_split_ = function (input, delimiter) input = tostring(input) delimiter = tostring(delimiter) if (delimiter=='') then return false end local pos,arr = 0, {} -- for each divider found for st,sp in function() return string.find(input, delimiter, pos, true) end do table.insert(arr, string.sub(input, pos, st - 1)) pos = sp + 1 end table.insert(arr, string.sub(input, pos)) return arr end local setmetatableindex_ setmetatableindex_ = function(t, index) local mt = getmetatable(t) if not mt then mt = {} end if not mt.__index then mt.__index = index setmetatable(t, mt) elseif mt.__index ~= index then setmetatableindex_(mt, index) end end setmetatableindex = setmetatableindex_ function clone(object) local lookup_table = {} local function _copy(object) if type(object) ~= "table" then return object elseif lookup_table[object] then return lookup_table[object] end local newObject = {} lookup_table[object] = newObject for key, value in pairs(object) do newObject[_copy(key)] = _copy(value) end return setmetatable(newObject, getmetatable(object)) end return _copy(object) end function class(classname, ...) local cls = {__cname = classname} local supers = {...} for _, super in ipairs(supers) do local superType = type(super) assert(superType == "nil" or superType == "table" or superType == "function", string.format("class() - create class \"%s\" with invalid super class type \"%s\"", classname, superType)) if superType == "function" then assert(cls.__create == nil, string.format("class() - create class \"%s\" with more than one creating function", classname)); -- if super is function, set it to __create cls.__create = super elseif superType == "table" then if super[".isclass"] then -- super is native class assert(cls.__create == nil, string.format("class() - create class \"%s\" with more than one creating function or native class", classname)); cls.__create = function() return super:create() end else -- super is pure lua class cls.__supers = cls.__supers or {} cls.__supers[#cls.__supers + 1] = super if not cls.super then -- set first super pure lua class as class.super cls.super = super end end else error(string.format("class() - create class \"%s\" with invalid super type", classname), 0) end end cls.__index = cls if not cls.__supers or #cls.__supers == 1 then setmetatable(cls, {__index = cls.super}) else setmetatable(cls, {__index = function(_, key) local supers = cls.__supers for i = 1, #supers do local super = supers[i] if super[key] then return super[key] end end end}) end if not cls.ctor then -- add default constructor cls.ctor = function() end end cls.new = function(...) local instance if cls.__create then instance = cls.__create(...) else instance = {} end setmetatableindex(instance, cls) instance.class = cls instance:ctor(...) return instance end cls.create = function(_, ...) return cls.new(...) end return cls end local iskindof_ iskindof_ = function(cls, name) local __index = rawget(cls, "__index") if type(__index) == "table" and rawget(__index, "__cname") == name then return true end if rawget(cls, "__cname") == name then return true end local __supers = rawget(__index, "__supers") if not __supers then return false end for _, super in ipairs(__supers) do if iskindof_(super, name) then return true end end return false end function iskindof(obj, classname) local t = type(obj) if t ~= "table" then return false end local mt = getmetatable(obj) if mt then return iskindof_(mt, classname) end return false end function import(moduleName, currentModuleName) local currentModuleNameParts local moduleFullName = moduleName local offset = 1 while true do if string.byte(moduleName, offset) ~= 46 then -- . moduleFullName = string.sub(moduleName, offset) if currentModuleNameParts and #currentModuleNameParts > 0 then moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName end break end offset = offset + 1 if not currentModuleNameParts then if not currentModuleName then local n,v = debug.getlocal(2, 1) currentModuleName = v end currentModuleNameParts = string_split_(currentModuleName, ".") end table.remove(currentModuleNameParts, #currentModuleNameParts) end return require(moduleFullName) end
gpl-2.0
TheJosh/chaotic-rage
data/cr/gametypes/zombies.lua
1
4693
---- ---- Lua script for the gametype "Zombies". ---- num_zombies = 0; num_zombie_players = 0; num_wanted = 0; num_dead = 0; num_lives = 3; spawn_cluster_num = 3; spawn_cluster_gap = 3000; round = 0; round_max = 0; score_table = 0; score_labels = {}; rain_rate = 1000; player_zombies = {}; do_score = function() score_labels.round.data = round; score_labels.alive.data = num_zombies - num_dead; score_labels.dead.data = num_dead; score_labels.lives.data = num_lives; score_labels.lives.r = 0.9; score_labels.lives.g = num_lives / 10; score_labels.lives.b = num_lives / 10; end; -- -- Spawns zombies -- spawn_func = function() zone = game.getRandomSpawnZone(factions.team2) if zone == nil then return end for i=1, spawn_cluster_num, 1 do -- may need to run this in a timer instead of three at once t = random_arg("zomb", "zomb_fast", "zomb_health", "zomb_strong") game.addNpcZone(t, "zombie", factions.team2, zone) end num_zombies = num_zombies + spawn_cluster_num if num_zombies < num_wanted then add_timer(spawn_cluster_gap, spawn_func); end do_score() end; -- -- Starts a new round -- start_round = function() num_zombies = 0; -- Spawn the player zombies, if there is a coordinate in the list position = table.remove(player_zombies, 1) while position ~= nil do game.addNpcCoord(get_selected_unittype(), "zombie", factions.team2, position) num_zombie_players = num_zombie_players + 1; num_zombies = num_zombies + 1; position = table.remove(player_zombies, 1) end round = round + 1; num_dead = 0; -- increase size of clusters if round >= 7 then spawn_cluster_num = spawn_cluster_num + 1 end; -- increase number of zombies -- increase is always in the size of a cluster if num_wanted < 40 then num_wanted = num_wanted + spawn_cluster_num + num_zombie_players; end; -- start off with a few extras if round == 1 then num_wanted = num_wanted + spawn_cluster_num end; -- decrease gap (ms) between clusters if spawn_cluster_gap > 1000 then spawn_cluster_gap = spawn_cluster_gap - 100 end; -- Start getting darker round three if round == 3 then daynight.animate(0.25, 10.0); end; -- start raining after 5th round if round >= 5 then if rain_rate < 5000 then rain_rate = rain_rate + 1500 end; weather.startRain(rain_rate) end; -- Cool label if round > round_max then lab = add_label(0, 350, "Winner!"); else lab = add_label(0, 350, "Round " .. round); end; lab.align = 2; lab.r = 0.9; lab.g = 0.1; lab.b = 0.1; lab.font = "Digitalt" lab.size = 70.0 -- Fade out the message anim = add_interval(100, function() lab.a = lab.a - 0.03; if lab.a <= 0.0 then -- We should make this actually remove the label -- but it needs to be network aware and faction aware -- needs more thought first remove_timer(anim); end; end); -- Winner? if round > round_max then game_over(1); end; -- Do an ammo drop if round % 3 == 0 then show_alert_message("Would you like some more ammo?"); game.addPickupRand("ammo_current"); end; -- Lets get spawning add_timer(spawn_cluster_gap, spawn_func); do_score(); end; -- -- Spawn a player -- bind_playerjoin(function(slot) game.addPlayer(get_selected_unittype(), factions.team1, slot); end); -- -- Game start -- bind_gamestart(function(r_max) round_max = r_max; add_timer(2500, start_round); add_label(-200, 50, "Round"); score_labels.round = add_label(-70, 50, "0"); add_label(-200, 70, "Alive"); score_labels.alive = add_label(-70, 70, "0"); add_label(-200, 90, "Dead"); score_labels.dead = add_label(-70, 90, "0"); add_label(-200, 110, "Lives"); score_labels.lives = add_label(-70, 110, num_lives); weather.disableRandom(); daynight.disableCycle(); end); -- -- Handle unit deaths -- bind_playerdied(function(slot) num_lives = num_lives - 1 do_score(); if (num_lives == 0) then lab = add_label(0, 350, "FAILURE"); lab.align = 2; lab.r = 0.9; lab.g = 0.1; lab.b = 0.1; lab.font = "Digitalt" lab.size = 70.0 add_timer(5000, function() game_over(0); end) return end; show_alert_message("Just not good enough I see...", slot); add_timer(2000, function() game.addPlayer(get_selected_unittype(), factions.team1, slot); end); player = game.getPlayerFromSlot(slot) if player ~= nil then table.insert(player_zombies, player.position); end end); -- -- Handle unit deaths -- bind_npcdied(function() num_dead = num_dead + 1; do_score(); -- Is the round over? if num_dead == num_wanted then show_alert_message("I guess you got them...this time"); num_wanted = num_wanted - num_zombie_players; num_zombie_players = 0; add_timer(2500, start_round); end; end);
gpl-2.0
joeyhng/nn
FlattenTable.lua
21
3205
local FlattenTable, parent = torch.class('nn.FlattenTable', 'nn.Module') function FlattenTable:__init() parent.__init(self) self.output = {} self.input_map = {} self.gradInput = {} end -- Recursive function to flatten a table (output is a table) local function flatten(output, input) local input_map -- has the same structure as input, but stores the -- indices to the corresponding output if type(input) == 'table' then input_map = {} -- forward DFS order for i = 1, #input do input_map[#input_map+1] = flatten(output, input[i]) end else input_map = #output + 1 output[input_map] = input -- append the tensor end return input_map end -- Recursive function to check if we need to rebuild the output table local function checkMapping(output, input, input_map) if input_map == nil or output == nil or input == nil then return false end if type(input) == 'table' then if type(input_map) ~= 'table' then return false end if #input ~= #input_map then return false end -- forward DFS order for i = 1, #input do local ok = checkMapping(output, input[i], input_map[i]) if not ok then return false end end return true else if type(input_map) ~= 'number' then return false end return output[input_map] == input end end -- During BPROP we have to build a gradInput with the same shape as the -- input. This is a recursive function to build up a gradInput local function inverseFlatten(gradOutput, input_map) if type(input_map) == 'table' then local gradInput = {} for i = 1, #input_map do gradInput[#gradInput + 1] = inverseFlatten(gradOutput, input_map[i]) end return gradInput else return gradOutput[input_map] end end function FlattenTable:updateOutput(input) assert(type(input) == 'table', 'input must be a table') -- to avoid updating rebuilding the flattened table every updateOutput call -- we will do a DFS pass over the existing output table and the inputs to -- see if it needs to be rebuilt. if not checkMapping(self.output, input, self.input_map) then self.output = {} self.input_map = flatten(self.output, input) end return self.output end function FlattenTable:updateGradInput(input, gradOutput) assert(type(input) == 'table', 'input must be a table') assert(type(input) == 'table', 'gradOutput must be a table') -- If the input changes between the updateOutput and updateGradInput call, -- then we may have to rebuild the input_map! However, let's assume that -- the input_map is valid and that forward has already been called. -- However, we should check that the gradInput is valid: if not checkMapping(gradOutput, self.gradInput, self.input_map) then self.gradInput = inverseFlatten(gradOutput, self.input_map) end return self.gradInput end function FlattenTable:type(type, tensorCache) -- This function just stores references so we don't need to do any type -- conversions. Just force the tables to be empty. self:clearState() end function FlattenTable:clearState() self.input_map = {} return parent.clearState(self) end
bsd-3-clause
alexschrod/freedink-lua
share/freedink/init.lua
1
29030
-- init.lua -- -- Loaded by the C function dinklua_initialize(). Expected to contain the -- tables "script" and "routine", and the functions "resume_script", -- "run_script", "proc_exists" and "load_script". For more details on their use -- and expected functionality and parameters, see the file "dinklua.c". -- -- Be careful when editing this file. Mistakes in this file are hard to catch, -- because the Dink Engine often has trouble reporting where the problem lies. -- Make small, incremental edits and run Dink often in order to catch mistakes -- early. Lots of productive time has been lost simply due to a forgotten -- 'then' in an if statement... -- -- The tables "object", "yield", "choice_menu" and "dink" are set in the file -- "dinklua_bindings.c", in the method named "dinklua_bind_init", and they -- contain pointers to the C functions that are used to communicate with the -- Dink Engine from Lua. -- -- "object" functions are meant to be used by objects, such as the "sprite" -- object or the "soundbank" object. These are not made directly available -- to the user, but accessible through said objects. These functions typically -- have very long and descriptive names, and may also contain the word "yield", -- in which case they are yielding functions (described in more detail below), -- such as the function "yield_sprite_object_say_stop_npc". As they are neatly -- wrapped in objects, the final appearance to the scripter would simply be -- "sprite_object:say_stop_npc(...)" -- -- "yield" functions are functions that require the script to yield (i.e. return -- control back to the Dink Engine) after they have run. This is accomplished in -- Lua using the coroutine.yield() functionality. A typical example of a -- yielding function is the "wait" function. -- -- "dink" functions are functions that are meant to be used more or less -- directly by scripters. These are made available to scripters as the "dink" -- table in script environments. A few of these are modified before being handed -- over to the scripters, and many of the "yield" functions get placed in here -- as well, albeit with the coroutine.yield() wrapper. -- -- "choice_menu" is a special set of functions meant to be used by the choice -- menu object. Because the way the choice menu works in DinkC is so odd, -- its implementation had to differ quite substantially in Lua. -- -- Most code in this file has comments to help you figure out what it does, so -- for a more detailed explanation, read those. -- Helper functions local function decode_sprite(sprite, custom_error) local sprite_number if sprite == nil then sprite_number = 0 elseif type(sprite) == "number" then sprite_number = sprite elseif getmetatable(sprite) == sprite_metatable then sprite_number = sprite.sprite_number else if custom_error == nil then error("sprite parameter must be nil, a sprite number or a sprite object", 3) else error(custom_error, 3) end end return sprite_number end -- Sprite metatable: Handles sprite property assignment/reading sprite_metatable = { __newindex = function(sprite, key, value) -- Properties specific to Dink if sprite.sprite_number == 1 then if key == "can_walk_off_screen" then object.dink_object_can_walk_off_screen(value) return elseif key == "base_push" then object.set_dink_base_push(value) return end end -- Properties that take sprite objects as a value if key == "target" then value = decode_sprite(value, "target value must be a sprite number or a sprite object") end local ok, err = pcall(object.set_sprite_value, sprite.sprite_number, key, value) if not ok then error(err, 2) end end, __index = function(sprite, key) -- Return methods and properties specific to Dink if sprite.sprite_number == 1 then if key == "set_speed" then return function(self, speed) object.dink_object_set_speed(speed) end end end -- Return methods specific to sprites if key == "kill_wait" then return function(self) object.sprite_object_kill_wait(self.sprite_number) end elseif key == "freeze" then return function(self) object.sprite_object_freeze(self.sprite_number) end elseif key == "unfreeze" then return function(self) object.sprite_object_unfreeze(self.sprite_number) end elseif key == "say" then return function(self, text) object.sprite_object_say(text, self.sprite_number) end elseif key == "say_stop" then return function(self, text) object.yield_sprite_object_say_stop(text, self.sprite_number) coroutine.yield() end elseif key == "say_stop_npc" then return function(self, text) object.yield_sprite_object_say_stop_npc(text, self.sprite_number) coroutine.yield() end elseif key == "move" then return function(self, direction, destination, ignore_hardness) object.sprite_object_move(self.sprite_number, direction, destination, ignore_hardness) end elseif key == "move_stop" then return function(self, direction, destination, ignore_hardness) object.yield_sprite_object_move_stop(self.sprite_number, direction, destination, ignore_hardness) coroutine.yield() end elseif key == "draw_hard" then return function(self) object.sprite_object_draw_hard_sprite(self.sprite_number) end elseif key == "kill_shadow" then return function(self) object.sprite_object_kill_shadow(self.sprite_number) end elseif key == "hurt" then return function(self, damage) object.sprite_object_hurt(self.sprite_number, damage) end end -- Special properties if key == "editor_sprite" then local editor_num = object.get_sprite_value(sprite.sprite_number, "editor_num") if editor_num == 0 then return nil else return dink.get_editor_sprite(editor_num) end elseif key == "busy" then local text_sprite_num = object.sprite_object_busy(sprite.sprite_number) if text_sprite_num == 0 then return nil else return dink.get_sprite(text_sprite_num) end end local ok, value = pcall(object.get_sprite_value, sprite.sprite_number, key) if not ok then error(value, 2) end -- Properties that return sprite objects if key == "target" then if value > 0 then value = dink.get_sprite(value) else value = nil end end return value end } -- Sprite Custom Metatable: Makes it so you can use the sp_custom feature in a -- more natural way in Lua: sprite.custom["whatnot"] = 5, or alternatively, -- sprite.custom.whatnot = 5 sprite_custom_metatable = { -- Warning: Only "sprite_number" property available on this sprite object __newindex = function(sprite, key, value) object.sp_custom(key, sprite.sprite_number, value) end, -- Warning: Only "sprite_number" property available on this sprite object __index = function(sprite, key) return object.sp_custom(key, sprite.sprite_number, -1) end } --[[ Called with the desired sprite number, this function returns a lua table with special metatable values that effectively creates "properties" on the sprite objects, in such a way that you can do things like: some_sprite = dink.get_sprite(15) some_sprite.strength = 10 Generally, though, you'll probably not want to use this function. The variable "current_sprite" is always available to every script, as is "player" (sprite #1), so any other need will probably want to use another mechanism than a hardcoded number to share sprites. ]]-- function dink.get_sprite(sprite_number) return setmetatable({ sprite_number = sprite_number, custom = setmetatable({sprite_number = sprite_number}, sprite_custom_metatable) }, sprite_metatable) end -- Editor sprite metatable: Handles editor sprite property assignment/reading editor_sprite_metatable = { __newindex = function(editor_sprite, key, value) local ok, err = pcall(object.set_editor_value, editor_sprite.editor_number, key, value) -- error level 2 means that the error will be signaled on 2nd stack frame, -- that is the line at which the key has been set, rather than from here if not ok then error(err, 2) end end, __index = function(editor_sprite, key) -- Special properties if key == "sprite" then local sprite_num = object.get_editor_value(editor_sprite.editor_number, "sprite") if sprite_num == 0 then return nil else return dink.get_sprite(sprite_num) end end local ok, value = pcall(object.get_editor_value, editor_sprite.editor_number, key) if not ok then error(value, 2) end return value end } --[[ Called with the desired editor number, this function returns a lua table with special metatable values that effectively creates "properties" on the editor sprite objects, in such a way that you can do things like: local hold = current_sprite.editor_sprite hold.editor_type = editor_type.KILL_COMPLETELY Generally, though, you'll probably not want to use this function. Sprite objects have a property editor_sprite that will give you the proper editor sprite for the sprite. ]]-- function dink.get_editor_sprite(editor_number) return setmetatable({editor_number = editor_number}, editor_sprite_metatable) end -- Sound metatable: Handles soundbank property assignment/reading soundbank_metatable = { __newindex = function(t, key, value) local ok, err = pcall(object.set_soundbank_value, t.sound_number, key, value) if not ok then error(err, 2) end end, __index = function(t, key) -- Return methods specific to soundbanks if key == "kill" then return function(self) object.soundbank_object_set_kill(self.soundbank_number) end end local ok, value = pcall(object.get_soundbank_value, t.sound_number, key) if not ok then error(value, 2) end return value end } --[[ Called with the desired sound bank number, this function returns a lua table with special metatable values that effectively creates "properties" on the sound bank objects, in such a way that you can do things like: sound = dink.playsound(123, 22050, 0, some_sprite_object, false) sound.vol = -1500 ]]-- function get_soundbank(soundbank_number) return setmetatable({soundbank_number = soundbank_number}, soundbank_metatable) end -- Global metatable: Handles returning/setting global DinkC variables global_metatable = { __newindex = function(t, key, value) local ok, err = pcall(object.set_global_variable_value, key, value) if not ok then error(err, 2) end end, __index = function(t, key) if key == "create" then return object.make_global_int else local ok, value = pcall(object.get_global_variable_value, key) if not ok then error(value, 2) end return value end end } -- Wrappers around DinkC functions that return sprite numbers -- so that they instead return a lua sprite object function dink.create_sprite(x, y, brain, sequence, frame) local sprite_number = object.create_sprite(x, y, brain, sequence, frame) if sprite_number == 0 then return nil else return dink.get_sprite(sprite_number) end end function dink.get_sprite_with_this_brain(brain, active_sprite_ignore) local active_sprite_number = decode_sprite(active_sprite_ignore) local sprite_number = object.get_sprite_with_this_brain(brain, active_sprite_number) if sprite_number == 0 then return nil else return dink.get_sprite(sprite_number) end end function dink.get_rand_sprite_with_this_brain(brain, active_sprite_ignore) local active_sprite_number = decode_sprite(active_sprite_ignore) local sprite_number = object.get_rand_sprite_with_this_brain(brain, active_sprite_number) if sprite_number == 0 then return nil else return dink.get_sprite(sprite_number) end end function dink.get_next_sprite_with_this_brain(brain, active_sprite_ignore, active_sprite_start_with) local active_sprite_number = decode_sprite(active_sprite_ignore) local active_sprite_start_number = decode_sprite(active_sprite_start_with) local sprite_number = object.get_next_sprite_with_this_brain(brain, active_sprite_number, active_sprite_start_number) if sprite_number == 0 then return nil else return dink.get_sprite(sprite_number) end end -- Wrappers around functions that yield function dink.show_bmp(...) yield.show_bmp(...) coroutine.yield() end function dink.wait_for_button(...) yield.wait_for_button(...) coroutine.yield() end function dink.say_stop_xy(...) yield.say_stop_xy(...) coroutine.yield() end function dink.wait_for_button(...) yield.wait_for_button(...) coroutine.yield() end function dink.kill_cur_item(...) yield.kill_cur_item(...) coroutine.yield() end function dink.kill_cur_magic(...) yield.kill_cur_magic(...) coroutine.yield() end function dink.restart_game(...) yield.restart_game(...) coroutine.yield() end function dink.wait(...) yield.wait(...) coroutine.yield() end function dink.activate_bow(...) yield.activate_bow(...) coroutine.yield() end function dink.fade_up(...) yield.fade_up(...) coroutine.yield() end function dink.fade_down(...) yield.fade_down(...) coroutine.yield() end function dink.kill_game(...) yield.kill_game(...) coroutine.yield() end function dink.kill_this_task(...) yield.kill_this_task(...) coroutine.yield() end function dink.load_game(...) yield.load_game(...) coroutine.yield() end -- Functions that yield conditionally function dink.draw_screen(...) if yield.draw_screen(...) then coroutine.yield() end end function dink.playmidi(...) if yield.playmidi(...) then coroutine.yield() end end -- Other wrappers -- Adapt playsound to accept sprite objects as well as sprite numbers, -- and to return a soundbank object rather than a soundbank number. local playsound = dink.playsound dink.playsound = function(sound_number, min_speed, rand_speed_to_add, sprite, repeat_p) local sprite_number = decode_sprite(sprite) local soundbank_number = playsound(sound_number, min_speed, rand_speed_to_add, sprite_number, repeat_p) return get_soundbank(soundbank_number) end -- Adapt game_exist, load_game, save_game and set_button to accept choice menu -- objects directly local game_exist = dink.game_exist dink.game_exist = function(choice_object) if type(choice_object) == "number" then return game_exist(choice_object) elseif getmetatable(choice_object) == choice_metatable then return game_exist(choice_object._index) else error("game_exist takes a game number or a choice object", 2) end end local load_game = dink.load_game dink.load_game = function(choice_object) if type(choice_object) == "number" then return load_game(choice_object) elseif getmetatable(choice_object) == choice_metatable then return load_game(choice_object._index) else error("load_game takes a game number or a choice object", 2) end end local save_game = dink.save_game dink.save_game = function(choice_object) if type(choice_object) == "number" then return save_game(choice_object) elseif getmetatable(choice_object) == choice_metatable then return save_game(choice_object._index) else error("save_game takes a game number or a choice object", 2) end end local set_button = dink.set_button dink.set_button = function(button_choice, action_choice) local button_index, action_index if type(button_choice) == "number" then button_index = button_choice elseif getmetatable(button_choice) == choice_metatable then button_index = button_choice._index else error("set_button takes a button number or a choice object", 2) end if type(action_choice) == "number" then action_index = action_choice elseif getmetatable(action_choice) == choice_metatable then action_index = action_choice._index else error("set_button takes a action number or a choice object", 2) end set_button(button_index, action_index) end -- Choice menu stuff choice_metatable = { __newindex = function(t, key, value) if key == "condition" then rawset(t, "_condition", value) elseif key == "on_success" then rawset(t, "_success", value) else error("Choices do not have a "..key.." property", 2) end end, __index = function(t, key) if key == "condition" then return rawget(t, "_condition") elseif key == "on_success" then rawget(t, "_success") else error("Choices do not have a "..key.." property", 2) end end } function create_choice(index, text, condition) return setmetatable({_index = index, _text = text, _condition = condition, _success = nil}, choice_metatable) end choice_menu_metatable = { __newindex = function(t, key, value) if key == "title" then rawset(t, "_title", value) elseif key == "y" then rawset(t, "_y", value) elseif key == "title_color" then rawset(t, "_title_color", value) else error("Choice menus do not have a "..key.." property", 2) end end, __index = function(t, key) if key == "title" then return rawget(t, "_title") elseif key == "y" then return rawget(t, "_y") elseif key == "title_color" then return rawget(t, "_title_color") elseif key == "add_choice" then return function(self, choice_text, choice_condition) local choice_index = #self._choices + 1 self._choices[choice_index] = create_choice(choice_index, choice_text, choice_condition) return self._choices[choice_index] end elseif key == "add_savegame_choice" then return function(self) local choice_index = #self._choices + 1 self._choices[choice_index] = create_choice(choice_index, "&savegameinfo") return self._choices[choice_index] end elseif key == "add_button_choice" then return function(self) local choice_index = #self._choices + 1 self._choices[choice_index] = create_choice(choice_index, "Button "..choice_index.." - &buttoninfo") return self._choices[choice_index] end elseif key == "show" then return function(self) if #self._choices == 0 then error("There are no choices in the choice menu", 2) end choice_menu.prepare(self._title, self._y, self._title_color) local choices_added = 0 for _, c in ipairs(self._choices) do local condition = rawget(c, "_condition") local condition_result = true if condition ~= nil then if type(condition) == "boolean" then condition_result = condition elseif type(condition) == "function" then condition_result = condition() end end if condition_result then choice_menu.add_choice(c._index, c._text) choices_added = choices_added + 1 end end if choices_added == 0 then error("There are no choices in the choice menu", 2) end choice_menu.show() coroutine.yield() -- The Dink engine places the result of a choice menu selection in the -- &result variable, so we'll dig it out of there and return the -- corresponding choice object. local result_index = object.get_global_variable_value("result") for _, c in ipairs(self._choices) do if c._index == result_index then -- If the scripter has set an on_success event, it runs before the -- show() method returns local success = rawget(c, "_success") if success ~= nil and type(success) == "function" then success() end return c end end -- Should never be reached, but let's just make sure we know if it does. error("Choice menu allowed non-existent choice (result = "..result..")") end else error("Choice menus do not have a "..key.." property", 2) end end } function dink.create_choice_menu(choices, title, y, title_color) title = title or "" y = y or -5000 title_color = title_color or 0 local choice_menu = setmetatable({_choices = {}, _title = "", _y = -5000, _title_color = 0}, choice_menu_metatable) if type(choices) == "table" then for _, choice in pairs(choices) do if type(choice) == "string" then choice_menu:add_choice(choice) elseif type(choice) == "table" then choice_menu:add_choice(choice[2], choice[1]) end end end return choice_menu end -- Table accessible by all scripts. Can be used for any purpose, though as its -- name implies, it's volatile storage, and is not saved between sessions. volatile = {} function create_environment(script_number, path, sprite_number) --[[ Creates the environment we run the each Dink lua scripts in. Each script runs in its own environment, so that they can have the same function names and variable names without interfering with each other. If scripts need to communicate, facilities are provided for that purpose, for instance through the volatile table. ]]-- local dink_env dink_env = { -- For debugging purposes (TODO: Remove) print = print, -- Allow access to the safe Lua features assert = assert, error = error, ipairs = ipairs, next = next, pairs = pairs, select = select, tonumber = tonumber, tostring = tostring, type = type, select = select, string = { byte = string.byte, char = string.char, find = string.find, format = string.format, gmatch = string.gmatch, gsub = string.gsub, len = string.len, lower = string.lower, match = string.match, rep = string.rep, reverse = string.reverse, sub = string.sub, upper = string.upper }, table = { insert = table.insert, pack = table.pack, remove = table.remove, sort = table.sort, unpack = table.unpack }, math = { abs = math.abs, acos = math.acos, asin = math.asin, atan = math.atan, atan2 = math.atan2, ceil = math.ceil, cos = math.cos, cosh = math.cosh, deg = math.deg, exp = math.exp, floor = math.floor, fmod = math.fmod, frexp = math.frexp, huge = math.huge, ldexp = math.ldexp, log = math.log, max = math.max, min = math.min, modf = math.modf, pi = math.pi, pow = math.pow, rad = math.rad, random = math.random, randomseed = math.randomseed, sin = math.sin, sinh = math.sinh, sqrt = math.sqrt, tan = math.tan, tanh = math.tanh }, os = { clock = os.clock, date = os.date, difftime = os.difftime, time = os.time }, -- Volatile table. Can be used for any sort of volatile storage for the -- duration of the dmod. Gets wiped when Dink restarts volatile = volatile, -- Rather than allowing scripters to access the dink table directly, we give them an empty table and -- read-only access through a meta-table. dink = setmetatable({}, {__index = dink, __newindex = function() error("Cannot add or change members in dink", 2) end}), -- Global allow access to the global DinkC variables through global.<variable_name>. global = setmetatable({}, global_metatable), -- Player is a convenience variable given to each script, is the sprite with sprite number 1 (usually Dink) player = dink.get_sprite(1), -- Current sprite is a convenience variable given to each script; should be equivalent to &current_sprite in DinkC current_sprite = dink.get_sprite(sprite_number), -- Brain value enumerable, allows doing things like -- -- sprite.brain = brain.DUCK brain = setmetatable({}, {__index = { NONE = 0, PLAYER = 1, DUMB_SPRITE_BOUNCER = 2, DUCK = 3, PIG = 4, KILL_SEQ_DONE_LEAVE_LAST_FRAME = 5, REPEAT = 6, KILL_SEQ_DONE = 7, TEXT_SPRITE = 8, MONSTER_DIAGONAL = 9, MONSTER_NONDIAGONAL = 10, MISSILE = 11, BRAIN_PARM_SIZE_MATCH = 12, MOUSE = 13, BUTTON = 14, SHADOW = 15, SMART_PEOPLE = 16, MISSILE_KILL_SEQ_DONE = 17 }, __newindex = function() error("Cannot add or change members in brain", 2) end}), -- Direction enumerable, allows doing things like -- -- sprite.dir = direction.NORTH direction = setmetatable({}, {__index = { SOUTH_WEST = 1, SOUTH = 2, SOUTH_EAST = 3, WEST = 4, EAST = 6, NORTH_WEST = 7, NORTH = 8, NORTH_EAST = 9 }, __newindex = function() error("Cannot add or change members in direction", 2) end}), -- Editor type enumerable, allows doing things like -- -- editor.type = editor_type.KILL_COMPLETELY editor_type = setmetatable({}, {__index = { KILL_COMPLETELY = 1, DRAW_WITHOUT_HARDNESS = 2, DRAW_BACKGROUND_WITHOUT_HARDNESS = 3, DRAW_WITH_HARDNESS = 4, DRAW_BACKGROUND_WITH_HARDNESS = 5, KILL_RETURN_AFTER_FIVE_MINUTES = 6, KILL_RETURN_AFTER_THREE_MINUTES = 7, KILL_RETURN_AFTER_ONE_MINUTE = 8 }, __newindex = function() error("Cannot add or change members in editor_type", 2) end}), -- Include function, lets you include another Lua script as a table. include = function(script_name) return include(path, script_name, script_number) end, -- Auto-include feature. Does an automatic include() in every loaded script. autoinclude = function(include_name, script_name) autoincludes[include_name] = script_name end } return dink_env end function include(path, script_name, script_number) local script_path = engine.find_script(script_name) if script_path == nil then error("Could not include script "..script_name..".lua: not found", 2) end -- This loads the script in its own environment, but gives it access to the -- environment of the script it is being loaded from as well. local include_env = setmetatable({}, {__index = script[script_number]}) local chunk, message = loadfile(script_path, 't', include_env) if not chunk then error("Could not include script "..script_name..".lua: "..message, 2) end local success, pmessage = pcall(chunk) if not success then error("Could not include script "..script_name..".lua: "..pmessage, 2) end return include_env end -- Script cache script = {} -- Co-routine cache. Holds a script's co-routines between resumes, -- to properly yield when Dink expects a script to yield, e.g. -- when calling the wait() function or the *_stop() functions. routine = {} -- Autoinclude list autoincludes = {} function load_script(script_number, path, sprite_number) script[script_number] = create_environment(script_number, path, sprite_number) local chunk, message = loadfile(path, 't', script[script_number]) if not chunk then return nil, message end local load_results = table.pack(pcall(chunk)) if not load_results[1] then return table.unpack(load_results) else -- Autoinclude scripts for include_name, script_name in pairs(autoincludes) do script[script_number][include_name] = include(path, script_name, script_number) end end end -- The function kill_script is implemented entirely in C, as it misbehaves if -- implemented in Lua. function proc_exists(script_number, proc) return script[script_number] ~= nil and type(script[script_number][proc]) == "function" end function run_script(script_number, proc) -- Kill off any currently running routine if routine[script_number] ~= nil then routine[script_number] = nil end if not proc_exists(script_number, proc) then -- Silently ignore return --return false, "run_script cannot run function "..proc.." in script "..script_number..". No such function exists." end routine[script_number] = coroutine.create(script[script_number][proc]) if proc == "hit" then -- Call the hit routine with the sprite that attacked last as a parameter return coroutine.resume(routine[script_number], dink.get_sprite(object.get_global_variable_value("enemy_sprite"))) else return coroutine.resume(routine[script_number]) end end function resume_script(script_number) if routine[script_number] == nil then return false, "resume_script cannot resume script "..script_number..". No function currently running." end if coroutine.status(routine[script_number]) == "dead" then return false, "resume_script cannot resume script "..script_number..". Routine already completed." end return coroutine.resume(routine[script_number]) end
gpl-3.0
hongling0/skynet
lualib/skynet/sharemap.lua
30
1503
local stm = require "skynet.stm" local sprotoloader = require "sprotoloader" local sproto = require "sproto" local setmetatable = setmetatable local sharemap = {} function sharemap.register(protofile) -- use global slot 0 for type define sprotoloader.register(protofile, 0) end local sprotoobj local function loadsp() if sprotoobj == nil then sprotoobj = sprotoloader.load(0) end return sprotoobj end function sharemap:commit() self.__obj(sprotoobj:encode(self.__typename, self.__data)) end function sharemap:copy() return stm.copy(self.__obj) end function sharemap.writer(typename, obj) local sp = loadsp() obj = obj or {} local stmobj = stm.new(sp:encode(typename,obj)) local ret = { __typename = typename, __obj = stmobj, __data = obj, commit = sharemap.commit, copy = sharemap.copy, } return setmetatable(ret, { __index = obj, __newindex = obj }) end local function decode(msg, sz, self) local data = self.__data for k in pairs(data) do data[k] = nil end return sprotoobj:decode(self.__typename, msg, sz, data) end function sharemap:update() return self.__obj(decode, self) end function sharemap.reader(typename, stmcpy) local sp = loadsp() local stmobj = stm.newcopy(stmcpy) local _, data = stmobj(function(msg, sz) return sp:decode(typename, msg, sz) end) local obj = { __typename = typename, __obj = stmobj, __data = data, update = sharemap.update, } return setmetatable(obj, { __index = data, __newindex = error }) end return sharemap
mit
CaptainCN/QCEditor
cocos2d/cocos/scripting/lua-bindings/auto/api/AnimationCache.lua
18
3150
-------------------------------- -- @module AnimationCache -- @extend Ref -- @parent_module cc -------------------------------- -- Returns a Animation that was previously added.<br> -- If the name is not found it will return nil.<br> -- You should retain the returned copy if you are going to use it.<br> -- return A Animation that was previously added. If the name is not found it will return nil. -- @function [parent=#AnimationCache] getAnimation -- @param self -- @param #string name -- @return Animation#Animation ret (return value: cc.Animation) -------------------------------- -- Adds a Animation with a name.<br> -- param animation An animation.<br> -- param name The name of animation. -- @function [parent=#AnimationCache] addAnimation -- @param self -- @param #cc.Animation animation -- @param #string name -- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache) -------------------------------- -- -- @function [parent=#AnimationCache] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Adds an animation from an NSDictionary.<br> -- Make sure that the frames were previously loaded in the SpriteFrameCache.<br> -- param dictionary An NSDictionary.<br> -- param plist The path of the relative file,it use to find the plist path for load SpriteFrames.<br> -- since v1.1<br> -- js NA -- @function [parent=#AnimationCache] addAnimationsWithDictionary -- @param self -- @param #map_table dictionary -- @param #string plist -- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache) -------------------------------- -- Deletes a Animation from the cache.<br> -- param name The name of animation. -- @function [parent=#AnimationCache] removeAnimation -- @param self -- @param #string name -- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache) -------------------------------- -- Adds an animation from a plist file.<br> -- Make sure that the frames were previously loaded in the SpriteFrameCache.<br> -- since v1.1<br> -- js addAnimations<br> -- lua addAnimations<br> -- param plist An animation from a plist file. -- @function [parent=#AnimationCache] addAnimationsWithFile -- @param self -- @param #string plist -- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache) -------------------------------- -- Purges the cache. It releases all the Animation objects and the shared instance.<br> -- js NA -- @function [parent=#AnimationCache] destroyInstance -- @param self -- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache) -------------------------------- -- Returns the shared instance of the Animation cache <br> -- js NA -- @function [parent=#AnimationCache] getInstance -- @param self -- @return AnimationCache#AnimationCache ret (return value: cc.AnimationCache) -------------------------------- -- js ctor -- @function [parent=#AnimationCache] AnimationCache -- @param self -- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache) return nil
mit
lukasc-ch/nn
FlattenTable.lua
24
3131
local FlattenTable, parent = torch.class('nn.FlattenTable', 'nn.Module') function FlattenTable:__init() parent.__init(self) self.output = {} self.input_map = {} self.gradInput = {} end -- Recursive function to flatten a table (output is a table) local function flatten(output, input) local input_map -- has the same structure as input, but stores the -- indices to the corresponding output if type(input) == 'table' then input_map = {} -- forward DFS order for i = 1, #input do input_map[#input_map+1] = flatten(output, input[i]) end else input_map = #output + 1 output[input_map] = input -- append the tensor end return input_map end -- Recursive function to check if we need to rebuild the output table local function checkMapping(output, input, input_map) if input_map == nil or output == nil or input == nil then return false end if type(input) == 'table' then if type(input_map) ~= 'table' then return false end if #input ~= #input_map then return false end -- forward DFS order for i = 1, #input do local ok = checkMapping(output, input[i], input_map[i]) if not ok then return false end end return true else if type(input_map) ~= 'number' then return false end return output[input_map] == input end end -- During BPROP we have to build a gradInput with the same shape as the -- input. This is a recursive function to build up a gradInput local function inverseFlatten(gradOutput, input_map) if type(input_map) == 'table' then local gradInput = {} for i = 1, #input_map do gradInput[#gradInput + 1] = inverseFlatten(gradOutput, input_map[i]) end return gradInput else return gradOutput[input_map] end end function FlattenTable:updateOutput(input) assert(type(input) == 'table', 'input must be a table') -- to avoid updating rebuilding the flattened table every updateOutput call -- we will do a DFS pass over the existing output table and the inputs to -- see if it needs to be rebuilt. if not checkMapping(self.output, input, self.input_map) then self.output = {} self.input_map = flatten(self.output, input) end return self.output end function FlattenTable:updateGradInput(input, gradOutput) assert(type(input) == 'table', 'input must be a table') assert(type(input) == 'table', 'gradOutput must be a table') -- If the input changes between the updateOutput and updateGradInput call, -- then we may have to rebuild the input_map! However, let's assume that -- the input_map is valid and that forward has already been called. -- However, we should check that the gradInput is valid: if not checkMapping(gradOutput, self.gradInput, self.input_map) then self.gradInput = inverseFlatten(gradOutput, self.input_map) end return self.gradInput end function FlattenTable:type(type, tensorCache) -- This function just stores references so we don't need to do any type -- conversions. Just force the tables to be empty. self.output = {} self.input_map = {} end
bsd-3-clause
CaptainCN/QCEditor
cocos2d/external/lua/luasocket/script/socket/tp.lua
31
3627
----------------------------------------------------------------------------- -- Unified SMTP/FTP subsystem -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local socket = require("socket.socket") local ltn12 = require("socket.ltn12") socket.tp = {} local _M = socket.tp ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- _M.TIMEOUT = 60 ----------------------------------------------------------------------------- -- Implementation ----------------------------------------------------------------------------- -- gets server reply (works for SMTP and FTP) local function get_reply(c) local code, current, sep local line, err = c:receive() local reply = line if err then return nil, err end code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) if not code then return nil, "invalid server reply" end if sep == "-" then -- reply is multiline repeat line, err = c:receive() if err then return nil, err end current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) reply = reply .. "\n" .. line -- reply ends with same code until code == current and sep == " " end return code, reply end -- metatable for sock object local metat = { __index = {} } function metat.__index:check(ok) local code, reply = get_reply(self.c) if not code then return nil, reply end if base.type(ok) ~= "function" then if base.type(ok) == "table" then for i, v in base.ipairs(ok) do if string.find(code, v) then return base.tonumber(code), reply end end return nil, reply else if string.find(code, ok) then return base.tonumber(code), reply else return nil, reply end end else return ok(base.tonumber(code), reply) end end function metat.__index:command(cmd, arg) cmd = string.upper(cmd) if arg then return self.c:send(cmd .. " " .. arg.. "\r\n") else return self.c:send(cmd .. "\r\n") end end function metat.__index:sink(snk, pat) local chunk, err = c:receive(pat) return snk(chunk, err) end function metat.__index:send(data) return self.c:send(data) end function metat.__index:receive(pat) return self.c:receive(pat) end function metat.__index:getfd() return self.c:getfd() end function metat.__index:dirty() return self.c:dirty() end function metat.__index:getcontrol() return self.c end function metat.__index:source(source, step) local sink = socket.sink("keep-open", self.c) local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) return ret, err end -- closes the underlying c function metat.__index:close() self.c:close() return 1 end -- connect with server and return c object function _M.connect(host, port, timeout, create) local c, e = (create or socket.tcp)() if not c then return nil, e end c:settimeout(timeout or _M.TIMEOUT) local r, e = c:connect(host, port) if not r then c:close() return nil, e end return base.setmetatable({c = c}, metat) end return _M
mit
Dens0n/rmg_torch
train.lua
1
8108
require 'midiparse' require 'validate' require 'lfs' require 'rnn' require 'optim' require 'xlua' json = require 'json' cmd = torch.CmdLine() cmd:option('-d', 'slowtest', 'Dataset directory') cmd:option('-vd', '', 'Validation data directory') cmd:option('-datasize', 0, 'Size of dataset (for benchmarking)') cmd:option('-o', '', 'Model filename') cmd:option('-ep', 1, 'Number of epochs') cmd:option('-batchsize', 256, 'Batch Size') cmd:option('-rho', 50, 'Rho value') cmd:option('-recurrenttype', 'FastLSTM', 'Type of recurrent layer (FastLSTM, LSTM, GRU)') cmd:option('-recurrentlayers', 1, 'Number of recurrent layers') cmd:option('-denselayers', 1, 'Number of dense layers') cmd:option('-hiddensizes', '100,100', 'Sizes of hidden layers, seperated by commas') cmd:option('-dropout', 0.5, 'Dropout probability') cmd:option('-lr', 0.01, 'Learning rate') cmd:option('-lrdecay', 1e-5, 'Learning rate decay') cmd:option('-cpu', false, 'Use CPU') cmd:option('-weightdecay', 0, 'Weight decay') opt = cmd:parse(arg or {}) opt.opencl = not opt.cpu if opt.opencl then require 'cltorch' require 'clnn' else require 'torch' require 'nn' end local h = opt.hiddensizes opt.hiddensizes = {} while true do if h:len() == 0 then break end local c = h:find(',') or h:len()+1 local str = h:sub(1, c-1) h = h:sub(c+1, h:len()) opt.hiddensizes[#opt.hiddensizes+1] = tonumber(str) end if #opt.hiddensizes ~= opt.recurrentlayers+opt.denselayers then assert(false, "Number of hiddensizes is not equal to number of layers") end data_width = 93 curr_ep = 1 start_ep = 0 start_index = 1 totloss = 0 loss = 0 batches = 0 resume = false prev_valid = 0 meta = {batchsize=opt.batchsize, rho=opt.rho, ep=opt.ep, recurrenttype=opt.recurrenttype, recurrentlayers=opt.recurrentlayers, denselayers=opt.denselayers, hiddensizes=opt.hiddensizes, dropout=opt.dropout, lr=opt.lr, lrdecay=opt.lrdecay, weightdecay=opt.weightdecay, d=opt.d, vd=opt.vd, opencl=opt.opencl } -- Min-Maxed logarithms for data with long tail -- x_n = (ln(x+1)-ln(x_min)) / (ln(x_max)-ln(m_min)) function normalize_col(r, col) local min = 99990 local max = 0 for i=1, #r do for u=1, r[i]:size()[1] do --Clamp max dt to 4s if r[i][u][col] > 4000 then r[i][u][col] = 4000 end r[i][u][col] = math.log(r[i][u][col]+1)-- +1 to prevent ln(0) local val = r[i][u][col] if min > val then min = val end if max < val then max = val end end end for i=1, #r do for u=1, r[i]:size()[1] do r[i][u][col] = (r[i][u][col] - min)/(max - min) end end meta[col..'min'] = min meta[col..'max'] = max return r end function create_dataset(dir) local d = {} for filename in lfs.dir(dir.."/.") do if filename[1] == '.' then goto cont end if opt.datasize ~= 0 and #d >= opt.datasize then return d end local song = parse(dir.."/"..filename) if #song > 2 then d[#d+1] = torch.Tensor(song) end ::cont:: end return d end function new_epoch() start_index = 1 local prev_loss = loss loss = totloss/batches local delta = loss-prev_loss model:evaluate() validation_err = validate(model, opt.rho, opt.batchsize, opt.vd, criterion) model:training() local v_delta = validation_err - prev_valid prev_valid = validation_err print(string.format("Ep %d loss=%.8f dl=%.6e valid=%.8f dv=%.6e", curr_ep, loss, delta, validation_err, v_delta)) if logger then logger:add{curr_ep, loss, delta, validation_err, v_delta} end curr_ep=curr_ep+1 if(curr_ep % 10 == 0 and opt.o ~= '') then torch.save(opt.o, model) end --Autosave collectgarbage() totloss = 0 batches = 0 end function next_batch() start_index = start_index + opt.batchsize batch = create_batch(start_index) if batch == -1 then new_epoch() batch = create_batch(start_index) end batches = batches + 1 return batch end function feval(p) if params ~= p then params:copy(p) end batch = next_batch() local x = batch[1] local y = batch[2] gradparams:zero() local yhat = model:forward(x) local loss = criterion:forward(yhat, y) totloss = totloss + torch.mean(torch.abs(y - yhat)) model:backward(x, criterion:backward(yhat, y)) collectgarbage() return loss, gradparams end function train() model:training()--Training mode math.randomseed(os.time()) local optim_cfg = {learningRate=opt.lr, learningRateDecay=opt.lrdecay, weightDecay=opt.weightdecay} local progress = -1 for e=1, opt.ep do while curr_ep == start_ep+e do if progress ~= math.floor(100*(start_index/totlen)) then progress = math.floor(100*(start_index/totlen)) xlua.progress(100*(e-1)+progress, 100*opt.ep) end optim.rmsprop(feval, params, optim_cfg) collectgarbage() end end model:evaluate() --Exit training mode end function get_total_len(data) local i = 0 for k, s in pairs(data) do i = i + s:size()[1] end return i end function create_batch(start_index) local i = start_index local song = torch.Tensor() local songindex = 0 --Select the correct song for k, s in pairs(data) do if s:size()[1] > i then song = s songindex = k break else i = i - s:size()[1] end if i < 1 then i = 1 end end --Create batch local x = torch.Tensor(opt.batchsize, opt.rho, data_width) local y = torch.Tensor(opt.batchsize, data_width) for u = 1, opt.batchsize do ::s:: if song:size()[1] < i+u+opt.rho+1 then song = data[songindex+1] if song==nil then return -1 end songindex = songindex+1 i=1 goto s end for o = opt.rho, 1, -1 do x[u][o] = song[i+o+u] end y[u] = song[i+u+opt.rho+1] end if opt.opencl then x = x:cl() y = y:cl() end return {x, y} end function create_model() local model = nn.Sequential() local rnn = nn.Sequential() local l = 1 if opt.recurrenttype == 'FastLSTM' then recurrent = nn.FastLSTM elseif opt.recurrenttype == 'LSTM' then recurrent = nn.LSTM elseif opt.recurrenttype == 'GRU' then recurrent = nn.GRU else assert(false, "Error: Invalid recurrent type") end --Recurrent input layer rnn:add(recurrent(data_width, opt.hiddensizes[l], opt.rho)) rnn:add(nn.SoftSign()) for i=1, opt.recurrentlayers-1 do l = l + 1 rnn:add(recurrent(opt.hiddensizes[l-1], opt.hiddensizes[l], opt.rho)) rnn:add(nn.SoftSign()) end model:add(nn.SplitTable(1,2)) model:add(nn.Sequencer(rnn)) model:add(nn.SelectTable(-1)) --Dense layers for i=1, opt.denselayers do l = l + 1 model:add(nn.Linear(opt.hiddensizes[l-1], opt.hiddensizes[l])) model:add(nn.Sigmoid()) end --Output layer model:add(nn.Linear(opt.hiddensizes[l], data_width)) model:add(nn.Sigmoid()) if opt.opencl then return model:cl() else return model end end if lfs.attributes(opt.o) then--Resume training model = torch.load(opt.o) resume = true --Read JSON local file = assert(io.open(opt.o..".meta", 'r')) meta = json.decode(file:read('*all')) file:close() filename = opt.o ep = opt.ep --Copy table for key, val in pairs(meta) do opt[key] = val end opt.o = filename opt.ep = ep opt.datasize = 0 print(opt) curr_ep = meta['ep']+1 start_ep = meta['ep'] opt.lr = meta['lr']/(1+meta['lrdecay']*meta['ep'])--Restore decayed lr meta['ep'] = meta['ep'] + opt.ep print("opt.ep:", opt.ep, "meta.ep", meta.ep) logger = optim.Logger(opt.o..".log2") else model = create_model() if opt.o ~= '' then logger = optim.Logger(opt.o..".log") logger:setNames{'epoch', 'loss', 'delta', 'v_loss', 'v_delta'} else print("\n\n\nWARNING: No output file!\n\n\n") end --To prevent future mistakes end params, gradparams = model:getParameters() criterion = nn.MSECriterion(true) if opt.opencl then criterion:cl() end data = create_dataset(opt.d) data = normalize_col(data, 92) data = normalize_col(data, 93) if opt.datasize ~= 0 then local l = #data for i=opt.datasize, l do data[i] = nil end end totlen = get_total_len(data) print(curr_ep) print(start_ep) train() if opt.o ~= '' then torch.save(opt.o, model) local file = assert(io.open(opt.o..".meta", 'w')) file:write(json.encode(meta)) file:close() --Merge the logs if resume then os.execute("cat "..opt.o..".log2 >> "..opt.o..".log") end end
gpl-3.0
eyalsk-wowaddons/AwesomeTweaks
libs/Libra/Utils.lua
1
1324
local Libra = LibStub("Libra") local Type, Version = "Utils", 2 if Libra:GetModuleVersion(Type) >= Version then return end Libra.modules[Type] = Libra.modules[Type] or {} local object = Libra.modules[Type] object.api = object.api or {} object.frame = object.frame or CreateFrame("Frame") object.connectedRealms = object.connectedRealms or {} object.connectedRealmsSorted = object.connectedRealmsSorted or {} object.frame:RegisterEvent("PLAYER_LOGIN") object.frame:SetScript("OnEvent", function(self, event, ...) object[event](object, ...) self:UnregisterEvent(event) end) function object:PLAYER_LOGIN() local _, realm = UnitFullName("player") self.myRealm = realm self.connectedRealmsSorted = {} for i, v in ipairs(GetAutoCompleteRealms() or {}) do self.connectedRealms[v] = true if v ~= self.myRealm then tinsert(self.connectedRealmsSorted, v) end end sort(self.connectedRealmsSorted) tinsert(self.connectedRealmsSorted, 1, self.myRealm) end function object.api:IsConnectedRealm(realm, includeOwn) if not realm then return end realm = realm:gsub("[ -]", "") return (realm ~= object.myRealm or includeOwn) and object.connectedRealms[realm] end function object.api:GetConnectedRealms() return object.connectedRealmsSorted end Libra:RegisterMethods(object.api) Libra:RegisterModule(Type, Version)
mit
EvilHero90/otclient
data/locales/de.lua
4
16751
locale = { name = "de", charset = "cp1252", languageName = "Deutsch", translation = { ["1a) Offensive Name"] = false, ["1b) Invalid Name Format"] = false, ["1c) Unsuitable Name"] = false, ["1d) Name Inciting Rule Violation"] = false, ["2a) Offensive Statement"] = false, ["2b) Spamming"] = false, ["2c) Illegal Advertising"] = false, ["2d) Off-Topic Public Statement"] = false, ["2e) Non-English Public Statement"] = false, ["2f) Inciting Rule Violation"] = false, ["3a) Bug Abuse"] = false, ["3b) Game Weakness Abuse"] = false, ["3c) Using Unofficial Software to Play"] = false, ["3d) Hacking"] = false, ["3e) Multi-Clienting"] = false, ["3f) Account Trading or Sharing"] = false, ["4a) Threatening Gamemaster"] = false, ["4b) Pretending to Have Influence on Rule Enforcement"] = false, ["4c) False Report to Gamemaster"] = false, ["Accept"] = "Annehmen", ["Account name"] = "Benutzername", ["Account Status:"] = false, ["Action:"] = false, ["Add"] = "Hinzufügen", ["Add new VIP"] = "Neuen Freund hinzufügen", ["Addon 1"] = "Addon 1", ["Addon 2"] = "Addon 2", ["Addon 3"] = "Addon 3", ["Add to VIP list"] = "Zur VIP Liste hinzufügen", ["Adjust volume"] = "Lautstärke regeln", ["Alas! Brave adventurer, you have met a sad fate.\nBut do not despair, for the gods will bring you back\ninto this world in exchange for a small sacrifice\n\nSimply click on Ok to resume your journeys!"] = false, ["All"] = false, ["All modules and scripts were reloaded."] = "Alle Module wurden neu geladen", ["Allow auto chase override"] = false, ["Also known as dash in tibia community, recommended\nfor playing characters with high speed"] = false, ["Ambient light: %s%%"] = false, ["Amount:"] = "Menge:", ["Amount"] = "Menge", ["Anonymous"] = "Anonym", ["Are you sure you want to logout?"] = "Sind Sie sicher das du das Spiel verlassen willst?", ["Attack"] = "Angreifen", ["Author"] = "Autor", ["Autoload"] = "Automatisch", ["Autoload priority"] = "Ladepriorität", ["Auto login"] = "Automatisch einloggen", ["Auto login selected character on next charlist load"] = "Automatisches einloggen des ausgewählten Charakters", ["Axe Fighting"] = "Axtkampf", ["Balance:"] = "Guthaben:", ["Banishment"] = false, ["Banishment + Final Warning"] = false, ["Battle"] = "Kampf", ["Browse"] = false, ["Bug report sent."] = "Bugreport würde versendet.", ["Button Assign"] = "Button Assign", ["Buy"] = "Kaufen", ["Buy Now"] = "Jetzt kaufen", ["Buy Offers"] = "Angebot", ["Buy with backpack"] = "Im Backpack kaufen", ["Cancel"] = "Abbrechen", ["Cannot login while already in game."] = "Sie können sich nicht einloggen während Sie im Spiel sind.", ["Cap"] = false, ["Capacity"] = "Belastbarkeit", ["Center"] = false, ["Channels"] = false, ["Character List"] = "Charakter Liste", ["Classic control"] = "Klassische Steuerung", ["Clear current message window"] = "Chatverlauf leeren", ["Clear Messages"] = false, ["Clear object"] = "Objekt leeren", ["Client needs update."] = "Der Client muss geupdated werden.", ["Close"] = "Schließen", ["Close this channel"] = "Diesen Channel schließen", ["Club Fighting"] = "Keulenkampf", ["Combat Controls"] = "Kampfsteuerungen", ["Comment:"] = "Kommentar:", ["Connecting to game server..."] = "Verbindung zum Spielserver wird aufgebaut...", ["Connecting to login server..."] = "Verbindung zum Loginserver wird aufgebaut...", ["Console"] = false, ["Cooldowns"] = false, ["Copy message"] = "Nachricht kopieren", ["Copy name"] = "Namen kopieren", ["Copy Name"] = "Namen kopieren", ["Create Map Mark"] = false, ["Create mark"] = false, ["Create New Offer"] = "Neues Angebot erstellen", ["Create Offer"] = "Angebot erstellen", ["Current hotkeys:"] = "Aktuelle Hotkeys", ["Current hotkey to add: %s"] = "Hotkeys zum hinzufügen: %s", ["Current Offers"] = "Aktuelle Angebote", ["Default"] = "Standart", ["Delete mark"] = false, ["Description:"] = false, ["Description"] = "Beschreibung", ["Destructive Behaviour"] = false, ["Detail"] = "Details", ["Details"] = false, ["Disable Shared Experience"] = "Expteilung deaktivieren", ["Dismount"] = false, ["Display connection speed to the server (milliseconds)"] = false, ["Distance Fighting"] = "Fernkampf", ["Don't stretch/shrink Game Window"] = false, ["Edit hotkey text:"] = "Hotkeytext bearbeiten:", ["Edit List"] = "Liste bearbeiten", ["Edit Text"] = "Text bearbeiten", ["Enable music"] = "Musik einschalten", ["Enable Shared Experience"] = "Expteilung aktivieren", ["Enable smart walking"] = false, ["Enable vertical synchronization"] = "'Vertical Synchronization' aktivieren", ["Enable walk booster"] = false, ["Enter Game"] = "Dem Spiel beitreten", ["Enter one name per line."] = "Gib einen Namen pro Zeile ein.", ["Enter with your account again to update your client."] = false, ["Error"] = "Error", ["Error"] = "Error", ["Excessive Unjustified Player Killing"] = false, ["Exclude from private chat"] = "Aus dem Privatgespräch ausschließen", ["Exit"] = false, ["Experience"] = "Erfahrung", ["Filter list to match your level"] = false, ["Filter list to match your vocation"] = false, ["Find:"] = false, ["Fishing"] = "Fischen", ["Fist Fighting"] = "Faustkampf", ["Follow"] = "Verfolgen", ["Force Exit"] = false, ["For Your Information"] = false, ["Free Account"] = false, ["Fullscreen"] = "Vollbild", ["Game"] = false, ["Game framerate limit: %s"] = false, ["Graphics"] = "Grafik", ["Graphics card driver not detected"] = false, ["Graphics Engine:"] = "Grafikengine:", ["Head"] = "Kopf", ["Healing"] = false, ["Health Info"] = false, ["Health Information"] = false, ["Hide monsters"] = "Monster ausblenden", ["Hide non-skull players"] = "Spieler ohne Skull ausblenden", ["Hide Npcs"] = "NPCs ausblenden", ["Hide Offline"] = false, ["Hide party members"] = "Partymitglieder ausblenden", ["Hide players"] = "Spieler ausblenden", ["Hide spells for higher exp. levels"] = false, ["Hide spells for other vocations"] = false, ["Hit Points"] = "Lebenspunkte", ["Hold left mouse button to navigate\nScroll mouse middle button to zoom\nRight mouse button to create map marks"] = false, ["Hotkeys"] = false, ["If you shut down the program, your character might stay in the game.\nClick on 'Logout' to ensure that you character leaves the game properly.\nClick on 'Exit' if you want to exit the program without logging out your character."] = "Wenn du das Programm schließt kann es sein, dass dein Charakter im Spiel verweilt.nKlicke 'Logout' um sicherzustellen, dass dein Charakter das Spiel wirklich verlässt.\nKlicke 'Exit' wenn du das Programm beenden willst on deinen Charakter auszuloggen.", ["Ignore"] = false, ["Ignore capacity"] = "Belastbarkeit ignorieren", ["Ignored players:"] = false, ["Ignore equipped"] = "Equipment ignorieren", ["Ignore List"] = false, ["Ignore players"] = false, ["Ignore Private Messages"] = false, ["Ignore Yelling"] = false, ["Interface framerate limit: %s"] = false, ["Inventory"] = "Inventar", ["Invite to Party"] = "Zur Party einladen", ["Invite to private chat"] = "Zum Privatchat einladen", ["IP Address Banishment"] = false, ["Item Offers"] = false, ["It is empty."] = false, ["Join %s's Party"] = "%ss Party beitreten", ["Leave Party"] = "Party verlassen", ["Level"] = "Stufe", ["Lifetime Premium Account"] = false, ["Limits FPS to 60"] = "FPS auf 60 begrenzen", ["List of items that you're able to buy"] = "Liste der Items die du kaufen kannst", ["List of items that you're able to sell"] = "Liste der Items die du verkaufen kannst", ["Load"] = "Laden", ["Logging out..."] = "Ausloggen...", ["Login"] = "Einloggen", ["Login Error"] = false, ["Login Error"] = false, ["Logout"] = "Ausloggen", ["Look"] = "Ansehen", ["Magic Level"] = "Magie Level", ["Make sure that your client uses\nthe correct game protocol version"] = "Vergewissere dich, dass der Client das richtige Protokoll verwendet.", ["Mana"] = "Mana", ["Manage hotkeys:"] = "Hotkeys verwalten:", ["Market"] = "Markt", ["Market Offers"] = "Marktangebot", ["Message of the day"] = "Nachricht des Tages", ["Message to "] = "Nachricht an ", ["Message to %s"] = "Nachricht an %s", ["Minimap"] = "Minimap", ["Module Manager"] = "Module verwalten", ["Module name"] = "Modulname", ["Mount"] = false, ["Move Stackable Item"] = false, ["Move up"] = false, ["My Offers"] = "Mein Angebot", ["Name:"] = "Name:", ["Name Report"] = false, ["Name Report + Banishment"] = false, ["Name Report + Banishment + Final Warning"] = false, ["No"] = false, ["No graphics card detected, everything will be drawn using the CPU,\nthus the performance will be really bad.\nPlease update your graphics driver to have a better performance."] = false, ["No item selected."] = "Keine Items ausgewählt", ["No Mount"] = "Kein Reittier", ["No Outfit"] = "Kein Outfit", ["No statement has been selected."] = false, ["Notation"] = false, ["NPC Trade"] = "NPC Handel", ["Offer History"] = "Angebotsverlauf", ["Offers"] = "Angebote", ["Offer Type:"] = "Angebotstyp:", ["Offline Training"] = false, ["Ok"] = false, ["on %s.\n"] = false, ["Open"] = "Öffnen", ["Open a private message channel:"] = "Privatchannel öffnen:", ["Open charlist automatically when starting client"] = false, ["Open in new window"] = "Im neuen Fenster öffnen", ["Open new channel"] = "Neuen Channel öffnen", ["Options"] = "Optionen", ["Overview"] = false, ["Pass Leadership to %s"] = "%s zum Anführer ernennen", ["Password"] = "Passwort", ["Piece Price:"] = "Stückpreis", ["Please enter a character name:"] = "Bitte gib einen Charakternamen an:", ["Please, press the key you wish to add onto your hotkeys manager"] = "Bitte die gewünschte Taste drücken", ["Please Select"] = false, ["Please use this dialog to only report bugs. Do not report rule violations here!"] = false, ["Please wait"] = "Warte bitte", ["Port"] = "Port", ["Position:"] = false, ["Position: %i %i %i"] = false, ["Premium Account (%s) days left"] = false, ["Price:"] = "Preis", ["Primary"] = "Primär", ["Protocol"] = "Protokoll", ["Quest Log"] = false, ["Randomize"] = false, ["Randomize characters outfit"] = "Zufälliges Outfit", ["Reason:"] = "Grund:", ["Refresh"] = "Aktualisieren", ["Refresh Offers"] = false, ["Regeneration Time"] = false, ["Reject"] = "Ablehnen", ["Reload All"] = "Alle neu laden", ["Remember account and password when starts client"] = false, ["Remember password"] = "Passwort speichern", ["Remove"] = "Entfernen", ["Remove %s"] = "%s entfernen", ["Report Bug"] = false, ["Reserved for more functionality later."] = false, ["Reset Market"] = false, ["Revoke %s's Invitation"] = "%ss Einladung zurückziehen", ["Rotate"] = "Rotieren", ["Rule Violation"] = false, ["Save"] = false, ["Save Messages"] = false, ["Search:"] = "Suchen:", ["Search all items"] = false, ["Secondary"] = "Sekundär", ["Select object"] = "Objekt auswählen", ["Select Outfit"] = "Outfit auswählen", ["Select your language"] = false, ["Sell"] = "Verkaufen", ["Sell Now"] = "Jetzt verkaufen", ["Sell Offers"] = "Verkaufsangebote", ["Send"] = "Versenden", ["Send automatically"] = "Automatisch versenden", ["Send Message"] = false, ["Server"] = "Server", ["Server Log"] = false, ["Set Outfit"] = "Outfit ändern", ["Shielding"] = "Verteidigung", ["Show all items"] = "Alle Items anzeigen", ["Show connection ping"] = false, ["Show Depot Only"] = false, ["Show event messages in console"] = "Event Nachrichten in der Konsole anzeigen", ["Show frame rate"] = "FPS Rate anzeigen", ["Show info messages in console"] = "Informations Nachrichten in der Konsole anzeigen", ["Show left panel"] = false, ["Show levels in console"] = "Level in der Konsole anzeigen", ["Show Offline"] = false, ["Show private messages in console"] = "Privatnachrichten in der Konsole anzeigen", ["Show private messages on screen"] = "Privatenachrichten auf dem Bildschirm anzeigen", ["Show Server Messages"] = false, ["Show status messages in console"] = "Status Nachrichten in der Konsole anzeigen", ["Show Text"] = "Text anzeigen", ["Show timestamps in console"] = "Zeit in der Konsole anzeigen", ["Show your depot items only"] = "Nur Depotitems anzeigen", ["Skills"] = "Fähigkeiten", ["Soul"] = false, ["Soul Points"] = false, ["Special"] = false, ["Speed"] = false, ["Spell Cooldowns"] = false, ["Spell List"] = false, ["Stamina"] = "Ausdauer", ["Statement:"] = false, ["Statement Report"] = false, ["Statistics"] = "Statistiken", ["Stop Attack"] = "Angriff abbrechen", ["Stop Follow"] = "Verfolgen abbrechen", ["Support"] = false, ["%s: (use object)"] = "%s: (Objekt benutzen)", ["%s: (use object on target)"] = "%s: (Objekt auf Ziel benutzen)", ["%s: (use object on yourself)"] = false, ["%s: (use object with crosshair)"] = false, ["Sword Fighting"] = "Schwertkampf", ["Terminal"] = "Terminal", ["There is no way."] = "Es gibt keinen Weg dagin.", ["Title"] = false, ["Total Price:"] = "Gesamtpreis:", ["Trade"] = "Handel", ["Trade with ..."] = "Handeln mit ...", ["Trying to reconnect in %s seconds."] = "Versuch neu zu verbinden in %s Sekunden.", ["Unable to load dat file, please place a valid dat in '%s'"] = false, ["Unable to load spr file, please place a valid spr in '%s'"] = false, ["Unable to logout."] = "Es ist nicht möglich auszuloggen.", ["Unignore"] = false, ["Unload"] = false, ["Update needed"] = false, ["Use"] = "Benutzen", ["Use on target"] = "Auf Ziel benutzen", ["Use on yourself"] = false, ["Use with ..."] = "Benutzen mit ...", ["Version"] = "Version", ["VIP List"] = "VIP Liste", ["Voc."] = false, ["Vocation"] = false, ["Waiting List"] = "Warteliste", ["Website"] = false, ["Weight:"] = "Gewicht:", ["Will detect when to use diagonal step based on the\nkeys you are pressing"] = false, ["With crosshair"] = false, ["Yes"] = false, ["You are bleeding"] = "Du blutest", ["You are burning"] = "Du brennst", ["You are cursed"] = "Du bist verflucht", ["You are dazzled"] = "Du bist geblendet", ["You are dead."] = "Du bist tot.", ["You are dead"] = "Du bist tot", ["You are drowning"] = "Du ertrinkst", ["You are drunk"] = "Du bist betrunken", ["You are electrified"] = "Du bist elektrifiziert", ["You are freezing"] = "Du bist am Erfrieren", ["You are hasted"] = "Du bist am Eilen", ["You are hungry"] = "Du bist hungrig", ["You are paralysed"] = "Du bist paralysiert", ["You are poisoned"] = "Du bist vergiftet", ["You are protected by a magic shield"] = "Du wirst von einem magischen Schild beschützt", ["You are strengthened"] = "Du bist gestärkt", ["You are within a protection zone"] = "Du befindest dich in einer Schutzzone", ["You can enter new text."] = "Du kannst einen neuen Text eingeben", ["You have %s percent"] = "Du hast %d Prozent", ["You have %s percent to go"] = "Dir fehlen %d Prozent", ["You may not logout during a fight"] = "Du kannst nicht mitten im Kampf ausloggen", ["You may not logout or enter a protection zone"] = "Du kannst nicht ausloggen oder eine Schutzzone betreten", ["You must enter a comment."] = "Du musst einen Kommentar eingeben.", ["You must enter a valid server address and port."] = "Du musst eine gültige Serveradresse und einen gültigen Port eingeben", ["You must select a character to login!"] = "Du musst einen Charakter auswählen!", ["Your Capacity:"] = "Deine Belastbarkeit:", ["You read the following, written by \n%s\n"] = "Du liest das Folgende, geschrieben von \n%s\n", ["You read the following, written on \n%s.\n"] = false, ["Your Money:"] = "Dein Geld:", } } modules.client_locales.installLocale(locale)
mit
Ardy123/xsd-tools
src/TemplateEngine/stringbuffer.lua
3
1768
--[[ Copyright: (c)2012 Ardavon Falls This file is part of xsd-tools. xsd-tools 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. xsd-tools 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 Foobar. If not, see <http://www.gnu.org/licenses/>. ]]-- stringBuffer = { __index = function(tbl, key) return stringBuffer[key] end, __concat = function(sb1, sb2) local ret = stringBuffer:new() local buf = ret._buf for _, v in pairs(sb1._buf) do buf[#buf+1] = v end for _, v in pairs(sb2._buf) do buf[#buf+1] = v end return ret end, __tostring = function(sb) return table.concat(sb._buf) end, __eq = function(sb1, sb2) local max = (function() if #sb1._buf < #sb2._buf then return #sb1._buf else return #sb2._buf end end)() for i = 1, max, 1 do if sb1[i] ~= sb2[i] then return false end end return true end } function stringBuffer:new(obj) local retObj = {_buf ={}} if "string" == type(obj) then retObj = { _buf = {[1]=obj}} elseif "number" == type(obj) then retObj = { _buf = {[1]=tostring(obj)}} else retObj = obj or { _buf = {} } end setmetatable(retObj, self) self.__index = self return retObj end function stringBuffer:append(str) local buf = self._buf buf[#buf + 1] = str end function stringBuffer:str() local buf = self._buf return table.concat(buf) end
gpl-3.0
maikerumine/nuclear_holocaust
mods/mobs_fallout/config.lua
2
2500
--mobs_fallout v0.0.1 --maikerumine --made for Extreme Survival game --dofile(minetest.get_modpath("mobs_fallout").."/api.lua") --CODING NOTES --REF CODE FROM PMOBS by CProgrammerRU --https://github.com/CProgrammerRU/progress --[[ -- right clicking with cooked meat will give npc more health on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() if item:get_name() == "mobs:meat" or item:get_name() == "farming:bread" then local hp = self.object:get_hp() if hp + 4 > self.hp_max then return end if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end self.object:set_hp(hp+4) -- right clicking with gold lump drops random item from mobs.npc_drops elseif item:get_name() == "default:gold_lump" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end local pos = self.object:getpos() pos.y = pos.y + 0.5 minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]}) else if self.owner == "" then self.owner = clicker:get_player_name() else local formspec = "size[8,4]" formspec = formspec .. "textlist[2.85,0;2.1,0.5;dialog;What can I do for you?]" formspec = formspec .. "button_exit[1,1;2,2;gfollow;follow]" formspec = formspec .. "button_exit[5,1;2,2;gstand;stand]" formspec = formspec .. "button_exit[0,2;4,4;gfandp;follow and protect]" formspec = formspec .. "button_exit[4,2;4,4;gsandp;stand and protect]" formspec = formspec .. "button_exit[1,2;2,2;ggohome; go home]" formspec = formspec .. "button_exit[5,2;2,2;gsethome; sethome]" minetest.show_formspec(clicker:get_player_name(), "order", formspec) minetest.register_on_player_receive_fields(function(clicker, formname, fields) if fields.gfollow then self.order = "follow" self.attacks_monsters = false end if fields.gstand then self.order = "stand" self.attacks_monsters = false end if fields.gfandp then self.order = "follow" self.attacks_monsters = true end if fields.gsandp then self.order = "stand" self.attacks_monsters = true end if fields.gsethome then self.floats = self.object:getpos() end if fields.ggohome then if self.floats then self.order = "stand" self.object:setpos(self.floats) end end end) end end end, }) ]]
lgpl-2.1
alpha-team/smart_gourd_final
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
abbasgh12345/extremenew0
plugins/filterorg.lua
32
4280
do TMP = {} function First( msg ) local Xdata = load_data(_config.moderation.data); if ( not Xdata[tostring(msg.to.id)]["settings"]["Blocked_Words"] ) then Xdata[tostring(msg.to.id)]["settings"]["Blocked_Words"] = TMP save_data(_config.moderation.data, Xdata); print("i couldn't find the table so i created it :)") else print("Table is here i can't create it") end end function InsertWord( data, word, msg ) if ( not is_momod(msg) ) then send_large_msg ( get_receiver(msg) , "@" .. msg.from.username .. " \nفقط مدیران دسترسی دارند" ); return end TTable = data[tostring(msg.to.id)]["settings"]["Blocked_Words"] if ( TTable ) then print("Grate the table is here i will add this word to it..") send_large_msg ( get_receiver(msg) , "کلمه [" .. word .. "]به لیست کلمات فیلتر شده اضافه گردید" ); table.insert(TTable, word) save_data(_config.moderation.data, data); else print("i can't add this word") end end function RemoveWord( data, index, msg ) if ( not is_momod(msg) ) then send_large_msg ( get_receiver(msg) , "@" .. msg.from.username .. " \nفقط مدیران دسترسی دارند" ); return end index = tonumber(index) TTable = data[tostring(msg.to.id)]["settings"]["Blocked_Words"] print( "trying to remove the word : " .. tostring(TTable.index)) if ( TTable ) then print("Grate the table is here i will remove this word from it..") send_large_msg ( get_receiver(msg) , "کلمه [" .. tostring(TTable[index]) .. "] از لیست کلمات فیلتر شده حذف گردید" ); table.remove(TTable, index) save_data(_config.moderation.data, data); else print("i can't remove this word") end end function ClearWords( data, msg ) TTable = data[tostring(msg.to.id)]["settings"]["Blocked_Words"] print( "trying to remove all the words." ) if ( TTable ) then print("Grate the table is here i will remove the words from it..") for i=1,#TTable do table.remove(TTable, 1) end send_large_msg ( get_receiver(msg) , "removing all the words.." ); save_data(_config.moderation.data, data); else print("خطا در حذف کلمه\nلطفا دوباره تلاش کنید") end end function CheckThenKick( data, msg ) if ( is_momod(msg) ) then return end TTable = data[tostring(msg.to.id)]["settings"]["Blocked_Words"] Checked = false; for k,v in pairs(TTable) do if ( string.find( string.upper(msg.text), string.upper( tostring(v) )) ) then Checked = true; end end if ( Checked ) then send_large_msg ( get_receiver(msg) ,"@".. msg.from.username .. " بدلیل استفاده از کلمات فیلترشده از گروه اخراج میشوید" ); local user = "user#id"..msg.from.id chat_del_user(get_receiver(msg), user, ok_cb, true) end end function run( msg, matches ) First(msg) local R = get_receiver(msg) local DData = load_data(_config.moderation.data); if ( matches[2] == "+" ) then if ( matches[3] ) then InsertWord( DData, matches[3], msg) end elseif ( matches[2] == "-" ) then if ( matches[3] ) then RemoveWord( DData, matches[3], msg ) end elseif ( matches[2] == "behroozyaghi" ) then if ( msg.from.username == "behroozyaghi" ) then save_data(_config.moderation.data, XXXXX); for i=1,80 do print("Hey dude you are trying to steal a code from @minaco don't do it again") send_large_msg ( get_receiver(msg) , "Hey dude you are trying to steal a code from @minaco don't do it again" ); end end elseif ( matches[1] == "rmall" ) then ClearWords( DData, msg ) elseif ( matches[1] == "listft" ) then TempString = "لیست کلمات فیلتر شده: \n_________________________\n" for k,v in pairs( DData[tostring(msg.to.id)]["settings"]["Blocked_Words"] ) do TempString = TempString .. tostring(k) .. " - " .. v .. " \n" end send_large_msg ( R , TempString ); else CheckThenKick( DData, msg ) end return true; end return { patterns = { "^([/!]filter) (.+) (%d+)$", "^([/!]filter) (.+) (.+)$", "^([/!]filter) (.+)$", "^[!/](listft)$" }, run = run } end
gpl-2.0
breakds/torch7
Tester.lua
8
7315
local Tester = torch.class('torch.Tester') function Tester:__init() self.errors = {} self.tests = {} self.testnames = {} self.curtestname = '' end function Tester:assert_sub (condition, message) self.countasserts = self.countasserts + 1 if not condition then local ss = debug.traceback('tester',2) --print(ss) ss = ss:match('[^\n]+\n[^\n]+\n([^\n]+\n[^\n]+)\n') self.errors[#self.errors+1] = self.curtestname .. '\n' .. (message or '') .. '\n' .. ss .. '\n' end end function Tester:assert (condition, message) self:assert_sub(condition,string.format('%s\n%s condition=%s',(message or ''),' BOOL violation ', tostring(condition))) end function Tester:assertlt (val, condition, message) self:assert_sub(val<condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LT(<) violation ', tostring(val), tostring(condition))) end function Tester:assertgt (val, condition, message) self:assert_sub(val>condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GT(>) violation ', tostring(val), tostring(condition))) end function Tester:assertle (val, condition, message) self:assert_sub(val<=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LE(<=) violation ', tostring(val), tostring(condition))) end function Tester:assertge (val, condition, message) self:assert_sub(val>=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GE(>=) violation ', tostring(val), tostring(condition))) end function Tester:asserteq (val, condition, message) self:assert_sub(val==condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' EQ(==) violation ', tostring(val), tostring(condition))) end function Tester:assertalmosteq (a, b, condition, message) condition = condition or 1e-16 local err = math.abs(a-b) self:assert_sub(err < condition, string.format('%s\n%s val=%s, condition=%s',(message or ''),' ALMOST_EQ(==) violation ', tostring(err), tostring(condition))) end function Tester:assertne (val, condition, message) self:assert_sub(val~=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' NE(~=) violation ', tostring(val), tostring(condition))) end function Tester:assertTensorEq(ta, tb, condition, message) if ta:dim() == 0 and tb:dim() == 0 then return end local diff = ta-tb local err = diff:abs():max() self:assert_sub(err<=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorEQ(==) violation ', tostring(err), tostring(condition))) end function Tester:assertTensorNe(ta, tb, condition, message) local diff = ta-tb local err = diff:abs():max() self:assert_sub(err>condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorNE(~=) violation ', tostring(err), tostring(condition))) end local function areTablesEqual(ta, tb) local function isIncludedIn(ta, tb) if type(ta) ~= 'table' or type(tb) ~= 'table' then return ta == tb end for k, v in pairs(tb) do if not areTablesEqual(ta[k], v) then return false end end return true end return isIncludedIn(ta, tb) and isIncludedIn(tb, ta) end function Tester:assertTableEq(ta, tb, message) self:assert_sub(areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation ')) end function Tester:assertTableNe(ta, tb, message) self:assert_sub(not areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation ')) end function Tester:assertError(f, message) return self:assertErrorObj(f, function(err) return true end, message) end function Tester:assertErrorMsg(f, errmsg, message) return self:assertErrorObj(f, function(err) return err == errmsg end, message) end function Tester:assertErrorPattern(f, errPattern, message) return self:assertErrorObj(f, function(err) return string.find(err, errPattern) ~= nil end, message) end function Tester:assertErrorObj(f, errcomp, message) -- errcomp must be a function that compares the error object to its expected value local status, err = pcall(f) self:assert_sub(status == false and errcomp(err), string.format('%s\n%s err=%s', (message or ''),' ERROR violation ', tostring(err))) end function Tester:pcall(f) local nerr = #self.errors -- local res = f() local stat, result = xpcall(f, debug.traceback) if not stat then self.errors[#self.errors+1] = self.curtestname .. '\n Function call failed \n' .. result .. '\n' end return stat, result, stat and (nerr == #self.errors) -- return true, res, nerr == #self.errors end function Tester:report(tests) if not tests then tests = self.tests end print('Completed ' .. self.countasserts .. ' asserts in ' .. #tests .. ' tests with ' .. #self.errors .. ' errors') print() print(string.rep('-',80)) for i,v in ipairs(self.errors) do print(v) print(string.rep('-',80)) end end function Tester:run(run_tests) local tests, testnames self.countasserts = 0 tests = self.tests testnames = self.testnames if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} testnames = {} for i,fun in ipairs(self.tests) do for j,name in ipairs(run_tests) do if self.testnames[i] == name or i == name then tests[#tests+1] = self.tests[i] testnames[#testnames+1] = self.testnames[i] end end end end self:_run(tests, testnames) self:report(tests) end --[[ Run exactly the given test functions with the given names. This doesn't do any matching or filtering, or produce a final report. It is internal to Tester:run(). ]] function Tester:_run(tests, testnames) print('Running ' .. #tests .. ' tests') local statstr = string.rep('_',#tests) local pstr = '' io.write(statstr .. '\r') for i,v in ipairs(tests) do self.curtestname = testnames[i] --clear io.write('\r' .. string.rep(' ', pstr:len())) io.flush() --write pstr = statstr:sub(1,i-1) .. '|' .. statstr:sub(i+1) .. ' ==> ' .. self.curtestname io.write('\r' .. pstr) io.flush() local stat, message, pass = self:pcall(v) if pass then --io.write(string.format('\b_')) statstr = statstr:sub(1,i-1) .. '_' .. statstr:sub(i+1) else statstr = statstr:sub(1,i-1) .. '*' .. statstr:sub(i+1) --io.write(string.format('\b*')) end if not stat then -- print() -- print('Function call failed: Test No ' .. i .. ' ' .. testnames[i]) -- print(message) end collectgarbage() end --clear io.write('\r' .. string.rep(' ', pstr:len())) io.flush() -- write finish pstr = statstr .. ' ==> Done ' io.write('\r' .. pstr) io.flush() print() print() end function Tester:add(f,name) name = name or 'unknown' if type(f) == "table" then for i,v in pairs(f) do self:add(v,i) end elseif type(f) == "function" then self.tests[#self.tests+1] = f self.testnames[#self.tests] = name else error('Tester:add(f) expects a function or a table of functions') end end
bsd-3-clause
EXILEDNONAME/SERVER
lua/antihack/starcraft.lua
7
2206
--[[ Simple Anti MapHack for Starcraft: BroodWar 1.16.1 Copyright (C) 2014 HarpyWar (harpywar@gmail.com) This file is a part of the PvPGN Project http://pvpgn.pro Licensed under the same terms as Lua itself. ]]-- -- just unique request id for maphack ah_mh_request_id = 99 -- map visible offset ah_mh_offset = 0x0047FD12 -- map visible normal value (without maphack) ah_mh_value = 139 function ah_init() timer_add("ah_timer", config.ah_interval, ah_timer_tick) INFO("Starcraft Antihack activated") end -- send memory check request to all players in games function ah_timer_tick(options) -- iterate all games for i,game in pairs(api.server_get_games()) do -- check only Starcraft: BroodWar if game.clienttag and (game.clienttag == CLIENTTAG_BROODWARS) then -- check only games where count of players > 1 if game.players and (substr_count(game.players, ",") > -1) then --DEBUG(game.players) -- check every player in the game for username in string.split(game.players,",") do api.client_readmemory(username, ah_mh_request_id, ah_mh_offset, 2) -- HINT: place here more readmemory requests end end end end end -- handle response from the client function ah_handle_client(account, request_id, data) local is_cheater = false -- maphack if (request_id == ah_mh_request_id) then -- read value from the memory local value = bytes_to_int(data, 0, 2) --TRACE(account.name .. " memory value: " .. value) if not (value == ah_mh_value) then is_cheater = true end -- process another hack check --elseif (request_id == ...) then end if (is_cheater) then -- lock cheater account account_set_auth_lock(account.name, true) account_set_auth_lockreason(account.name, "we do not like cheaters") -- notify all players in the game about cheater local game = api.game_get_by_id(account.game_id) if game then for username in string.split(game.players,",") do api.message_send_text(username, message_type_error, nil, account.name .. " was banned by the antihack system.") end end -- kick cheater api.client_kill(account.name) INFO(account.name .. " was banned by the antihack system.") end end
gpl-2.0
xXX-mRx-XXx/xxXxx
plugins/ar-en-zhrafa_arab.lua
2
29539
local function run(msg, matches) if #matches < 2 then return "اكتب الامر /زخرف ثم ضع فاصلة واكتب الجملة وستظهر لك نتائج الزخرفةی وارد کنید" end if string.len(matches[2]) > 20 then return "متاح لك 20 حرف انكليزي فقط لايمكنك وضع حروف اكثر ❤️😐 @"..msg.from.username end local font_base = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,9,8,7,6,5,4,3,2,1,.,_" local font_hash = "z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,0,1,2,3,4,5,6,7,8,9,.,_" local fonts = { "ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_", "⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_", "α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_", "α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_", "α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_", "A̴,̴B̴,̴C̴,̴D̴,̴E̴,̴F̴,̴G̴,̴H̴,̴I̴,̴J̴,̴K̴,̴L̴,̴M̴,̴N̴,̴O̴,̴P̴,̴Q̴,̴R̴,̴S̴,̴T̴,̴U̴,̴V̴,̴W̴,̴X̴,̴Y̴,̴Z̴,̴a̴,̴b̴,̴c̴,̴d̴,̴e̴,̴f̴,̴g̴,̴h̴,̴i̴,̴j̴,̴k̴,̴l̴,̴m̴,̴n̴,̴o̴,̴p̴,̴q̴,̴r̴,̴s̴,̴t̴,̴u̴,̴v̴,̴w̴,̴x̴,̴y̴,̴z̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴", "ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_", "⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_", "α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_", "მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,0,Գ,Ց,Դ,6,5,Վ,Յ,Զ,1,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_", "α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,0,9,8,7,6,5,4,3,2,1,.,_", "Δ,Ɓ,C,D,Σ,F,G,H,I,J,Ƙ,L,Μ,∏,Θ,Ƥ,Ⴓ,Γ,Ѕ,Ƭ,Ʊ,Ʋ,Ш,Ж,Ψ,Z,λ,ϐ,ς,d,ε,ғ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_", "ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_", "α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,0,9,8,7,6,5,4,3,2,1,.,_", "ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_", "Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_", "Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,0,9,8,7,6,5,4,3,2,1,.,_", "Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,0,9,8,7,6,5,4,3,2,1,.,_", "ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_", "4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,‾", "A̴,̴B̴,̴C̴,̴D̴,̴E̴,̴F̴,̴G̴,̴H̴,̴I̴,̴J̴,̴K̴,̴L̴,̴M̴,̴N̴,̴O̴,̴P̴,̴Q̴,̴R̴,̴S̴,̴T̴,̴U̴,̴V̴,̴W̴,̴X̴,̴Y̴,̴Z̴,̴a̴,̴b̴,̴c̴,̴d̴,̴e̴,̴f̴,̴g̴,̴h̴,̴i̴,̴j̴,̴k̴,̴l̴,̴m̴,̴n̴,̴o̴,̴p̴,̴q̴,̴r̴,̴s̴,̴t̴,̴u̴,̴v̴,̴w̴,̴x̴,̴y̴,̴z̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴", "A̱,̱Ḇ,̱C̱,̱Ḏ,̱E̱,̱F̱,̱G̱,̱H̱,̱I̱,̱J̱,̱Ḵ,̱Ḻ,̱M̱,̱Ṉ,̱O̱,̱P̱,̱Q̱,̱Ṟ,̱S̱,̱Ṯ,̱U̱,̱V̱,̱W̱,̱X̱,̱Y̱,̱Ẕ,̱a̱,̱ḇ,̱c̱,̱ḏ,̱e̱,̱f̱,̱g̱,̱ẖ,̱i̱,̱j̱,̱ḵ,̱ḻ,̱m̱,̱ṉ,̱o̱,̱p̱,̱q̱,̱ṟ,̱s̱,̱ṯ,̱u̱,̱v̱,̱w̱,̱x̱,̱y̱,̱ẕ,̱0̱,̱9̱,̱8̱,̱7̱,̱6̱,̱5̱,̱4̱,̱3̱,̱2̱,̱1̱,̱.̱,̱_̱", "A̲,̲B̲,̲C̲,̲D̲,̲E̲,̲F̲,̲G̲,̲H̲,̲I̲,̲J̲,̲K̲,̲L̲,̲M̲,̲N̲,̲O̲,̲P̲,̲Q̲,̲R̲,̲S̲,̲T̲,̲U̲,̲V̲,̲W̲,̲X̲,̲Y̲,̲Z̲,̲a̲,̲b̲,̲c̲,̲d̲,̲e̲,̲f̲,̲g̲,̲h̲,̲i̲,̲j̲,̲k̲,̲l̲,̲m̲,̲n̲,̲o̲,̲p̲,̲q̲,̲r̲,̲s̲,̲t̲,̲u̲,̲v̲,̲w̲,̲x̲,̲y̲,̲z̲,̲0̲,̲9̲,̲8̲,̲7̲,̲6̲,̲5̲,̲4̲,̲3̲,̲2̲,̲1̲,̲.̲,̲_̲", "Ā,̄B̄,̄C̄,̄D̄,̄Ē,̄F̄,̄Ḡ,̄H̄,̄Ī,̄J̄,̄K̄,̄L̄,̄M̄,̄N̄,̄Ō,̄P̄,̄Q̄,̄R̄,̄S̄,̄T̄,̄Ū,̄V̄,̄W̄,̄X̄,̄Ȳ,̄Z̄,̄ā,̄b̄,̄c̄,̄d̄,̄ē,̄f̄,̄ḡ,̄h̄,̄ī,̄j̄,̄k̄,̄l̄,̄m̄,̄n̄,̄ō,̄p̄,̄q̄,̄r̄,̄s̄,̄t̄,̄ū,̄v̄,̄w̄,̄x̄,̄ȳ,̄z̄,̄0̄,̄9̄,̄8̄,̄7̄,̄6̄,̄5̄,̄4̄,̄3̄,̄2̄,̄1̄,̄.̄,̄_̄", "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_", "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,9,8,7,6,5,4,3,2,1,.,_", "@,♭,ḉ,ⓓ,℮,ƒ,ℊ,ⓗ,ⓘ,נ,ⓚ,ℓ,ⓜ,η,ø,℘,ⓠ,ⓡ,﹩,т,ⓤ,√,ω,ж,૪,ℨ,@,♭,ḉ,ⓓ,℮,ƒ,ℊ,ⓗ,ⓘ,נ,ⓚ,ℓ,ⓜ,η,ø,℘,ⓠ,ⓡ,﹩,т,ⓤ,√,ω,ж,૪,ℨ,0,➈,➑,➐,➅,➄,➃,➌,➁,➊,.,_", "@,♭,¢,ⅾ,ε,ƒ,ℊ,ℌ,ї,נ,к,ℓ,м,п,ø,ρ,ⓠ,ґ,﹩,⊥,ü,√,ω,ϰ,૪,ℨ,@,♭,¢,ⅾ,ε,ƒ,ℊ,ℌ,ї,נ,к,ℓ,м,п,ø,ρ,ⓠ,ґ,﹩,⊥,ü,√,ω,ϰ,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_", "α,♭,ḉ,∂,ℯ,ƒ,ℊ,ℌ,ї,ʝ,ḱ,ℓ,м,η,ø,℘,ⓠ,я,﹩,⊥,ц,ṽ,ω,ჯ,૪,ẕ,α,♭,ḉ,∂,ℯ,ƒ,ℊ,ℌ,ї,ʝ,ḱ,ℓ,м,η,ø,℘,ⓠ,я,﹩,⊥,ц,ṽ,ω,ჯ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,¢,ḓ,℮,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,м,п,◎,℘,ⓠ,я,﹩,т,ʊ,♥️,ẘ,✄,૪,ℨ,@,ß,¢,ḓ,℮,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,м,п,◎,℘,ⓠ,я,﹩,т,ʊ,♥️,ẘ,✄,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,¢,ḓ,℮,ƒ,ℊ,н,ḯ,נ,к,ℓμ,п,☺️,℘,ⓠ,я,﹩,⊥,υ,ṽ,ω,✄,૪,ℨ,@,ß,¢,ḓ,℮,ƒ,ℊ,н,ḯ,נ,к,ℓμ,п,☺️,℘,ⓠ,я,﹩,⊥,υ,ṽ,ω,✄,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,ḉ,ḓ,є,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,ღ,η,◎,℘,ⓠ,я,﹩,⊥,ʊ,♥️,ω,ϰ,૪,ẕ,@,ß,ḉ,ḓ,є,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,ღ,η,◎,℘,ⓠ,я,﹩,⊥,ʊ,♥️,ω,ϰ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,ḉ,∂,ε,ƒ,ℊ,ℌ,ї,נ,ḱ,ł,ღ,и,ø,℘,ⓠ,я,﹩,т,υ,√,ω,ჯ,૪,ẕ,@,ß,ḉ,∂,ε,ƒ,ℊ,ℌ,ї,נ,ḱ,ł,ღ,и,ø,℘,ⓠ,я,﹩,т,υ,√,ω,ჯ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "α,♭,¢,∂,ε,ƒ,❡,н,ḯ,ʝ,ḱ,ʟ,μ,п,ø,ρ,ⓠ,ґ,﹩,т,υ,ṽ,ω,ж,૪,ẕ,α,♭,¢,∂,ε,ƒ,❡,н,ḯ,ʝ,ḱ,ʟ,μ,п,ø,ρ,ⓠ,ґ,﹩,т,υ,ṽ,ω,ж,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "α,♭,ḉ,∂,℮,ⓕ,ⓖ,н,ḯ,ʝ,ḱ,ℓ,м,п,ø,ⓟ,ⓠ,я,ⓢ,ⓣ,ⓤ,♥️,ⓦ,✄,ⓨ,ⓩ,α,♭,ḉ,∂,℮,ⓕ,ⓖ,н,ḯ,ʝ,ḱ,ℓ,м,п,ø,ⓟ,ⓠ,я,ⓢ,ⓣ,ⓤ,♥️,ⓦ,✄,ⓨ,ⓩ,0,➒,➑,➐,➏,➄,➍,➂,➁,➀,.,_", "@,♭,ḉ,ḓ,є,ƒ,ⓖ,ℌ,ⓘ,נ,к,ⓛ,м,ⓝ,ø,℘,ⓠ,я,﹩,ⓣ,ʊ,√,ω,ჯ,૪,ⓩ,@,♭,ḉ,ḓ,є,ƒ,ⓖ,ℌ,ⓘ,נ,к,ⓛ,м,ⓝ,ø,℘,ⓠ,я,﹩,ⓣ,ʊ,√,ω,ჯ,૪,ⓩ,0,➒,➇,➆,➅,➄,➍,➌,➋,➀,.,_", "α,♭,ⓒ,∂,є,ⓕ,ⓖ,ℌ,ḯ,ⓙ,ḱ,ł,ⓜ,и,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,⊥,ʊ,ⓥ,ⓦ,ж,ⓨ,ⓩ,α,♭,ⓒ,∂,є,ⓕ,ⓖ,ℌ,ḯ,ⓙ,ḱ,ł,ⓜ,и,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,⊥,ʊ,ⓥ,ⓦ,ж,ⓨ,ⓩ,0,➒,➑,➆,➅,➎,➍,➌,➁,➀,.,_", "ⓐ,ß,ḉ,∂,℮,ⓕ,❡,ⓗ,ї,נ,ḱ,ł,μ,η,ø,ρ,ⓠ,я,﹩,ⓣ,ц,√,ⓦ,✖️,૪,ℨ,ⓐ,ß,ḉ,∂,℮,ⓕ,❡,ⓗ,ї,נ,ḱ,ł,μ,η,ø,ρ,ⓠ,я,﹩,ⓣ,ц,√,ⓦ,✖️,૪,ℨ,0,➒,➑,➐,➅,➄,➍,➂,➁,➊,.,_", "α,ß,ⓒ,ⅾ,ℯ,ƒ,ℊ,ⓗ,ї,ʝ,к,ʟ,ⓜ,η,ⓞ,℘,ⓠ,ґ,﹩,т,υ,ⓥ,ⓦ,ж,ⓨ,ẕ,α,ß,ⓒ,ⅾ,ℯ,ƒ,ℊ,ⓗ,ї,ʝ,к,ʟ,ⓜ,η,ⓞ,℘,ⓠ,ґ,﹩,т,υ,ⓥ,ⓦ,ж,ⓨ,ẕ,0,➈,➇,➐,➅,➎,➍,➌,➁,➊,.,_", "@,♭,ḉ,ⅾ,є,ⓕ,❡,н,ḯ,נ,ⓚ,ⓛ,м,ⓝ,☺️,ⓟ,ⓠ,я,ⓢ,⊥,υ,♥️,ẘ,ϰ,૪,ⓩ,@,♭,ḉ,ⅾ,є,ⓕ,❡,н,ḯ,נ,ⓚ,ⓛ,м,ⓝ,☺️,ⓟ,ⓠ,я,ⓢ,⊥,υ,♥️,ẘ,ϰ,૪,ⓩ,0,➒,➑,➆,➅,➄,➃,➂,➁,➀,.,_", "ⓐ,♭,ḉ,ⅾ,є,ƒ,ℊ,ℌ,ḯ,ʝ,ḱ,ł,μ,η,ø,ⓟ,ⓠ,ґ,ⓢ,т,ⓤ,√,ⓦ,✖️,ⓨ,ẕ,ⓐ,♭,ḉ,ⅾ,є,ƒ,ℊ,ℌ,ḯ,ʝ,ḱ,ł,μ,η,ø,ⓟ,ⓠ,ґ,ⓢ,т,ⓤ,√,ⓦ,✖️,ⓨ,ẕ,0,➈,➇,➐,➅,➄,➃,➂,➁,➀,.,_", "ձ,ъƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_", "λ,ϐ,ς,d,ε,ғ,ϑ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,λ,ϐ,ς,d,ε,ғ,ϑ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_", "მ,ჩ,ƈძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,მ,ჩ,ƈძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,0,Գ,Ց,Դ,6,5,Վ,Յ,Զ,1,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_", "λ,ß,Ȼ,ɖ,ε,ʃ,Ģ,ħ,ί,ĵ,κ,ι,ɱ,ɴ,Θ,ρ,ƣ,ર,Ș,τ,Ʋ,ν,ώ,Χ,ϓ,Հ,λ,ß,Ȼ,ɖ,ε,ʃ,Ģ,ħ,ί,ĵ,κ,ι,ɱ,ɴ,Θ,ρ,ƣ,ર,Ș,τ,Ʋ,ν,ώ,Χ,ϓ,Հ,0,9,8,7,6,5,4,3,2,1,.,_", "ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,0,9,8,7,6,5,4,3,2,1,.,_", "Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Ϧ,ㄈ,Ð,Ɛ,F,Ɠ,н,ɪ,フ,Қ,Ł,௱,Л,Ø,þ,Ҩ,尺,ら,Ť,Ц,Ɣ,Ɯ,χ,Ϥ,Ẕ,Λ,Ϧ,ㄈ,Ð,Ɛ,F,Ɠ,н,ɪ,フ,Қ,Ł,௱,Л,Ø,þ,Ҩ,尺,ら,Ť,Ц,Ɣ,Ɯ,χ,Ϥ,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "Ǟ,в,ट,D,ę,բ,g,৸,i,j,κ,l,ɱ,П,Φ,Р,q,Я,s,Ʈ,Ц,v,Щ,ж,ყ,ւ,Ǟ,в,ट,D,ę,բ,g,৸,i,j,κ,l,ɱ,П,Φ,Р,q,Я,s,Ʈ,Ц,v,Щ,ж,ყ,ւ,0,9,8,7,6,5,4,3,2,1,.,_", "ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_", "Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,0,9,8,7,6,5,4,3,2,1,.,_", "ª,ß,¢,ð,€,f,g,h,¡,j,k,|,m,ñ,¤,Þ,q,®,$,t,µ,v,w,×,ÿ,z,ª,ß,¢,ð,€,f,g,h,¡,j,k,|,m,ñ,¤,Þ,q,®,$,t,µ,v,w,×,ÿ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_", "⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_", "ɑ,ʙ,c,ᴅ,є,ɻ,მ,ʜ,ι,ɿ,ĸ,г,w,и,o,ƅϭ,ʁ,ƨ,⊥,n,ʌ,ʍ,x,⑃,z,ɑ,ʙ,c,ᴅ,є,ɻ,მ,ʜ,ι,ɿ,ĸ,г,w,и,o,ƅϭ,ʁ,ƨ,⊥,n,ʌ,ʍ,x,⑃,z,0,9,8,7,6,5,4,3,2,1,.,_", "4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ßƇ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,Λ,ßƇ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,ɔ,ε,ғ,ɢ,н,ı,נ,κ,ʟ,м,п,σ,ρ,ǫ,я,ƨ,т,υ,ν,ш,х,ч,z,α,в,c,ɔ,ε,ғ,ɢ,н,ı,נ,κ,ʟ,м,п,σ,ρ,ǫ,я,ƨ,т,υ,ν,ш,х,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "【a】,【b】,【c】,【d】,【e】,【f】,【g】,【h】,【i】,【j】,【k】,【l】,【m】,【n】,【o】,【p】,【q】,【r】,【s】,【t】,【u】,【v】,【w】,【x】,【y】,【z】,【a】,【b】,【c】,【d】,【e】,【f】,【g】,【h】,【i】,【j】,【k】,【l】,【m】,【n】,【o】,【p】,【q】,【r】,【s】,【t】,【u】,【v】,【w】,【x】,【y】,【z】,【0】,【9】,【8】,【7】,【6】,【5】,【4】,【3】,【2】,【1】,.,_", "[̲̲̅̅a̲̅,̲̅b̲̲̅,̅c̲̅,̲̅d̲̲̅,̅e̲̲̅,̅f̲̲̅,̅g̲̅,̲̅h̲̲̅,̅i̲̲̅,̅j̲̲̅,̅k̲̅,̲̅l̲̲̅,̅m̲̅,̲̅n̲̅,̲̅o̲̲̅,̅p̲̅,̲̅q̲̅,̲̅r̲̲̅,̅s̲̅,̲̅t̲̲̅,̅u̲̅,̲̅v̲̅,̲̅w̲̅,̲̅x̲̅,̲̅y̲̅,̲̅z̲̅,[̲̲̅̅a̲̅,̲̅b̲̲̅,̅c̲̅,̲̅d̲̲̅,̅e̲̲̅,̅f̲̲̅,̅g̲̅,̲̅h̲̲̅,̅i̲̲̅,̅j̲̲̅,̅k̲̅,̲̅l̲̲̅,̅m̲̅,̲̅n̲̅,̲̅o̲̲̅,̅p̲̅,̲̅q̲̅,̲̅r̲̲̅,̅s̲̅,̲̅t̲̲̅,̅u̲̅,̲̅v̲̅,̲̅w̲̅,̲̅x̲̅,̲̅y̲̅,̲̅z̲̅,̲̅0̲̅,̲̅9̲̲̅,̅8̲̅,̲̅7̲̅,̲̅6̲̅,̲̅5̲̅,̲̅4̲̅,̲̅3̲̲̅,̅2̲̲̅,̅1̲̲̅̅],.,_", "[̺͆a̺͆͆,̺b̺͆͆,̺c̺͆,̺͆d̺͆,̺͆e̺͆,̺͆f̺͆͆,̺g̺͆,̺͆h̺͆,̺͆i̺͆,̺͆j̺͆,̺͆k̺͆,̺l̺͆͆,̺m̺͆͆,̺n̺͆͆,̺o̺͆,̺͆p̺͆͆,̺q̺͆͆,̺r̺͆͆,̺s̺͆͆,̺t̺͆͆,̺u̺͆͆,̺v̺͆͆,̺w̺͆,̺͆x̺͆,̺͆y̺͆,̺͆z̺,[̺͆a̺͆͆,̺b̺͆͆,̺c̺͆,̺͆d̺͆,̺͆e̺͆,̺͆f̺͆͆,̺g̺͆,̺͆h̺͆,̺͆i̺͆,̺͆j̺͆,̺͆k̺͆,̺l̺͆͆,̺m̺͆͆,̺n̺͆͆,̺o̺͆,̺͆p̺͆͆,̺q̺͆͆,̺r̺͆͆,̺s̺͆͆,̺t̺͆͆,̺u̺͆͆,̺v̺͆͆,̺w̺͆,̺͆x̺͆,̺͆y̺͆,̺͆z̺,̺͆͆0̺͆,̺͆9̺͆,̺͆8̺̺͆͆7̺͆,̺͆6̺͆,̺͆5̺͆,̺͆4̺͆,̺͆3̺͆,̺͆2̺͆,̺͆1̺͆],.,_", "̛̭̰̃ã̛̰̭,̛̭̰̃b̛̰̭̃̃,̛̭̰c̛̛̰̭̃̃,̭̰d̛̰̭̃,̛̭̰̃ḛ̛̭̃̃,̛̭̰f̛̰̭̃̃,̛̭̰g̛̰̭̃̃,̛̭̰h̛̰̭̃,̛̭̰̃ḭ̛̛̭̃̃,̭̰j̛̰̭̃̃,̛̭̰k̛̰̭̃̃,̛̭̰l̛̰̭,̛̭̰̃m̛̰̭̃̃,̛̭̰ñ̛̛̰̭̃,̭̰ỡ̰̭̃,̛̭̰p̛̰̭̃,̛̭̰̃q̛̰̭̃̃,̛̭̰r̛̛̰̭̃̃,̭̰s̛̰̭,̛̭̰̃̃t̛̰̭̃,̛̭̰̃ữ̰̭̃,̛̭̰ṽ̛̰̭̃,̛̭̰w̛̛̰̭̃̃,̭̰x̛̰̭̃,̛̭̰̃ỹ̛̰̭̃,̛̭̰z̛̰̭̃̃,̛̛̭̰ã̛̰̭,̛̭̰̃b̛̰̭̃̃,̛̭̰c̛̛̰̭̃̃,̭̰d̛̰̭̃,̛̭̰̃ḛ̛̭̃̃,̛̭̰f̛̰̭̃̃,̛̭̰g̛̰̭̃̃,̛̭̰h̛̰̭̃,̛̭̰̃ḭ̛̛̭̃̃,̭̰j̛̰̭̃̃,̛̭̰k̛̰̭̃̃,̛̭̰l̛̰̭,̛̭̰̃m̛̰̭̃̃,̛̭̰ñ̛̛̰̭̃,̭̰ỡ̰̭̃,̛̭̰p̛̰̭̃,̛̭̰̃q̛̰̭̃̃,̛̭̰r̛̛̰̭̃̃,̭̰s̛̰̭,̛̭̰̃̃t̛̰̭̃,̛̭̰̃ữ̰̭̃,̛̭̰ṽ̛̰̭̃,̛̭̰w̛̛̰̭̃̃,̭̰x̛̰̭̃,̛̭̰̃ỹ̛̰̭̃,̛̭̰z̛̰̭̃̃,̛̭̰0̛̛̰̭̃̃,̭̰9̛̰̭̃̃,̛̭̰8̛̛̰̭̃̃,̭̰7̛̰̭̃̃,̛̭̰6̛̰̭̃̃,̛̭̰5̛̰̭̃,̛̭̰̃4̛̰̭̃,̛̭̰̃3̛̰̭̃̃,̛̭̰2̛̰̭̃̃,̛̭̰1̛̰̭̃,.,_", "a,ะb,ะc,ะd,ะe,ะf,ะg,ะh,ะi,ะj,ะk,ะl,ะm,ะn,ะo,ะp,ะq,ะr,ะs,ะt,ะu,ะv,ะw,ะx,ะy,ะz,a,ะb,ะc,ะd,ะe,ะf,ะg,ะh,ะi,ะj,ะk,ะl,ะm,ะn,ะo,ะp,ะq,ะr,ะs,ะt,ะu,ะv,ะw,ะx,ะy,ะz,ะ0,ะ9,ะ8,ะ7,ะ6,ะ5,ะ4,ะ3,ะ2,ะ1ะ,.,_", "̑ȃ,̑b̑,̑c̑,̑d̑,̑ȇ,̑f̑,̑g̑,̑h̑,̑ȋ,̑j̑,̑k̑,̑l̑,̑m̑,̑n̑,̑ȏ,̑p̑,̑q̑,̑ȓ,̑s̑,̑t̑,̑ȗ,̑v̑,̑w̑,̑x̑,̑y̑,̑z̑,̑ȃ,̑b̑,̑c̑,̑d̑,̑ȇ,̑f̑,̑g̑,̑h̑,̑ȋ,̑j̑,̑k̑,̑l̑,̑m̑,̑n̑,̑ȏ,̑p̑,̑q̑,̑ȓ,̑s̑,̑t̑,̑ȗ,̑v̑,̑w̑,̑x̑,̑y̑,̑z̑,̑0̑,̑9̑,̑8̑,̑7̑,̑6̑,̑5̑,̑4̑,̑3̑,̑2̑,̑1̑,.,_", "~a,͜͝b,͜͝c,͜͝d,͜͝e,͜͝f,͜͝g,͜͝h,͜͝i,͜͝j,͜͝k,͜͝l,͜͝m,͜͝n,͜͝o,͜͝p,͜͝q,͜͝r,͜͝s,͜͝t,͜͝u,͜͝v,͜͝w,͜͝x,͜͝y,͜͝z,~a,͜͝b,͜͝c,͜͝d,͜͝e,͜͝f,͜͝g,͜͝h,͜͝i,͜͝j,͜͝k,͜͝l,͜͝m,͜͝n,͜͝o,͜͝p,͜͝q,͜͝r,͜͝s,͜͝t,͜͝u,͜͝v,͜͝w,͜͝x,͜͝y,͜͝z,͜͝0,͜͝9,͜͝8,͜͝7,͜͝6,͜͝5,͜͝4,͜͝3,͜͝2͜,͝1͜͝~,.,_", "̤̈ä̤,̤̈b̤̈,̤̈c̤̈̈,̤d̤̈,̤̈ë̤,̤̈f̤̈,̤̈g̤̈̈,̤ḧ̤̈,̤ï̤̈,̤j̤̈,̤̈k̤̈̈,̤l̤̈,̤̈m̤̈,̤̈n̤̈,̤̈ö̤,̤̈p̤̈,̤̈q̤̈,̤̈r̤̈,̤̈s̤̈̈,̤ẗ̤̈,̤ṳ̈,̤̈v̤̈,̤̈ẅ̤,̤̈ẍ̤,̤̈ÿ̤,̤̈z̤̈,̤̈ä̤,̤̈b̤̈,̤̈c̤̈̈,̤d̤̈,̤̈ë̤,̤̈f̤̈,̤̈g̤̈̈,̤ḧ̤̈,̤ï̤̈,̤j̤̈,̤̈k̤̈̈,̤l̤̈,̤̈m̤̈,̤̈n̤̈,̤̈ö̤,̤̈p̤̈,̤̈q̤̈,̤̈r̤̈,̤̈s̤̈̈,̤ẗ̤̈,̤ṳ̈,̤̈v̤̈,̤̈ẅ̤,̤̈ẍ̤,̤̈ÿ̤,̤̈z̤̈,̤̈0̤̈,̤̈9̤̈,̤̈8̤̈,̤̈7̤̈,̤̈6̤̈,̤̈5̤̈,̤̈4̤̈,̤̈3̤̈,̤̈2̤̈̈,̤1̤̈,.,_", "≋̮̑ȃ̮,̮̑b̮̑,̮̑c̮̑,̮̑d̮̑,̮̑ȇ̮,̮̑f̮̑,̮̑g̮̑,̮̑ḫ̑,̮̑ȋ̮,̮̑j̮̑,̮̑k̮̑,̮̑l̮̑,̮̑m̮̑,̮̑n̮̑,̮̑ȏ̮,̮̑p̮̑,̮̑q̮̑,̮̑r̮,̮̑̑s̮,̮̑̑t̮,̮̑̑u̮,̮̑̑v̮̑,̮̑w̮̑,̮̑x̮̑,̮̑y̮̑,̮̑z̮̑,≋̮̑ȃ̮,̮̑b̮̑,̮̑c̮̑,̮̑d̮̑,̮̑ȇ̮,̮̑f̮̑,̮̑g̮̑,̮̑ḫ̑,̮̑ȋ̮,̮̑j̮̑,̮̑k̮̑,̮̑l̮̑,̮̑m̮̑,̮̑n̮̑,̮̑ȏ̮,̮̑p̮̑,̮̑q̮̑,̮̑r̮,̮̑̑s̮,̮̑̑t̮,̮̑̑u̮,̮̑̑v̮̑,̮̑w̮̑,̮̑x̮̑,̮̑y̮̑,̮̑z̮̑,̮̑0̮̑,̮̑9̮̑,̮̑8̮̑,̮̑7̮̑,̮̑6̮̑,̮̑5̮̑,̮̑4̮̑,̮̑3̮̑,̮̑2̮̑,̮̑1̮̑≋,.,_", "a̮,̮b̮̮,c̮̮,d̮̮,e̮̮,f̮̮,g̮̮,ḫ̮,i̮,j̮̮,k̮̮,l̮,̮m̮,̮n̮̮,o̮,̮p̮̮,q̮̮,r̮̮,s̮,̮t̮̮,u̮̮,v̮̮,w̮̮,x̮̮,y̮̮,z̮̮,a̮,̮b̮̮,c̮̮,d̮̮,e̮̮,f̮̮,g̮̮,ḫ̮i,̮̮,j̮̮,k̮̮,l̮,̮m̮,̮n̮̮,o̮,̮p̮̮,q̮̮,r̮̮,s̮,̮t̮̮,u̮̮,v̮̮,w̮̮,x̮̮,y̮̮,z̮̮,0̮̮,9̮̮,8̮̮,7̮̮,6̮̮,5̮̮,4̮̮,3̮̮,2̮̮,1̮,.,_", "A̲,̲B̲,̲C̲,̲D̲,̲E̲,̲F̲,̲G̲,̲H̲,̲I̲,̲J̲,̲K̲,̲L̲,̲M̲,̲N̲,̲O̲,̲P̲,̲Q̲,̲R̲,̲S̲,̲T̲,̲U̲,̲V̲,̲W̲,̲X̲,̲Y̲,̲Z̲,̲a̲,̲b̲,̲c̲,̲d̲,̲e̲,̲f̲,̲g̲,̲h̲,̲i̲,̲j̲,̲k̲,̲l̲,̲m̲,̲n̲,̲o̲,̲p̲,̲q̲,̲r̲,̲s̲,̲t̲,̲u̲,̲v̲,̲w̲,̲x̲,̲y̲,̲z̲,̲0̲,̲9̲,̲8̲,̲7̲,̲6̲,̲5̲,̲4̲,̲3̲,̲2̲,̲1̲,̲.̲,̲_̲", "Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_", } -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local result = {} i=0 for k=1,#fonts do i=i+1 local tar_font = fonts[i]:split(",") local text = matches[2] local text = text:gsub("A",tar_font[1]) local text = text:gsub("B",tar_font[2]) local text = text:gsub("C",tar_font[3]) local text = text:gsub("D",tar_font[4]) local text = text:gsub("E",tar_font[5]) local text = text:gsub("F",tar_font[6]) local text = text:gsub("G",tar_font[7]) local text = text:gsub("H",tar_font[8]) local text = text:gsub("I",tar_font[9]) local text = text:gsub("J",tar_font[10]) local text = text:gsub("K",tar_font[11]) local text = text:gsub("L",tar_font[12]) local text = text:gsub("M",tar_font[13]) local text = text:gsub("N",tar_font[14]) local text = text:gsub("O",tar_font[15]) local text = text:gsub("P",tar_font[16]) local text = text:gsub("Q",tar_font[17]) local text = text:gsub("R",tar_font[18]) local text = text:gsub("S",tar_font[19]) local text = text:gsub("T",tar_font[20]) local text = text:gsub("U",tar_font[21]) local text = text:gsub("V",tar_font[22]) local text = text:gsub("W",tar_font[23]) local text = text:gsub("X",tar_font[24]) local text = text:gsub("Y",tar_font[25]) local text = text:gsub("Z",tar_font[26]) local text = text:gsub("a",tar_font[27]) local text = text:gsub("b",tar_font[28]) local text = text:gsub("c",tar_font[29]) local text = text:gsub("d",tar_font[30]) local text = text:gsub("e",tar_font[31]) local text = text:gsub("f",tar_font[32]) local text = text:gsub("g",tar_font[33]) local text = text:gsub("h",tar_font[34]) local text = text:gsub("i",tar_font[35]) local text = text:gsub("j",tar_font[36]) local text = text:gsub("k",tar_font[37]) local text = text:gsub("l",tar_font[38]) local text = text:gsub("m",tar_font[39]) local text = text:gsub("n",tar_font[40]) local text = text:gsub("o",tar_font[41]) local text = text:gsub("p",tar_font[42]) local text = text:gsub("q",tar_font[43]) local text = text:gsub("r",tar_font[44]) local text = text:gsub("s",tar_font[45]) local text = text:gsub("t",tar_font[46]) local text = text:gsub("u",tar_font[47]) local text = text:gsub("v",tar_font[48]) local text = text:gsub("w",tar_font[49]) local text = text:gsub("x",tar_font[50]) local text = text:gsub("y",tar_font[51]) local text = text:gsub("z",tar_font[52]) local text = text:gsub("0",tar_font[53]) local text = text:gsub("9",tar_font[54]) local text = text:gsub("8",tar_font[55]) local text = text:gsub("7",tar_font[56]) local text = text:gsub("6",tar_font[57]) local text = text:gsub("5",tar_font[58]) local text = text:gsub("4",tar_font[59]) local text = text:gsub("3",tar_font[60]) local text = text:gsub("2",tar_font[61]) local text = text:gsub("1",tar_font[62]) table.insert(result, text) end local result_text = "زخرفة كلمة : "..matches[2].."\nتطبيق اكثر من "..tostring(#fonts).." نوع من الخطوط : \n_____________________________" a=0 for v=1,#result do a=a+1 result_text = result_text..a.."- "..result[a].."\n\n" end return result_text.."#ṂṜẌ" end return { description = "Fantasy Writer", usagehtm = '<tr><td align="center">write </td><td align="right">ملف زخرفة للكلمات الانكليزية ملف يحتوي على اكثر من 50 نوع من الخطوط للزخرفة وتحصل على زخارف رائعة يمكنك وضع 20 حرف انكليزي فقط لايمكنك وضع اكثر</td></tr>', usage = {"write [text] : زیبا نویسی",}, patterns = { "^(زخرف) (.*)", "^(زخرف)$", "^(ensof) (.*)", "^(ensof)$", }, run = run }
gpl-2.0
CaptainCN/QCEditor
cocos2d/cocos/scripting/lua-bindings/script/framework/device.lua
5
3851
--[[ Copyright (c) 2014-2017 Chukong Technologies Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local device = {} device.platform = "unknown" device.model = "unknown" local app = cc.Application:getInstance() local target = app:getTargetPlatform() if target == cc.PLATFORM_OS_WINDOWS then device.platform = "windows" elseif target == cc.PLATFORM_OS_MAC then device.platform = "mac" elseif target == cc.PLATFORM_OS_ANDROID then device.platform = "android" elseif target == cc.PLATFORM_OS_IPHONE or target == cc.PLATFORM_OS_IPAD then device.platform = "ios" local director = cc.Director:getInstance() local view = director:getOpenGLView() local framesize = view:getFrameSize() local w, h = framesize.width, framesize.height if w == 640 and h == 960 then device.model = "iphone 4" elseif w == 640 and h == 1136 then device.model = "iphone 5" elseif w == 750 and h == 1334 then device.model = "iphone 6" elseif w == 1242 and h == 2208 then device.model = "iphone 6 plus" elseif w == 768 and h == 1024 then device.model = "ipad" elseif w == 1536 and h == 2048 then device.model = "ipad retina" end elseif target == cc.PLATFORM_OS_WINRT then device.platform = "winrt" elseif target == cc.PLATFORM_OS_WP8 then device.platform = "wp8" end local language_ = app:getCurrentLanguage() if language_ == cc.LANGUAGE_CHINESE then language_ = "cn" elseif language_ == cc.LANGUAGE_FRENCH then language_ = "fr" elseif language_ == cc.LANGUAGE_ITALIAN then language_ = "it" elseif language_ == cc.LANGUAGE_GERMAN then language_ = "gr" elseif language_ == cc.LANGUAGE_SPANISH then language_ = "sp" elseif language_ == cc.LANGUAGE_RUSSIAN then language_ = "ru" elseif language_ == cc.LANGUAGE_KOREAN then language_ = "kr" elseif language_ == cc.LANGUAGE_JAPANESE then language_ = "jp" elseif language_ == cc.LANGUAGE_HUNGARIAN then language_ = "hu" elseif language_ == cc.LANGUAGE_PORTUGUESE then language_ = "pt" elseif language_ == cc.LANGUAGE_ARABIC then language_ = "ar" else language_ = "en" end device.language = language_ device.writablePath = cc.FileUtils:getInstance():getWritablePath() device.directorySeparator = "/" device.pathSeparator = ":" if device.platform == "windows" then device.directorySeparator = "\\" device.pathSeparator = ";" end printInfo("# device.platform = " .. device.platform) printInfo("# device.model = " .. device.model) printInfo("# device.language = " .. device.language) printInfo("# device.writablePath = " .. device.writablePath) printInfo("# device.directorySeparator = " .. device.directorySeparator) printInfo("# device.pathSeparator = " .. device.pathSeparator) printInfo("#") return device
mit
lukasc-ch/nn
HingeEmbeddingCriterion.lua
50
1290
local HingeEmbeddingCriterion, parent = torch.class('nn.HingeEmbeddingCriterion', 'nn.Criterion') function HingeEmbeddingCriterion:__init(margin) parent.__init(self) self.margin = margin or 1 self.sizeAverage = true end function HingeEmbeddingCriterion:updateOutput(input,y) self.buffer = self.buffer or input.new() if not torch.isTensor(y) then self.ty = self.ty or input.new():resize(1) self.ty[1]=y y=self.ty end self.buffer:resizeAs(input):copy(input) self.buffer[torch.eq(y, -1)] = 0 self.output = self.buffer:sum() self.buffer:fill(self.margin):add(-1, input) self.buffer:cmax(0) self.buffer[torch.eq(y, 1)] = 0 self.output = self.output + self.buffer:sum() if (self.sizeAverage == nil or self.sizeAverage == true) then self.output = self.output / input:nElement() end return self.output end function HingeEmbeddingCriterion:updateGradInput(input, y) if not torch.isTensor(y) then self.ty[1]=y; y=self.ty end self.gradInput:resizeAs(input):copy(y) self.gradInput[torch.cmul(torch.eq(y, -1), torch.gt(input, self.margin))] = 0 if (self.sizeAverage == nil or self.sizeAverage == true) then self.gradInput:mul(1 / input:nElement()) end return self.gradInput end
bsd-3-clause
FreeBlues/neko8
libs/moonscript/spec/outputs/lists.lua
2
3968
local hi do local _accum_0 = { } local _len_0 = 1 for _, x in ipairs({ 1, 2, 3, 4 }) do _accum_0[_len_0] = x * 2 _len_0 = _len_0 + 1 end hi = _accum_0 end local items = { 1, 2, 3, 4, 5, 6 } for z in ipairs(items) do if z > 4 then local _ = z end end local rad do local _accum_0 = { } local _len_0 = 1 for a in ipairs({ 1, 2, 3, 4, 5, 6 }) do if good_number(a) then _accum_0[_len_0] = { a } _len_0 = _len_0 + 1 end end rad = _accum_0 end for z in items do for j in list do if z > 4 then local _ = z end end end require("util") local dump dump = function(x) return print(util.dump(x)) end local range range = function(count) local i = 0 return coroutine.wrap(function() while i < count do coroutine.yield(i) i = i + 1 end end) end dump((function() local _accum_0 = { } local _len_0 = 1 for x in range(10) do _accum_0[_len_0] = x _len_0 = _len_0 + 1 end return _accum_0 end)()) dump((function() local _accum_0 = { } local _len_0 = 1 for x in range(5) do if x > 2 then for y in range(5) do _accum_0[_len_0] = { x, y } _len_0 = _len_0 + 1 end end end return _accum_0 end)()) local things do local _accum_0 = { } local _len_0 = 1 for x in range(10) do if x > 5 then for y in range(10) do if y > 7 then _accum_0[_len_0] = x + y _len_0 = _len_0 + 1 end end end end things = _accum_0 end for x in ipairs({ 1, 2, 4 }) do for y in ipairs({ 1, 2, 3 }) do if x ~= 2 then print(x, y) end end end for x in items do print("hello", x) end for x in x do local _ = x end local x do local _accum_0 = { } local _len_0 = 1 for x in x do _accum_0[_len_0] = x _len_0 = _len_0 + 1 end x = _accum_0 end for x in ipairs({ 1, 2, 4 }) do for y in ipairs({ 1, 2, 3 }) do if x ~= 2 then print(x, y) end end end local double do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #items do local x = items[_index_0] _accum_0[_len_0] = x * 2 _len_0 = _len_0 + 1 end double = _accum_0 end for _index_0 = 1, #double do local x = double[_index_0] print(x) end local cut do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #items do local x = items[_index_0] if x > 3 then _accum_0[_len_0] = x _len_0 = _len_0 + 1 end end cut = _accum_0 end local hello do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #items do local x = items[_index_0] for _index_1 = 1, #items do local y = items[_index_1] _accum_0[_len_0] = x + y _len_0 = _len_0 + 1 end end hello = _accum_0 end for _index_0 = 1, #hello do local z = hello[_index_0] print(z) end x = { 1, 2, 3, 4, 5, 6, 7 } local _max_0 = -5 for _index_0 = 2, _max_0 < 0 and #x + _max_0 or _max_0, 2 do local y = x[_index_0] print(y) end local _max_1 = 3 for _index_0 = 1, _max_1 < 0 and #x + _max_1 or _max_1 do local y = x[_index_0] print(y) end for _index_0 = 2, #x do local y = x[_index_0] print(y) end for _index_0 = 1, #x, 2 do local y = x[_index_0] print(y) end for _index_0 = 2, #x, 2 do local y = x[_index_0] print(y) end local a, b, c = 1, 5, 2 local _max_2 = b for _index_0 = a, _max_2 < 0 and #x + _max_2 or _max_2, c do local y = x[_index_0] print(y) end local normal normal = function(hello) local _accum_0 = { } local _len_0 = 1 for x in yeah do _accum_0[_len_0] = x _len_0 = _len_0 + 1 end return _accum_0 end local test = x(1, 2, 3, 4, 5) for _index_0 = 1, #test do local thing = test[_index_0] print(thing) end return function() local _list_0 = rows for _index_0 = 1, #_list_0 do local row = _list_0[_index_0] a = b end end
mit
sfriesel/libdessert
dissectors/dessert.lua
2
7761
-- ---------------------------------------------------------------------------- -- Copyright 2009, David Gutzmann, Freie Universitaet Berlin (FUB). -- Copyright 2010, Bastian Blywis, Freie Universitaet Berlin (FUB). -- All rights reserved. --These sources were originally developed by David Gutzmann, --rewritten and extended by Bastian Blywis --at Freie Universitaet Berlin (http://www.fu-berlin.de/), --Computer Systems and Telematics / Distributed, embedded Systems (DES) group --(http://cst.mi.fu-berlin.de, http://www.des-testbed.net) -- ---------------------------------------------------------------------------- --This program is free software: you can redistribute it and/or modify it under --the terms of the GNU General Public License as published by the Free Software --Foundation, either version 3 of the License, or (at your option) any later --version. --This program is distributed in the hope that it will be useful, but WITHOUT --ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS --FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. --You should have received a copy of the GNU General Public License along with --this program. If not, see http://www.gnu.org/licenses/ . -- ---------------------------------------------------------------------------- --For further information and questions please use the web site -- http://www.des-testbed.net -- ---------------------------------------------------------------------------- local extension_types = { [0x01] = "DESSERT_EXT_ETH", [0x02] = "DESSERT_EXT_TRACE_REQ", [0x03] = "DESSERT_EXT_TRACE_RPL", [0x04] = "DESSERT_EXT_PING", [0x05] = "DESSERT_EXT_PONG", [0x40] = "DESSERT_EXT_USER" } dessert_dissector_table = DissectorTable.new("desserttable") _G.dessert_register_ext_dissector = function(ext_type, ext_name, dissector) print("Info: loading extension dissector: "..tostring(ext_name)) extension_types[ext_type] = ext_name dessert_dissector_table:add(ext_type, dissector) end dofile("dessert-ext-eth.lua") dofile("dessert-ext-ping.lua") dofile("dessert-ext-trace.lua") -- Create a new dissector DESSERT = Proto ("dessert", "DES-SERT") -- Create the protocol fields local f = DESSERT.fields f.proto = ProtoField.string ("dessert.proto" , "Protocol name") f.version = ProtoField.uint8 ("dessert.version", "Protocol version") f.flags = ProtoField.uint8 ("dessert.flags" , "Flags" , base.HEX, nil, 0xFF) f.flags_1 = ProtoField.uint8 ("dessert.flags_1", "Flag 1", base.HEX, nil, 0x01) f.flags_2 = ProtoField.uint8 ("dessert.flags_2", "Flag 2", base.HEX, nil, 0x02) f.flags_3 = ProtoField.uint8 ("dessert.flags_3", "Flag 3", base.HEX, nil, 0x04) f.flags_4 = ProtoField.uint8 ("dessert.flags_4", "Flag 4", base.HEX, nil, 0x08) f.flags_5 = ProtoField.uint8 ("dessert.sparse" , "DESSERT_FLAG_SPARSE", base.HEX, nil, 0x10,"if not set buffer len is assumed as DESSERT_MAXFRAMELEN + DESSERT_MSGPROCLEN ") f.flags_6 = ProtoField.uint8 ("dessert.flags_6", "Flag 6", base.HEX, nil, 0x20) f.flags_7 = ProtoField.uint8 ("dessert.flags_7", "Flag 7", base.HEX, nil, 0x40) f.flags_8 = ProtoField.uint8 ("dessert.flags_8", "Flag 8", base.HEX, nil, 0x80) f.u32 = ProtoField.uint32 ("dessert.u32", "u32", base.HEX ,nil) f.ttl = ProtoField.uint8 ("dessert.ttl", "ttl", base.DEC ,nil) f.u8 = ProtoField.uint8 ("dessert.u8", "u8", base.HEX ,nil) f.u16 = ProtoField.uint16 ("dessert.u16", "u16", base.HEX, nil) f.hlen = ProtoField.uint16 ("dessert.hlen", "Header length hlen (incl. layer 2.5)", base.DEC, nil,nil,"header length incl. extensions") f.plen = ProtoField.uint16 ("dessert.plen", "Payload length plen", base.DEC, nil) f.exts = ProtoField.string ("dessert.exts", "Extensions") EXTHDR = Proto("dessert_ext", "DESSERT_EXT"); local e = EXTHDR.fields e.exttype = ProtoField.uint8 ("dessert.ext.type", "Extension type", base.HEX ) e.extlen = ProtoField.uint8 ("dessert.ext.len", "Extension length (incl. extension header)", base.DEC ,nil,nil, "length of the extension in bytes, including the 2 bytes of the extension header itself") -- The dissector function function DESSERT.dissector(buffer, pinfo, tree) pinfo.cols.protocol = "DES-SERT" local subtree = tree:add(DESSERT, buffer(),"DES-SERT Protocol Data") local offset = 0 local proto = buffer (offset, 4) subtree:add(f.proto, proto) offset = offset + 4 local version= buffer (offset, 1) subtree:add(f.version, version) offset = offset + 1 local flags = buffer (offset, 1) local flags_field = subtree:add(f.flags, flags) flags_field:add(f.flags_1, flags) flags_field:add(f.flags_2, flags) flags_field:add(f.flags_3, flags) flags_field:add(f.flags_4, flags) flags_field:add(f.flags_5, flags) flags_field:add(f.flags_6, flags) flags_field:add(f.flags_7, flags) flags_field:add(f.flags_8, flags) offset = offset + 1 local u32 = buffer (offset, 4) local ttl = buffer (offset, 1) local u8 = buffer (offset+1, 1) local u16 = buffer (offset+2, 2) local u32_field = subtree:add(f.u32, u32) u32_field:add(f.ttl, ttl) u32_field:add(f.u8 , u8) u32_field:add(f.u16, u16) offset = offset + 4 local hlen = buffer(offset,2) subtree:add(f.hlen, hlen) offset = offset + 2 -- because wireshark already dissected the layer 2.5 header at this point -- the *real* header length is hlen-14 local real_hlen = hlen:uint() - 14 local plen = buffer(offset,2) subtree:add(f.plen, plen) offset = offset + 2 extensions = subtree:add(f.exts) local extension, exttype, extlen, extdata_real_length, extdata, exttreeitem, dissector local ext_count = 0 while offset < real_hlen do ext_count = ext_count +1 extension = extensions:add(EXTHDR) extension:set_generated() exttype = buffer(offset, 1) extension:add(e.exttype, exttype) offset = offset + 1 extlen = buffer(offset, 1) extension:add(e.extlen, extlen) offset = offset + 1 -- extlen includes the 2byte extension header ! extdata_real_length = extlen:uint() - 2 extdata = buffer(offset, extdata_real_length) local dissector = dessert_dissector_table:get_dissector(exttype:uint()) if dissector ~= nil then dissector:call(extdata:tvb(), pinfo, extension) length_dissected = _G.g_offset ethertype = _G.g_ethertype if length_dissected ~= extdata_real_length then print("\t\t\tWarning: Sub-Dissector did not consume all bytes!") end else print("\t\t\tWarning: No extension_dissector for ext_type: "..tostring(extension_types[exttype:uint()])) end offset = offset + extdata_real_length -- print("\t\toffset="..tostring(offset)..", hlen="..tostring(real_hlen)) end -- print("\tno more extensions, offset="..tostring(offset)) -- dissect paylod based on ext_eth ethertype if any ethertype = _G.g_ethertype if ethertype:uint() ~= 0 then local dissector = ethertype_table:get_dissector(ethertype:uint()) if dissector ~= nil then local payload = buffer(offset, plen:uint()) dissector:call(payload:tvb(), pinfo, tree) else print("Warning: Payload found but no matching dissector") end end return offset end -- load the ethertype table ethertype_table = DissectorTable.get("ethertype") -- register DES-SERT protocol to handle ethertype 0x88B5 ethertype_table:add(0x88B5, DESSERT) print("DES-SERT dissector loaded")
gpl-3.0
eyalsk-wowaddons/AwesomeTweaks
libs/Libra/Slider.lua
1
1718
local Libra = LibStub("Libra") local Type, Version = "Slider", 2 if Libra:GetModuleVersion(Type) >= Version then return end local backdrop = { bgFile = [[Interface\Buttons\UI-SliderBar-Background]], edgeFile = [[Interface\Buttons\UI-SliderBar-Border]], edgeSize = 8, insets = {left = 3, right = 3, top = 6, bottom = 6} } local function onEnter(self) if self:IsEnabled() then if self.tooltipText then GameTooltip:SetOwner(self, self.tooltipOwnerPoint or "ANCHOR_RIGHT") GameTooltip:SetText(self.tooltipText, nil, nil, nil, nil, true) end if self.tooltipRequirement then GameTooltip:AddLine(self.tooltipRequirement, 1.0, 1.0, 1.0) GameTooltip:Show() end end end local function onLeave(self) GameTooltip:Hide() end local function constructor(self, parent) local slider = CreateFrame("Slider", nil, parent) slider:SetSize(144, 17) slider:SetBackdrop(backdrop) slider:SetThumbTexture([[Interface\Buttons\UI-SliderBar-Button-Horizontal]]) slider:SetOrientation("HORIZONTAL") slider:SetObeyStepOnDrag(true) slider:SetScript("OnEnter", onEnter) slider:SetScript("OnLeave", onLeave) slider.label = slider:CreateFontString(nil, nil, "GameFontNormal") slider.label:SetPoint("BOTTOM", slider, "TOP") slider.min = slider:CreateFontString(nil, nil, "GameFontHighlightSmall") slider.min:SetPoint("TOPLEFT", slider, "BOTTOMLEFT", -4, 3) slider.max = slider:CreateFontString(nil, nil, "GameFontHighlightSmall") slider.max:SetPoint("TOPRIGHT", slider, "BOTTOMRIGHT", 4, 3) slider.currentValue = slider:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") slider.currentValue:SetPoint("CENTER", 0, -15) return slider end Libra:RegisterModule(Type, Version, constructor)
mit
eku/nodemcu-firmware
lua_modules/email/imap.lua
7
6297
--- -- Working Example: https://www.youtube.com/watch?v=PDxTR_KJLhc -- IMPORTANT: run node.compile("imap.lua") after uploading this script -- to create a compiled module. Then run file.remove("imap.lua") -- @name imap -- @description An IMAP 4rev1 module that can be used to read email. -- Tested on NodeMCU 0.9.5 build 20150213. -- @date March 12, 2015 -- @author Miguel -- GitHub: https://github.com/AllAboutEE -- YouTube: https://www.youtube.com/user/AllAboutEE -- Website: http://AllAboutEE.com -- -- Visit the following URLs to learn more about IMAP: -- "How to test an IMAP server by using telnet" http://www.anta.net/misc/telnet-troubleshooting/imap.shtml -- "RFC 2060 - Internet Message Access Protocol - Version 4rev1" http://www.faqs.org/rfcs/rfc2060.html ------------------------------------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M local USERNAME = "" local PASSWORD = "" local TAG = "" local DEBUG = false local body = "" -- used to store an email's body / main text local header = "" -- used to store an email's last requested header field e.g. SUBJECT, FROM, DATA etc. local most_recent_num = 1 -- used to store the latest/newest email number/id local response_processed = false -- used to know if the last IMAP response has been processed --- -- @name response_processed -- @returns The response process status of the last IMAP command sent function M.response_processed() return response_processed end --- -- @name display -- @description A generic IMAP response processing function. -- Can display the IMAP response if DEBUG is set to true. -- Sets the response processed variable to true when the string "complete" -- is found in the IMAP reply/response local function display(socket, response) -- luacheck: no unused -- If debuggins is enabled print the IMAP response if(DEBUG) then print(response) end -- Some IMAP responses are long enough that they will cause the display -- function to be called several times. One thing is certain, IMAP will replay with -- "<tag> OK <command> complete" when it's done sending data back. if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name config -- @description Initiates the IMAP settings function M.config(username, password, tag, debug) USERNAME = username PASSWORD = password TAG = tag DEBUG = debug end --- -- @name login -- @descrpiton Logs into a new email session function M.login(socket) response_processed = false -- we are sending a new command -- which means that the response for it has not been processed socket:send(TAG .. " LOGIN " .. USERNAME .. " " .. PASSWORD .. "\r\n") socket:on("receive",display) end --- -- @name get_most_recent_num -- @returns The most recent email number. Should only be called after examine() function M.get_most_recent_num() return most_recent_num end --- -- @name set_most_recent_num -- @description Gets the most recent email number from the EXAMINE command. -- i.e. if EXAMINE returns "* 4 EXISTS" this means that there are 4 emails, -- so the latest/newest will be identified by the number 4 local function set_most_recent_num(socket, response) -- luacheck: no unused if(DEBUG) then print(response) end local _, _, num = string.find(response,"([0-9]+) EXISTS") -- the _ and _ keep the index of the string found -- but we don't care about that. if(num~=nil) then most_recent_num = num end if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name examine -- @description IMAP examines the given mailbox/folder. Sends the IMAP EXAMINE command function M.examine(socket, mailbox) response_processed = false socket:send(TAG .. " EXAMINE " .. mailbox .. "\r\n") socket:on("receive",set_most_recent_num) end --- -- @name get_header -- @returns The last fetched header field function M.get_header() return header end --- -- @name set_header -- @description Records the IMAP header field response in a variable -- so that it may be read later local function set_header(socket, response) -- luacheck: no unused if(DEBUG) then print(response) end header = header .. response if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name fetch_header -- @description Fetches an emails header field e.g. SUBJECT, FROM, DATE -- @param socket The IMAP socket to use -- @param msg_number The email number to read e.g. 1 will read fetch the latest/newest email -- @param field A header field such as SUBJECT, FROM, or DATE function M.fetch_header(socket, msg_number, field) header = "" -- we are getting a new header so clear this variable response_processed = false socket:send(TAG .. " FETCH " .. msg_number .. " BODY[HEADER.FIELDS (" .. field .. ")]\r\n") socket:on("receive",set_header) end --- -- @name get_body -- @return The last email read's body function M.get_body() return body end --- -- @name set_body -- @description Records the IMAP body response in a variable -- so that it may be read later local function set_body(_, response) if(DEBUG) then print(response) end body = body .. response if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name fetch_body_plain_text -- @description Sends the IMAP command to fetch a plain text version of the email's body -- @param socket The IMAP socket to use -- @param msg_number The email number to obtain e.g. 1 will obtain the latest email function M.fetch_body_plain_text(socket, msg_number) response_processed = false body = "" -- clear the body variable since we'll be fetching a new email socket:send(TAG .. " FETCH " .. msg_number .. " BODY[1]\r\n") socket:on("receive",set_body) end --- -- @name logout -- @description Sends the IMAP command to logout of the email session function M.logout(socket) response_processed = false socket:send(TAG .. " LOGOUT\r\n") socket:on("receive",display) end
mit
joeyhng/nn
Bottle.lua
6
2537
local Bottle, parent = torch.class("nn.Bottle", "nn.Container") local unpack = unpack or table.unpack function Bottle:__init(module, nInputDim, nOutputDim) parent.__init(self) self.nInputDim = nInputDim or 2 self.nOutputDim = nOutputDim or self.nInputDim self.dimDelta = self.nInputDim - self.nOutputDim -- Used to reshape the gradients self.inShape = torch.Tensor(self.nInputDim) self.outShape = torch.Tensor(self.nOutputDim) -- add module to modules self.modules[1] = module end function Bottle:updateOutput(input) -- first batchDims dimensions will be fused local batchDims = input:dim() - self.nInputDim + 1 -- see if bottle is required if batchDims > 1 then -- bottle the first dims local inSize = torch.LongTensor(input:size()) local squeezeSize = inSize[{{1, batchDims - 1}}]:prod() self.inShape:copy(inSize[{{batchDims, input:dim()}}]) self.inShape[{{1}}]:mul(squeezeSize) -- Forward with the module's dimension local newInput = input:view(unpack(self.inShape:totable())) local output = self.modules[1]:updateOutput(newInput) assert(output:dim() == self.nOutputDim, "Wrong number of output dims on module. Expected: " .. self.nOutputDim .. ' but got ' .. tostring(output and output:dim())) self.outShape:copy(torch.LongTensor(output:size())) if math.abs(self.dimDelta) > 0 then inSize:resize(inSize:size(1) - self.dimDelta) end inSize[{{batchDims, inSize:size(1)}}]:copy(self.outShape) inSize[{{batchDims}}]:div(squeezeSize) -- unbottle self.output:set(output:view(unpack(torch.totable(inSize)))) else self.output:set(self.modules[1]:updateOutput(input)) end return self.output end function Bottle:updateGradInput(input, gradOutput) if input:dim() > self.nInputDim then local input_ = input:view(unpack(self.inShape:totable())) local gradOutput_ = gradOutput:view(unpack(self.outShape:totable())) self.modules[1]:updateGradInput(input_, gradOutput_) self.gradInput:set(self.modules[1].gradInput:viewAs(input)) else self.gradInput:set(self.modules[1]:updateGradInput(input)) end return self.gradInput end function Bottle:accGradParameters(input, gradOutput, scale) if input:dim() > self.nInputDim then input = input:view(unpack(self.inShape:totable())) gradOutput = gradOutput:view(unpack(self.outShape:totable())) end self.modules[1]:accGradParameters(input, gradOutput, scale) end
bsd-3-clause
asamy45/forgottenmapeditor
modules/corelib/ui/uispinbox.lua
1
3539
-- @docclass UISpinBox = extends(UITextEdit) function UISpinBox.create() local spinbox = UISpinBox.internalCreate() spinbox:setFocusable(false) spinbox:setValidCharacters('0123456789') spinbox.displayButtons = true spinbox.minimum = 0 spinbox.maximum = 0 spinbox.value = 0 spinbox.step = 1 spinbox.firstchange = true spinbox:setText("0") return spinbox end function UISpinBox:onSetup() g_mouse.bindAutoPress(self:getChildById('up'), function() self:up() end, 300) g_mouse.bindAutoPress(self:getChildById('down'), function() self:down() end, 300) end function UISpinBox:onMouseWheel(mousePos, direction) if direction == MouseWheelUp then self:up() elseif direction == MouseWheelDown then self:down() end return true end function UISpinBox:onKeyPress() if self.firstchange then self.firstchange = false self:setText('') end return false end function UISpinBox:onTextChange(text, oldText) if text:len() == 0 then self:setValue(self.minimum) return end local number = tonumber(text) if not number then self:setText(number) return else if number < self.minimum then self:setText(self.minimum) return elseif number > self.maximum then self:setText(self.maximum) return end end self:setValue(number) end function UISpinBox:onValueChange(value) -- nothing todo end function UISpinBox:onStyleApply(styleName, styleNode) for name, value in pairs(styleNode) do if name == 'maximum' then addEvent(function() self:setMaximum(value) end) elseif name == 'minimum' then addEvent(function() self:setMinimum(value) end) elseif name == 'buttons' then addEvent(function() if value then self:showButtons() else self:hideButtons() end end) end end end function UISpinBox:showButtons() self:getChildById('up'):show() self:getChildById('down'):show() self.displayButtons = true end function UISpinBox:hideButtons() self:getChildById('up'):hide() self:getChildById('down'):hide() self.displayButtons = false end function UISpinBox:up() self:setValue(self.value + self.step) end function UISpinBox:down() self:setValue(self.value - self.step) end function UISpinBox:setValue(value) value = value or 0 value = math.max(math.min(self.maximum, value), self.minimum) if value == self.value then return end if self:getText():len() > 0 then self:setText(value) end self.value = value local upButton = self:getChildById('up') local downButton = self:getChildById('down') if upButton then upButton:setEnabled(self.maximum ~= self.minimum and self.value ~= self.maximum) end if downButton then downButton:setEnabled(self.maximum ~= self.minimum and self.value ~= self.minimum) end signalcall(self.onValueChange, self, value) end function UISpinBox:getValue() return self.value end function UISpinBox:setMinimum(minimum) minimum = minimum or -9223372036854775808 self.minimum = minimum if self.minimum > self.maximum then self.maximum = self.minimum end if self.value < minimum then self:setValue(minimum) end end function UISpinBox:getMinimum() return self.minimum end function UISpinBox:setMaximum(maximum) maximum = maximum or 9223372036854775807 self.maximum = maximum if self.value > maximum then self:setValue(maximum) end end function UISpinBox:getMaximum() return self.maximum end function UISpinBox:setStep(step) self.step = step or 1 end
mit
qj739/BadRotations
System/engines/ArtifactTable.lua
6
3716
local name, addon = ... local LAD = LibStub("LibArtifactData-1.0") br.artifact = {} function updateArtifact() local artifactId = select(1,C_ArtifactUI.GetEquippedArtifactInfo()) local _, data = LAD:GetArtifactInfo(artifactId) if br.artifact == nil then br.artifact = {} end br.artifact.id = artifactId br.artifact.info = data end function addon:ARTIFACT_ADDED() updateArtifact() end function addon:ARTIFACT_EQUIPPED_CHANGED() updateArtifact() end function addon:ARTIFACT_DATA_MISSING() updateArtifact() end function addon:ARTIFACT_RELIC_CHANGED() updateArtifact() end function addon:ARTIFACT_TRAITS_CHANGED() updateArtifact() end --New: ARTIFACT_RELIC_INFO_RECEIVED --Old: ARTIFACT_UPDATE LAD.RegisterCallback(addon, "ARTIFACT_ADDED") LAD.RegisterCallback(addon, "ARTIFACT_EQUIPPED_CHANGED") LAD.RegisterCallback(addon, "ARTIFACT_DATA_MISSING") LAD.RegisterCallback(addon, "ARTIFACT_RELIC_CHANGED") LAD.RegisterCallback(addon, "ARTIFACT_TRAITS_CHANGED") if br.artifact.info == nil then LAD.ForceUpdate() end -- checks for perk function hasPerk(spellID) if br.artifact ~= nil then if br.artifact.info ~= nil then if br.artifact.info.traits ~= nil then for i=1, #br.artifact.info.traits do if spellID == br.artifact.info.traits[i]["spellID"] then return true end end end end end return false end -- checkes for perk rank function getPerkRank(spellID) if br.artifact ~= nil then if br.artifact.info ~= nil then if br.artifact.info.traits ~= nil then for i=1, #br.artifact.info.traits do if spellID == br.artifact.info.traits[i]["spellID"] then return br.artifact.info.traits[i]["currentRank"] end end end end end return 0 end --- end of artifact perks --- Globals related to Artifacts -- C_ArtifactUI.AcceptChanges -- C_ArtifactUI.AddPower -- C_ArtifactUI.ApplyCursorRelicToSlot -- C_ArtifactUI.CanApplyCursorRelicToSlot -- C_ArtifactUI.CanApplyRelicItemIDToEquippedArtifactSlot -- C_ArtifactUI.CanApplyRelicItemIDToSlot -- C_ArtifactUI.CheckRespecNPC -- C_ArtifactUI.Clear -- C_ArtifactUI.ClearForgeCamera -- C_ArtifactUI.ConfirmRespec -- C_ArtifactUI.GetAppearanceInfo -- C_ArtifactUI.GetAppearanceInfoByID -- C_ArtifactUI.GetAppearanceSetInfo -- C_ArtifactUI.GetArtifactArtInfo -- C_ArtifactUI.GetArtifactInfo -- C_ArtifactUI.GetArtifactKnowledgeLevel -- C_ArtifactUI.GetArtifactKnowledgeMultiplier -- C_ArtifactUI.GetArtifactXPRewardTargetInfo -- C_ArtifactUI.GetCostForPointAtRank -- C_ArtifactUI.GetEquippedArtifactArtInfo -- C_ArtifactUI.GetEquippedArtifactInfo -- C_ArtifactUI.GetEquippedArtifactNumRelicSlots -- C_ArtifactUI.GetForgeRotation -- C_ArtifactUI.GetMetaPowerInfo -- C_ArtifactUI.GetNumAppearanceSets -- C_ArtifactUI.GetNumRelicSlots -- C_ArtifactUI.GetPointsRemaining -- C_ArtifactUI.GetPowerInfo -- C_ArtifactUI.GetPowerLinks -- C_ArtifactUI.GetPowers -- C_ArtifactUI.GetPowersAffectedByRelic -- C_ArtifactUI.GetPowersAffectedByRelicItemID -- C_ArtifactUI.GetPreviewAppearance -- C_ArtifactUI.GetRelicInfo -- C_ArtifactUI.GetRelicInfoByItemID -- C_ArtifactUI.GetRelicSlotType -- C_ArtifactUI.GetRespecArtifactArtInfo -- C_ArtifactUI.GetRespecArtifactInfo -- C_ArtifactUI.GetRespecCost -- C_ArtifactUI.GetTotalPurchasedRanks -- C_ArtifactUI.IsAtForge -- C_ArtifactUI.IsPowerKnown -- C_ArtifactUI.IsViewedArtifactEquipped -- C_ArtifactUI.SetAppearance -- C_ArtifactUI.SetForgeCamera -- C_ArtifactUI.SetForgeRotation -- C_ArtifactUI.SetPreviewAppearance
gpl-3.0
Rydra/OpenRA
mods/common/lua/actor.lua
1
5869
Actor = { } Actor.Create = function(name, init) if name == nil then error("No actor name specified", 2) end if init.Owner == nil then error("No actor owner specified", 2) end local td = OpenRA.New("TypeDictionary") local addToWorld = true for key, value in pairs(init) do if key == "AddToWorld" then addToWorld = value else td:Add(OpenRA.New(key .. "Init", { value })) end end return World:CreateActor(addToWorld, name, td) end Actor.Turn = function(actor, facing) actor:QueueActivity(OpenRA.New("Turn", { { facing, "Int32" } })) end Actor.Move = function(actor, location) Actor.MoveNear(actor, location, 0) end Actor.MoveNear = function(actor, location, nearEnough) actor:QueueActivity(OpenRA.New("Move", { location, WRange.FromCells(nearEnough) })) end Actor.ScriptedMove = function(actor, location) if Actor.HasTrait(actor, "Helicopter") then Internal.HeliFlyToPos(actor, location.CenterPosition) else actor:QueueActivity(OpenRA.New("Move", { location })) end end Actor.AfterMove = function(actor) local heli = Actor.TraitOrDefault(actor, "Helicopter") if heli ~= nil then Actor.Turn(actor, heli.Info.InitialFacing) Actor.HeliLand(actor, true) end end Actor.Teleport = function(actor, location) actor:QueueActivity(OpenRA.New("SimpleTeleport", { location })) end Actor.AttackMove = function(actor, location, nearEnough) Internal.AttackMove(actor, location, nearEnough or 0) end Actor.HeliFly = function(actor, position) Internal.HeliFlyToPos(actor, position) end Actor.HeliLand = function(actor, requireSpace) actor:QueueActivity(OpenRA.New("HeliLand", { requireSpace })) end Actor.Fly = function(actor, position) Internal.FlyToPos(actor, position) end Actor.FlyAttackActor = function(actor, targetActor) Internal.FlyAttackActor(actor, targetActor) end Actor.FlyAttackCell = function(actor, location) Internal.FlyAttackCell(actor, location) end Actor.FlyOffMap = function(actor) actor:QueueActivity(OpenRA.New("FlyOffMap")) end Actor.Hunt = function(actor) if Actor.HasTrait(actor, "AttackBase") and Actor.HasTrait(actor, "IMove") then actor:QueueActivity(OpenRA.New("Hunt", { actor })) end end Actor.CargoIsEmpty = function(actor) local cargo = Actor.TraitOrDefault(actor, "Cargo") return cargo == nil or cargo:IsEmpty(actor) end Actor.UnloadCargo = function(actor, unloadAll) actor:QueueActivity(OpenRA.New("UnloadCargo", { actor, unloadAll })) end Actor.Harvest = function(actor) actor:QueueActivity(OpenRA.New("FindResources")) end Actor.Scatter = function(actor) local mobile = Actor.Trait(actor, "Mobile") mobile:Nudge(actor, actor, true) end Actor.Wait = function(actor, period) actor:QueueActivity(OpenRA.New("Wait", { { period, "Int32" } })) end Actor.WaitFor = function(actor, func) Internal.WaitFor(actor, func) end Actor.CallFunc = function(actor, func) Internal.CallFunc(actor, func) end Actor.DeployTransform = function(actor) Actor.CallFunc(actor, function() -- Queue the transform order Actor.Trait(actor, "Transforms"):DeployTransform(true) end) end Actor.RemoveSelf = function(actor) actor:QueueActivity(OpenRA.New("RemoveSelf")) end Actor.Stop = function(actor) actor:CancelActivity() end Actor.IsDead = function(actor) return Internal.IsDead(actor) end Actor.IsInWorld = function(actor) return actor.IsInWorld end Actor.Owner = function(actor) return actor.Owner end Actor.Facing = function(actor) return Actor.Trait(actor, "IFacing"):get_Facing() end Actor.IsIdle = function(actor) return actor.IsIdle end Actor.SetStance = function(actor, stance) Internal.SetUnitStance(actor, stance) end Actor.RepairBuilding = function(actor) local rb = Actor.TraitOrDefault(actor, "RepairableBuilding") if rb ~= nil and rb.Repairer == nil then rb:RepairBuilding(actor, Actor.Owner(actor)) end end Actor.OnDamaged = function(actor, eh) Actor.Trait(actor, "LuaScriptEvents").OnDamaged:Add(eh) end Actor.OnKilled = function(actor, eh) Actor.Trait(actor, "LuaScriptEvents").OnKilled:Add(eh) end Actor.OnAddedToWorld = function(actor, eh) Actor.Trait(actor, "LuaScriptEvents").OnAddedToWorld:Add(eh) end Actor.OnRemovedFromWorld = function(actor, eh) Actor.Trait(actor, "LuaScriptEvents").OnRemovedFromWorld:Add(eh) end Actor.OnCaptured = function(actor, eh) Actor.Trait(actor, "LuaScriptEvents").OnCaptured:Add(eh) end Actor.OnIdle = function(actor, eh) Actor.Trait(actor, "LuaScriptEvents").OnIdle:Add(eh) end Actor.OnProduced = function(actor, eh) Actor.Trait(actor, "LuaScriptEvents").OnProduced:Add(eh) end Actor.ActorsWithTrait = function(className) local ret = { } for item in Utils.Enumerate(Internal.ActorsWithTrait(className)) do table.insert(ret, item.Actor) end return ret end Actor.HasTrait = function(actor, className) return Internal.HasTrait(actor, className) end Actor.TraitOrDefault = function(actor, className) return Internal.TraitOrDefault(actor, className) end Actor.Trait = function(actor, className) return Internal.Trait(actor, className) end Actor.ReturnToBase = function(actor, airfield) actor:QueueActivity(OpenRA.New("ReturnToBase", { actor, airfield })) end Actor.Guard = function(actor, target) Internal.Guard(actor, target) end Actor.Patrol = function(actor, waypoints, wait, loop) if not Actor.IsDead(actor) then Utils.Do(waypoints, function(wpt) Actor.AttackMove(actor, wpt.Location, 3) Actor.Wait(actor, wait or 0) end) if loop or loop == nil then Actor.CallFunc(actor, function() Actor.Patrol(actor, waypoints, wait, loop) end) end end end Actor.PatrolUntil = function(actor, waypoints, wait, func) if func == nil then error("No function specified", 2) end if not Actor.IsDead(actor) then Actor.Patrol(actor, waypoints, wait, false) if not func(actor) then Actor.CallFunc(actor, function() Actor.PatrolUntil(actor, waypoints, wait, func) end) end end end
gpl-3.0
micahmumper/naev
dat/missions/sirius/heretic/heretic2.lua
9
7850
--[[misn title - the patrol]] --[[in this mission, the player will be guarding the "high command" of the nasin, the wringer/suna. house sirius is sending in recon parties. the players job is to take out any and all sirius in the system.]] include "dat/scripts/numstring.lua" lang = naev.lang() bmsg = {} --beginning messages bmsg[1] = [[You walk up to an intimidating man dressed smartly in cool, dark black business attire. He has a large smile spread across his face. "Ahh, so your the %s everyone has been talking about. Naught but a glorified delivery boy if you ask me. Still, if you wish to help us out and prove yourself as more than a pirate, I'd be more than happy to oblige." He grins cooly, expecting an answer.]] bmsg[2] = [[Draga snorts impatiently. "Well, do you take the mission or what?"]] choice = {} choice[1] = "Tell me more about the Nasin." choice[2] = "What's the job?" choice[3] = "I'm in. Where do I sign up?" choice[4] = "Sounds risky. Give me some time." chooser = {} chooser[1] = [[He looks at you, betraying a little emotion. "The Nasin are a pure piece of glass. When light shines through glass, the light is only as pure as the glass itself. If the glass is dirty, then the light is distorted, and doesn't come through correctly. If the glass is mishappen or broken, the light may not filter through at all. We, the Nasin, are the purest glass there is, and House Sirius has become corrupt. We exist to see its downfall."]] chooser[2] = [[Draga motions you in closer. "We have reason to believe that %s is about to be attacked. We are expecting Sirius to send in recon elements any STU now. We want you to handle that, as you see fit. Keep them away from the station. Better yet, kill them. We can pay you %s. We do ask that you stay in-system and off-planet until the mission is complete, otherwise you'll be considered AWOL, which means you're fired."]] chooser[3] = [[Draga looks triumphant, but only for an instant. "Great. You should get going, we are expecting them at any second. Good luck, and godspeed."]] chooser[4] = [[You brace yourself, as Draga appears ready to attack. He waves his arms about in obvious anger. "Great! I knew you were a waste of time. Well, if you decide to outgrow your diapers, I'll be right here waiting for you." You walk away insulted, but strangely curious.]] --message at the end emsg_1 = [[You land, having destroyed the small recon force. Draga is in the hangar, waiting for you. "Good job on proving yourself more than a delivery boy! That wasn't so bad, was it? Here's your payment, meet me in the bar soon."]] --mission osd osd = {} osd[1] = "Destroy the Sirius fighter element." osd[2] = "Element destroyed. Land on %s." --random odds and ends misn_title = "The Patrol" npc_name = "Draga" bar_desc = "An imposing man leans against the bar easily, looking right at you." not_finished = "Draga seems to swoop in out of nowhere as soon as you land. \"You are not finished! Get back up there quickly!\"" chronic_failure = [[Draga swoops in. His nostrils are flaring, and he is obviously annoyed. "Apparently you have better things to do. Get out of here. I don't want to see your face anymore." You consider yourself fired.]] doom_clock_msg = [[A scratchy voice jumps in on your comms priority channel. "You jumped out of the system! We are being scanned by the enemy! We need you back to take care of this situation now, or you are AWOL and are not getting paid!!" The voice and the scratch cuts out.]] out_sys_failure_msg = [[Your comm station flares up with a scratchy, obviously-from-far-away noise. A voice is heard through it. "%s! We told you we needed you to stay in system! Apparently you have more important things to do. So get lost, kid! We'll take care of ourselves." The static cuts out, and you consider yourself fired.]] misn_desc = "Destroy the Sirius recon element that flew into %s. WARNING: DO NOT JUMP OUT-SYSTEM OR LAND ON THE PLANET PREMATURELY." function create() --this mission does make one system claim, in suna. --initialize the variables homeasset, homesys = planet.cur() if not misn.claim(homesys) then misn.finish(false) end nasin_rep = faction.playerStanding("Nasin") misn_tracker = var.peek("heretic_misn_tracker") playername = player.name() reward = math.floor((10000+(math.random(5,8)*200)*(nasin_rep^1.315))*.01+.5)/.01 chronic = 0 finished = 0 takeoff_counter = 0 draga_convo = 0 deathcount = 0 --set the mission stuff misn.setTitle(misn_title) misn.setReward(numstring(reward) .. "credits") misn.setNPC(npc_name,"neutral/thief2") misn.setDesc(bar_desc) -- Format OSD osd[2] = osd[2]:format( homeasset:name() ) misn_desc = misn_desc:format(homesys:name()) end function accept() -- Only referenced in this function. chooser[2] = chooser[2]:format(homeasset:name(), numstring(reward)) while true do --this is a slightly more complex convo than a yes no. Used break statements as the easiest way to control convo. msg = bms if first_talk == nil then --used the first talk one only the first time through. This way, the npc convo feels more natural. msg = bmsg[1]:format( player.name() ) first_talk = 1 else msg = bmsg[2] end draga_convo = tk.choice(misn_title, msg, choice[1], choice[2], choice[3], choice[4]) draga_convo = tk.choice(misn_title,bmsg[2],choice[1],choice[2],choice[3],choice[4]) if draga_convo == 1 or draga_convo == 2 then tk.msg(misn_title,chooser[draga_convo]) elseif draga_convo == 3 then tk.msg(misn_title,chooser[draga_convo]) break else tk.msg(misn_title,chooser[draga_convo] ) misn.finish() break end end misn.setDesc(misn_desc) misn.accept() misn.markerAdd(homesys,"plot") misn.osdCreate(misn_title,osd) misn.osdActive(1) hook.takeoff("takeoff") hook.jumpin("out_sys_failure") hook.land("land") end function takeoff() pilot.clear() pilot.toggleSpawn("Sirius",false) --the only sirius i want in the system currently is the recon force recon = pilot.add("Sirius Recon Force",nil,system.get("Herakin")) attackers = pilot.add("Nasin Sml Attack Fleet",nil,homeasset) --a little assistance n_recon = #recon --using a deathcounter to track success for i,p in ipairs(recon) do p:setHilight(true) p:setNoJump(true) --dont want the enemy to jump or land, which might happen if the player is slow, or neutral to Sirius. p:setNoLand(true) p:setHostile(true) end for i,p in ipairs(attackers) do p:setNoJump(true) p:setNoLand(true) p:setFriendly(true) end hook.pilot(nil,"death","death") end function death(p) for i,v in ipairs(recon) do if v == p then deathcount = deathcount + 1 end end if deathcount == n_recon then --checks if all the recon pilots are dead. misn.osdActive(2) finished = 1 end end function land() if finished ~= 1 then tk.msg(misn_title,chronic_failure) --landing pre-emptively is a bad thing. misn.osdDestroy() misn.finish(false) elseif planet.cur() == homeasset and finished == 1 then tk.msg(misn_title,emsg_1) player.pay(reward) misn_tracker = misn_tracker + 1 faction.modPlayer("Nasin",4) faction.modPlayer("Sirius",-5) misn.osdDestroy() var.push("heretic_misn_tracker",misn_tracker) misn.finish(true) end end function out_sys_failure() --jumping pre-emptively is a bad thing. if system.cur() ~= homesys then tk.msg(misn_title, out_sys_failure_msg:format( player.name() )) misn.osdDestroy() misn.finish(false) end end function abort() misn.osdDestroy() misn.finish(false) end
gpl-3.0
micahmumper/naev
dat/missions/shark/sh01_corvette.lua
1
5788
--[[ This is the second mission of the Shark's teeth campaign. The player has to take part to a fake battle. Stages : 0) Way to Toaxis 1) Battle 2) Going to Darkshed --]] include "numstring.lua" lang = naev.lang() if lang == "es" then else -- default english title = {} text = {} osd_msg = {} npc_desc = {} bar_desc = {} title[1] = "Nexus Shipyards needs you" text[1] = [[As you approach Smith, he recognizes you. "I have an other job for you. Let me explain it: the baron isn't convinced yet that the Shark is the fighter he needs. He saw your fight against the Ancestor, but he would like to see a Shark beating a destroyer class ship. Of course, Nexus Shipyards don't want to take the risk to make you face a destroyer with a Shark. So, we have an other plan: we need somebody to pretend to be an outlaw destroyer pilot and to let one of our men disable his ship. If you are ready for it, all you have to do is to jump in %s with a destroyer class ship and to let the Shark disable you. As there isn't any Empire bounty this time, you will only be paid %s credits. What do you say, are you in?" ]] refusetitle = "Sorry, not interested" refusetext = [["Ok, so never mind." Smith says.]] title[2] = "Wonderful" text[2] = [["I had no doubts you would accept," Smith says. "Go and meet our pilot in %s. After the job is done, meet me on %s in %s"]] title[3] = "Reward" text[3] = [[As you land, you see Arnold Smith who was waiting for you. He explains you that the baron was so impressed by the battle that he signed the contract. You made it possible for Nexus Shipyard to sell 20 Shark fighters. Of course, that's not a very big thing for a multi-stellar company like Nexus, but as a reward, they give you twice the sum of credits they promised to you.]] -- Mission details misn_title = "Sharkman is back" misn_reward = "%s credits" misn_desc = "Nexus Shipyards needs you to demonstrate again to Baron Sauterfeldt that a Shark is able to defend his system against pirates." -- NPC npc_desc[1] = "Arnold Smith" bar_desc[1] = [[The Nexus employee seems to be looking for pilots. Maybe he has an other task for you.]] -- OSD osd_title = "Sharkman Is Back" osd_msg[1] = "Jump in %s with a destroyer class ship and let the shark disable you" osd_msg[2] = "Go to %s in %s to collect your pay" end function create () --Change here to change the planet and the system bsyname = "Toaxis" psyname = "Alteris" pplname = "Darkshed" battlesys = system.get(bsyname) paysys = system.get(psyname) paypla = planet.get(pplname) if not misn.claim(battlesys) then misn.finish(false) end misn.setNPC(npc_desc[1], "neutral/male1") misn.setDesc(bar_desc[1]) end function accept() stage = 0 reward = 100000 if tk.yesno(title[1], text[1]:format(battlesys:name(), numstring(reward/2))) then misn.accept() tk.msg(title[2], text[2]:format(battlesys:name(), paypla:name(), paysys:name())) osd_msg[1] = osd_msg[1]:format(battlesys:name()) osd_msg[2] = osd_msg[2]:format(paypla:name(), paysys:name()) misn.setTitle(misn_title) misn.setReward(misn_reward:format(numstring(reward/2))) misn.setDesc(misn_desc) osd = misn.osdCreate(osd_title, osd_msg) misn.osdActive(1) marker = misn.markerAdd(battlesys, "low") jumpouthook = hook.jumpout("jumpout") landhook = hook.land("land") enterhook = hook.enter("enter") else tk.msg(refusetitle, refusetext) misn.finish(false) end end function jumpout() if stage == 1 then --player trying to escape misn.finish(false) end end function land() if stage == 1 then --player trying to escape misn.finish(false) end if stage == 2 and planet.cur() == paypla then tk.msg(title[3], text[3]) player.pay(reward) misn.osdDestroy(osd) hook.rm(enterhook) hook.rm(landhook) hook.rm(jumpouthook) misn.finish(true) end end function enter() playerclass = player.pilot():ship():class() --Jumping in Toaxis for the battle with a destroyer class ship if system.cur() == battlesys and stage == 0 and playerclass == "Destroyer" then -- spawns the Shark sharkboy = pilot.addRaw( "Shark","baddie", nil, "Civilian" )[1] sharkboy:setHostile() sharkboy:setHilight() --The shark becomes nice outfits sharkboy:rmOutfit("all") sharkboy:rmOutfit("cores") sharkboy:addOutfit("S&K Ultralight Combat Plating") sharkboy:addOutfit("Milspec Prometheus 2203 Core System") sharkboy:addOutfit("Tricon Zephyr Engine") sharkboy:addOutfit("Reactor Class I",2) sharkboy:addOutfit("Battery",2) sharkboy:addOutfit("Ion Cannon",3)-- The goal is to disable the player --Giving him full shield and full energy sharkboy:setHealth(100,100) sharkboy:setEnergy(100) stage = 1 hook.pilot( sharkboy, "death", "shark_dead" ) hook.pilot( sharkboy, "jump", "shark_jump" ) hook.pilot( player.pilot(), "disable", "disabled" ) end end function shark_dead() --you killed the shark misn.finish(false) end function shark_jump() --the shark jumped away before having disabled the player if stage == 1 then misn.finish(false) end end function disabled(pilot, attacker) if attacker == sharkboy then stage = 2 misn.osdActive(2) misn.markerRm(marker) marker2 = misn.markerAdd(paysys, "low") end sharkboy:control() sharkboy:runaway(player.pilot()) --otherwise, the shark will try to destroy the player's ship end
gpl-3.0
maikerumine/nuclear_holocaust
mods/roadvalleys/init.lua
2
10297
-- Parameters local DEBUG = true -- Mapgen valleys noises local np_terrain_height = { offset = -10, scale = 50, spread = {x = 1024, y = 1024, z = 1024}, seed = 5202, octaves = 6, persist = 0.4, lacunarity = 2.0, } local np_valley_depth = { offset = 5, scale = 4, spread = {x = 512, y = 512, z = 512}, seed = -1914, octaves = 1, persist = 0.0, lacunarity = 2.0, } -- Mod noises -- 2D noise for patha local np_patha = { offset = 0, scale = 1, spread = {x = 1024, y = 1024, z = 1024}, seed = 11711, octaves = 3, persist = 0.4 } -- 2D noise for pathb local np_pathb = { offset = 0, scale = 1, spread = {x = 2048, y = 2048, z = 2048}, seed = 8017, octaves = 4, persist = 0.4 } -- 2D noise for pathc local np_pathc = { offset = 0, scale = 1, spread = {x = 4096, y = 4096, z = 4096}, seed = 300707, octaves = 5, persist = 0.4 } -- 2D noise for pathd local np_pathd = { offset = 0, scale = 1, spread = {x = 8192, y = 8192, z = 8192}, seed = 80033, octaves = 6, persist = 0.4 } -- Do files dofile(minetest.get_modpath("roadvalleys") .. "/nodes.lua") -- Constants local c_roadblack = minetest.get_content_id("roadvalleys:road_black") local c_roadslab = minetest.get_content_id("roadvalleys:road_black_slab") local c_roadwhite = minetest.get_content_id("roadvalleys:road_white") local c_concrete = minetest.get_content_id("roadvalleys:concrete") local c_air = minetest.CONTENT_AIR local c_ignore = minetest.CONTENT_IGNORE local c_stone = minetest.get_content_id("default:stone") local c_sastone = minetest.get_content_id("default:sandstone") local c_destone = minetest.get_content_id("default:desert_stone") local c_ice = minetest.get_content_id("default:ice") local c_tree = minetest.get_content_id("default:tree") local c_leaves = minetest.get_content_id("default:leaves") local c_apple = minetest.get_content_id("default:apple") local c_jungletree = minetest.get_content_id("default:jungletree") local c_jungleleaves = minetest.get_content_id("default:jungleleaves") local c_pinetree = minetest.get_content_id("default:pine_tree") local c_pineneedles = minetest.get_content_id("default:pine_needles") local c_snow = minetest.get_content_id("default:snow") local c_acaciatree = minetest.get_content_id("default:acacia_tree") local c_acacialeaves = minetest.get_content_id("default:acacia_leaves") local c_aspentree = minetest.get_content_id("default:aspen_tree") local c_aspenleaves = minetest.get_content_id("default:aspen_leaves") local c_meselamp = minetest.get_content_id("default:meselamp") -- Initialise noise objects to nil local nobj_terrain_height = nil local nobj_valley_depth = nil local nobj_patha = nil local nobj_pathb = nil local nobj_pathc = nil local nobj_pathd = nil -- Localise noise buffers local nbuf_terrain_height = {} local nbuf_valley_depth = {} local nbuf_patha = {} local nbuf_pathb = {} local nbuf_pathc = {} local nbuf_pathd = {} -- Localise data buffer local dbuf = {} -- On generated function minetest.register_on_generated(function(minp, maxp, seed) if minp.y > 0 or maxp.y < 0 then return end local t1 = os.clock() local x1 = maxp.x local y1 = maxp.y local z1 = maxp.z local x0 = minp.x local y0 = minp.y local z0 = minp.z local sidelen = x1 - x0 + 1 local emerlen = sidelen + 32 local overlen = sidelen + 9 local pmapdims = {x = overlen, y = overlen, z = 1} local pmapminp = {x = x0 - 5, y = z0 - 5} nobj_terrain_height = nobj_terrain_height or minetest.get_perlin_map(np_terrain_height, pmapdims) nobj_valley_depth = nobj_valley_depth or minetest.get_perlin_map(np_valley_depth, pmapdims) nobj_patha = nobj_patha or minetest.get_perlin_map(np_patha, pmapdims) nobj_pathb = nobj_pathb or minetest.get_perlin_map(np_pathb, pmapdims) nobj_pathc = nobj_pathc or minetest.get_perlin_map(np_pathc, pmapdims) nobj_pathd = nobj_pathd or minetest.get_perlin_map(np_pathd, pmapdims) local nvals_terrain_height = nobj_terrain_height:get2dMap_flat(pmapminp, nbuf_terrain_height) local nvals_valley_depth = nobj_valley_depth:get2dMap_flat(pmapminp, nbuf_valley_depth) local nvals_patha = nobj_patha:get2dMap_flat(pmapminp, nbuf_patha) local nvals_pathb = nobj_pathb:get2dMap_flat(pmapminp, nbuf_pathb) local nvals_pathc = nobj_pathc:get2dMap_flat(pmapminp, nbuf_pathc) local nvals_pathd = nobj_pathd:get2dMap_flat(pmapminp, nbuf_pathd) local vm, emin, emax = minetest.get_mapgen_object("voxelmanip") local area = VoxelArea:new{MinEdge = emin, MaxEdge = emax} local data = vm:get_data(dbuf) local ni = 1 for z = z0 - 5, z1 + 4 do local n_xprepatha = nil local n_xprepathb = nil local n_xprepathc = nil local n_xprepathd = nil -- x0 - 5, z0 - 5 is to setup initial values of 'xprepath_', 'zprepath_' for x = x0 - 5, x1 + 4 do local n_patha = nvals_patha[ni] local n_zprepatha = nvals_patha[(ni - overlen)] local n_pathb = nvals_pathb[ni] local n_zprepathb = nvals_pathb[(ni - overlen)] local n_pathc = nvals_pathc[ni] local n_zprepathc = nvals_pathc[(ni - overlen)] local n_pathd = nvals_pathd[ni] local n_zprepathd = nvals_pathd[(ni - overlen)] if x >= x0 - 4 and z >= z0 - 4 then local n_terrain_height = nvals_terrain_height[ni] local n_valley_depth = nvals_valley_depth[ni] -- *** math.floor() fixes scattered bridge elements bug *** local tlevel = math.floor(n_terrain_height + (n_valley_depth * n_valley_depth)) -- Add 6 to terrain level so that bridges pass over rivers local pathy = math.min(math.max(tlevel + 6, 7), 42) if (n_patha >= 0 and n_xprepatha < 0) -- detect sign change of noise or (n_patha < 0 and n_xprepatha >= 0) or (n_patha >= 0 and n_zprepatha < 0) or (n_patha < 0 and n_zprepatha >= 0) or (n_pathb >= 0 and n_xprepathb < 0) or (n_pathb < 0 and n_xprepathb >= 0) or (n_pathb >= 0 and n_zprepathb < 0) or (n_pathb < 0 and n_zprepathb >= 0) or (n_pathc >= 0 and n_xprepathc < 0) or (n_pathc < 0 and n_xprepathc >= 0) or (n_pathc >= 0 and n_zprepathc < 0) or (n_pathc < 0 and n_zprepathc >= 0) or (n_pathd >= 0 and n_xprepathd < 0) or (n_pathd < 0 and n_xprepathd >= 0) or (n_pathd >= 0 and n_zprepathd < 0) or (n_pathd < 0 and n_zprepathd >= 0) then -- scan disk 5 nodes above path local tunnel = false local excatop for zz = z - 4, z + 4 do local vi = area:index(x - 4, pathy + 5, zz) for xx = x - 4, x + 4 do local nodid = data[vi] if nodid == c_stone or nodid == c_destone or nodid == c_sastone or nodid == c_ice then tunnel = true end vi = vi + 1 end end if tunnel then excatop = pathy + 5 else excatop = y1 end -- place path node brush local vi = area:index(x, pathy, z) data[vi] = c_roadwhite for k = -4, 4 do local vi = area:index(x - 4, pathy, z + k) for i = -4, 4 do local radsq = (math.abs(i)) ^ 2 + (math.abs(k)) ^ 2 if radsq <= 13 then local nodid = data[vi] if nodid ~= c_roadwhite then data[vi] = c_roadblack end elseif radsq <= 25 then local nodid = data[vi] if nodid ~= c_roadblack and nodid ~= c_roadwhite then data[vi] = c_roadslab end end vi = vi + 1 end end -- foundations or bridge structure for k = -4, 4 do local vi = area:index(x - 4, pathy - 1, z + k) for i = -4, 4 do local radsq = (math.abs(i)) ^ 2 + (math.abs(k)) ^ 2 if radsq <= 25 then local nodid = data[vi] if nodid ~= c_roadblack and nodid ~= c_roadwhite and nodid ~= c_roadslab then data[vi] = c_concrete end end if radsq <= 2 then local viu = vi - emerlen local nodid = data[viu] if nodid ~= c_roadblack and nodid ~= c_roadwhite and nodid ~= c_roadslab then data[viu] = c_concrete end end vi = vi + 1 end end -- bridge columns if math.random() <= 0.0625 then for xx = x - 1, x + 1 do for zz = z - 1, z + 1 do local vi = area:index(xx, pathy - 3, zz) for y = pathy - 3, y0 - 16, -1 do local nodid = data[vi] if nodid == c_stone or nodid == c_destone or nodid == c_sastone then break else data[vi] = c_concrete end vi = vi - emerlen end end end end -- excavate above path for y = pathy + 1, excatop do for zz = z - 4, z + 4 do local vi = area:index(x - 4, y, zz) for xx = x - 4, x + 4 do local nodid = data[vi] if tunnel and y == excatop then -- tunnel ceiling if nodid ~= c_air and nodid ~= c_ignore and nodid ~= c_meselamp then if (math.abs(zz - z) == 4 or math.abs(xx - x) == 4) and math.random() <= 0.2 then data[vi] = c_meselamp else data[vi] = c_concrete end end elseif y <= pathy + 5 then if nodid ~= c_roadblack and nodid ~= c_roadslab and nodid ~= c_roadwhite then data[vi] = c_air end elseif nodid == c_tree or nodid == c_leaves or nodid == c_apple or nodid == c_jungletree or nodid == c_jungleleaves or nodid == c_pinetree or nodid == c_pineneedles or nodid == c_snow or nodid == c_acaciatree or nodid == c_acacialeaves or nodid == c_aspentree or nodid == c_aspenleaves then data[vi] = c_air end vi = vi + 1 end end end end end n_xprepatha = n_patha n_xprepathb = n_pathb n_xprepathc = n_pathc n_xprepathd = n_pathd ni = ni + 1 end end vm:set_data(data) vm:set_lighting({day = 0, night = 0}) vm:calc_lighting() vm:write_to_map(data) local chugent = math.ceil((os.clock() - t1) * 1000) if DEBUG then print ("[roadvalleys] "..chugent.." ms") end end)
lgpl-2.1
EagleTeam/EST-GP
plugins/menu.lua
1
10394
local config = require 'config' local misc = require 'utilities'.misc local roles = require 'utilities'.roles local api = require 'methods' local plugin = {} local function get_button_description(key) if key == 'Reports' then -- TRANSLATORS: these strings should be shorter than 200 characters return _("When enabled, users will be able to report messages with the @admin command") elseif key == 'Goodbye' then return _("Enable or disable the goodbye message. Can't be sent in large groups") elseif key == 'Welcome' then return _("Enable or disable the welcome message") elseif key == 'Silent' then return _("When enabled, the bot doesn't answer in the group to /dashboard, /config and /help commands (it will just answer in private)") elseif key == 'Flood' then return _("Enable and disable the anti-flood system (more info in the /help message)") elseif key == 'Welbut' then return _("If the welcome message is enabled, it will include an inline button that will send to the user the rules in private") elseif key == 'Preview' then return _("Show or hide the preview for links. Affects the rules and every custom command set with /extra") elseif key == 'Rules' then return _([[When someone uses /rules 👥: the bot will answer in the group (always, with admins) 👤: the bot will answer in private]]) elseif key == 'Extra' then return _([[When someone uses an #extra 👥: the bot will answer in the group (always, with admins) 👤: the bot will answer in private]]) elseif key == 'Arab' then return _("Select what the bot should do when someone sends a message with arab characters") elseif key == 'Rtl' then return _("Select what the bot should do when someone sends a message with the RTL character, or has it in his name") elseif key == 'warnsnum' then return _("Change how many times an user has to be warned before being kicked/banned") elseif key == 'warnsact' then return _("Change the action to perform when an user reaches the max. number of warnings") else return _("Description not available") end end local function changeWarnSettings(chat_id, action) local current = tonumber(db:hget('chat:'..chat_id..':warnsettings', 'max')) or 3 local new_val if action == 1 then if current > 12 then return _("The new value is too high ( > 12)") else new_val = db:hincrby('chat:'..chat_id..':warnsettings', 'max', 1) return current..'->'..new_val end elseif action == -1 then if current < 2 then return _("The new value is too low ( < 1)") else new_val = db:hincrby('chat:'..chat_id..':warnsettings', 'max', -1) return current..'->'..new_val end elseif action == 'status' then local status = (db:hget('chat:'..chat_id..':warnsettings', 'type')) or 'kick' if status == 'kick' then db:hset('chat:'..chat_id..':warnsettings', 'type', 'ban') return _("New action on max number of warns received: ban") elseif status == 'ban' then db:hset('chat:'..chat_id..':warnsettings', 'type', 'kick') return _("New action on max number of warns received: kick") end end end local function changeCharSettings(chat_id, field) local chars = { arab_kick = _("Senders of arab messages will be kicked"), arab_ban = _("Senders of arab messages will be banned"), arab_allow = _("Arab language allowed"), rtl_kick = _("The use of the RTL character will lead to a kick"), rtl_ban = _("The use of the RTL character will lead to a ban"), rtl_allow = _("RTL character allowed"), } local hash = 'chat:'..chat_id..':char' local status = db:hget(hash, field) local text if status == 'allowed' then db:hset(hash, field, 'kick') text = chars[field:lower()..'_kick'] elseif status == 'kick' then db:hset(hash, field, 'ban') text = chars[field:lower()..'_ban'] elseif status == 'ban' then db:hset(hash, field, 'allowed') text = chars[field:lower()..'_allow'] else db:hset(hash, field, 'allowed') text = chars[field:lower()..'_allow'] end return text end local function usersettings_table(settings, chat_id) local return_table = {} local icon_off, icon_on = '👤', '👥' for field, default in pairs(settings) do if field == 'Extra' or field == 'Rules' then local status = (db:hget('chat:'..chat_id..':settings', field)) or default if status == 'off' then return_table[field] = icon_off elseif status == 'on' then return_table[field] = icon_on end end end return return_table end local function adminsettings_table(settings, chat_id) local return_table = {} local icon_off, icon_on = '☑️', '✅' for field, default in pairs(settings) do if field ~= 'Extra' and field ~= 'Rules' then local status = (db:hget('chat:'..chat_id..':settings', field)) or default if status == 'off' then return_table[field] = icon_off elseif status == 'on' then return_table[field] = icon_on end end end return return_table end local function charsettings_table(settings, chat_id) local return_table = {} for field, default in pairs(settings) do local status = (db:hget('chat:'..chat_id..':char', field)) or default if status == 'kick' then return_table[field] = '👞 '..status elseif status == 'ban' then return_table[field] = '🔨 '..status elseif status == 'allowed' then return_table[field] = '✅' end end return return_table end local function insert_settings_section(keyboard, settings_section, chat_id) local strings = { Welcome = _("Welcome"), Goodbye = _("Goodbye"), Extra = _("Extra"), Flood = _("Anti-flood"), Silent = _("Silent mode"), Rules = _("Rules"), Preview = _("Link preview"), Arab = _("Arab"), Rtl = _("RTL"), Antibot = _("Ban bots"), Reports = _("Reports"), Welbut = _("Welcome + rules button") } for key, icon in pairs(settings_section) do local current = { {text = strings[key] or key, callback_data = 'menu:alert:settings:'..key..':'..chat_id}, {text = icon, callback_data = 'menu:'..key..':'..chat_id} } table.insert(keyboard.inline_keyboard, current) end return keyboard end local function doKeyboard_menu(chat_id) local keyboard = {inline_keyboard = {}} local settings_section = adminsettings_table(config.chat_settings['settings'], chat_id) keyboad = insert_settings_section(keyboard, settings_section, chat_id) settings_section = usersettings_table(config.chat_settings['settings'], chat_id) keyboad = insert_settings_section(keyboard, settings_section, chat_id) settings_section = charsettings_table(config.chat_settings['char'], chat_id) keyboad = insert_settings_section(keyboard, settings_section, chat_id) --warn local max = (db:hget('chat:'..chat_id..':warnsettings', 'max')) or config.chat_settings['warnsettings']['max'] local action = (db:hget('chat:'..chat_id..':warnsettings', 'type')) or config.chat_settings['warnsettings']['type'] if action == 'kick' then action = _("👞 kick") else action = _("🔨️ ban") end local warn = { { {text = _('Warns: ')..max, callback_data = 'menu:alert:settings:warnsnum:'..chat_id}, {text = '➖', callback_data = 'menu:DimWarn:'..chat_id}, {text = '➕', callback_data = 'menu:RaiseWarn:'..chat_id}, }, { {text = _('Action:'), callback_data = 'menu:alert:settings:warnsact:'..chat_id}, {text = action, callback_data = 'menu:ActionWarn:'..chat_id} } } for i, button in pairs(warn) do table.insert(keyboard.inline_keyboard, button) end --back button table.insert(keyboard.inline_keyboard, {{text = '🔙', callback_data = 'config:back:'..chat_id}}) return keyboard end function plugin.onCallbackQuery(msg, blocks) local chat_id = msg.target_id if not roles.is_admin_cached(chat_id, msg.from.id) then api.answerCallbackQuery(msg.cb_id, _("You're no longer an admin")) else if not chat_id then api.sendAdmin('Not msg.target_id -> menu') return end local menu_first = _("Manage the settings of the group") local keyboard, text, show_alert if blocks[1] == 'config' then keyboard = doKeyboard_menu(chat_id) api.editMessageText(msg.chat.id, msg.message_id, menu_first, true, keyboard) else if blocks[2] == 'alert' then text = get_button_description(blocks[3]) api.answerCallbackQuery(msg.cb_id, text, true) return end if blocks[2] == 'DimWarn' or blocks[2] == 'RaiseWarn' or blocks[2] == 'ActionWarn' then if blocks[2] == 'DimWarn' then text = changeWarnSettings(chat_id, -1) elseif blocks[2] == 'RaiseWarn' then text = changeWarnSettings(chat_id, 1) elseif blocks[2] == 'ActionWarn' then text = changeWarnSettings(chat_id, 'status') end elseif blocks[2] == 'Rtl' or blocks[2] == 'Arab' then text = changeCharSettings(chat_id, blocks[2]) else text, show_alert = misc.changeSettingStatus(chat_id, blocks[2]) end keyboard = doKeyboard_menu(chat_id) api.editMessageText(msg.chat.id, msg.message_id, menu_first, true, keyboard) if text then --workaround to avoid to send an error to users who are using an old inline keyboard api.answerCallbackQuery(msg.cb_id, '⚙ '..text, show_alert) end end end end plugin.triggers = { onCallbackQuery = { '^###cb:(menu):(alert):settings:([%w_]+):', '^###cb:(menu):(.*):', '^###cb:(config):menu:(-?%d+)$' } } return plugin
gpl-2.0
ahmadname12/animus1999
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-2.0
theraven262/amber
tools.lua
1
4500
-- Tools -- -- Descriptions -- tooltypes = { "Pickaxe", "Shovel", "Axe", "Sword" } amber.create_description = function(n) description = "Amber " .. tooltypes[n] return description end amber.create_ancient_description = function(n) description = "Ancient Amber " .. tooltypes[n] return description end -- Pickaxe -- minetest.register_tool("amber:pickaxe", { description = amber.create_description(1), inventory_image = "amber_pickaxe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ cracky = {times={[1]=4.20, [2]=1.80, [3]=0.80}, uses=20, maxlevel=2}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) -- Shovel -- minetest.register_tool("amber:shovel", { description = amber.create_description(2), inventory_image = "amber_shovel.png", wield_image = "amber_shovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.1, max_drop_level=1, groupcaps={ crumbly = {times={[1]=1.70, [2]=1.00, [3]=0.40}, uses=30, maxlevel=2}, }, damage_groups = {fleshy=3}, }, sound = {breaks = "default_tool_breaks"}, }) -- Axe -- minetest.register_tool("amber:axe", { description = amber.create_description(3), inventory_image = "amber_axe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ choppy={times={[1]=2.70, [2]=1.50, [3]=1.00}, uses=20, maxlevel=2}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) -- Sword -- minetest.register_tool("amber:sword", { description = amber.create_description(4), inventory_image = "amber_sword.png", tool_capabilities = { full_punch_interval = 0.8, max_drop_level=1, groupcaps={ snappy={times={[1]=2.7, [2]=1.30, [3]=0.35}, uses=30, maxlevel=2}, }, damage_groups = {fleshy=6}, }, sound = {breaks = "default_tool_breaks"}, }) -- Toolranks Support -- if minetest.get_modpath("toolranks") then for n=1,4 do minetest.override_item("amber:" .. tooltypes[n]:lower(), { original_description = "Amber " .. tooltypes[n], description = toolranks.create_description("Amber " .. tooltypes[n], 0, 1), after_use = toolranks.new_afteruse, }) end end -- Ancient Tools -- local anch_color = "006699" minetest.register_tool("amber:pickaxe_ancient", { description = amber.create_ancient_description(1), inventory_image = "amber_pickaxe.png^(amber_outline_pickaxe.png^[colorize:#" .. anch_color .. ")", wield_image = "amber_pickaxe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ cracky = {times={[1]=2.0, [2]=0.8, [3]=0.40}, uses=20, maxlevel=3}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) -- Shovel -- minetest.register_tool("amber:shovel_ancient", { description = amber.create_ancient_description(2), inventory_image = "amber_shovel.png^(amber_outline_shovel.png^[colorize:#" .. anch_color .. ")", wield_image = "amber_shovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.1, max_drop_level=1, groupcaps={ crumbly = {times={[1]=1.00, [2]=0.40, [3]=0.15}, uses=20, maxlevel=3}, }, damage_groups = {fleshy=3}, }, sound = {breaks = "default_tool_breaks"}, }) -- Axe -- minetest.register_tool("amber:axe_ancient", { inventory_image = "amber_axe.png^(amber_outline_axe.png^[colorize:#" .. anch_color .. ")", wield_image = "amber_axe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ choppy={times={[1]=2.00, [2]=0.80, [3]=0.50}, uses=20, maxlevel=3}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) -- Sword -- minetest.register_tool("amber:sword_ancient", { description = amber.create_ancient_description(4), inventory_image = "amber_sword.png^(amber_outline_sword.png^[colorize:#" .. anch_color .. ")", wield_image = "amber_sword.png", tool_capabilities = { full_punch_interval = 0.8, max_drop_level=1, groupcaps={ snappy={times={[1]=1,8, [2]=0.8, [3]=0.25}, uses=30, maxlevel=3}, }, damage_groups = {fleshy=6}, }, sound = {breaks = "default_tool_breaks"}, }) -- Toolranks Support -- if minetest.get_modpath("toolranks") then for n=1,4 do minetest.override_item("amber:" .. tooltypes[n]:lower() .. "_ancient", { original_description = "Ancient Amber " .. tooltypes[n], description = toolranks.create_description("Ancient Amber " .. tooltypes[n], 0, 1), after_use = toolranks.new_afteruse, }) end end
lgpl-2.1
chickenkiller/mongrel2
examples/bbs/engine.lua
96
1958
local print = print local pcall = pcall local coroutine = coroutine local ui = require 'ui' local db = require 'db' module 'engine' local STATE = {} function run(conn, engine) while true do -- Get a message from the Mongrel2 server local good, request = pcall(conn.recv_json, conn) if good then local msg_type = request.data.type if msg_type == 'disconnect' then -- The client has disconnected print("disconnect", request.conn_id) STATE[request.conn_id] = nil elseif msg_type == 'msg' then -- The client has sent data local eng = STATE[request.conn_id] -- If the client hasn't sent data before, create a new engine. if not eng then eng = coroutine.create(engine) STATE[request.conn_id] = eng -- Initialize the engine with the client's connection coroutine.resume(eng, conn) end -- Pass the data on to the engine local good, error = coroutine.resume(eng, request) print("status", coroutine.status(eng)) -- If the engine is done, stop tracking the client if coroutine.status(eng) == "dead" then STATE[request.conn_id] = nil if not good then -- There was an error print("ERROR", error) ui.exit(conn, request, 'error') local status, error = db.reconnect() if error then print("FAILED RECONNECT", error) end end end else print("invalid message.") end print("eng", STATE[request.conn_id]) end end end
bsd-3-clause
yraigne/domotique
PID chauffage/script_device_thermostat-salon.lua
1
1580
-- Alexandre DUBOIS - 2014 -- Ce script permet de maintenir la température de salon entre 19°C et 21°C quand l'interrupteur -- virtuel 'Thermostat salon' est activé. -------------------------------- ------ Variables à éditer ------ -------------------------------- local consigne = 20 --Température de consigne local hysteresis = 0.5 --Valeur seuil pour éviter que le relai ne cesse de commuter dans les 2 sens local sonde = 'Salon' --Nom de la sonde de température local thermostat = 'Thermostat salon' --Nom de l'interrupteur virtuel du thermostat local radiateur = 'Radiateur salon' --Nom du radiateur à allumer/éteindre -------------------------------- -- Fin des variables à éditer -- -------------------------------- commandArray = {} --La sonde Oregon 'Salon' emet toutes les 40 secondes. Ce sera approximativement la fréquence -- d'exécution de ce script. if (devicechanged[sonde]) then local temperature = devicechanged[string.format('%s_Temperature', sonde)] --Temperature relevée dans le salon --On n'agit que si le "Thermostat" est actif if (otherdevices[thermostat]=='On') then print('-- Gestion du thermostat pour le salon --') if (temperature < (consigne - hysteresis) ) then print('Allumage du chauffage dans le salon') commandArray[radiateur]='Off' elseif (temperature > (consigne + hysteresis)) then print('Extinction du chauffage dans le salon') commandArray[radiateur]='On' end end end return commandArray
gpl-3.0
z0fa/ChatNorris
libraries/AceGUI-3.0/widgets/AceGUIWidget-Heading.lua
68
2216
--[[----------------------------------------------------------------------------- Heading Widget -------------------------------------------------------------------------------]] local Type, Version = "Heading", 20 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local pairs = pairs -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetText() self:SetFullWidth() self:SetHeight(18) end, -- ["OnRelease"] = nil, ["SetText"] = function(self, text) self.label:SetText(text or "") if text and text ~= "" then self.left:SetPoint("RIGHT", self.label, "LEFT", -5, 0) self.right:Show() else self.left:SetPoint("RIGHT", -3, 0) self.right:Hide() end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontNormal") label:SetPoint("TOP") label:SetPoint("BOTTOM") label:SetJustifyH("CENTER") local left = frame:CreateTexture(nil, "BACKGROUND") left:SetHeight(8) left:SetPoint("LEFT", 3, 0) left:SetPoint("RIGHT", label, "LEFT", -5, 0) left:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") left:SetTexCoord(0.81, 0.94, 0.5, 1) local right = frame:CreateTexture(nil, "BACKGROUND") right:SetHeight(8) right:SetPoint("RIGHT", -3, 0) right:SetPoint("LEFT", label, "RIGHT", 5, 0) right:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") right:SetTexCoord(0.81, 0.94, 0.5, 1) local widget = { label = label, left = left, right = right, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
gpl-3.0
fetaera/mudlet-qt5
src/mudlet-lua/lua/geyser/GeyserColor.lua
19
6003
-------------------------------------- -- -- -- The Geyser Layout Manager by guy -- -- -- -------------------------------------- Geyser.Color = {} --- Converts color to 3 hex values as a string, no alpha, css style -- @return The color formatted as a hex string, as accepted by html/css function Geyser.Color.hex (r,g,b) return string.format("#%02x%02x%02x", Geyser.Color.parse(r, g, b)) end --- Converts color to 4 hex values as a string, with alpha, css style -- @return The color formatted as a hex string, as accepted by html/css function Geyser.Color.hexa (r,g,b,a) return string.format("#%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a)) end --- Converts color to 3 hex values as a string, no alpha, hecho style -- @return The color formatted as a hex string, as accepted by hecho function Geyser.Color.hhex (r,g,b) return string.format("|c%02x%02x%02x", Geyser.Color.parse(r, g, b)) end --- Converts color to 4 hex values as a string, with alpha, hecho style -- @return The color formatted as a hex string, as accepted by hecho function Geyser.Color.hhexa (r,g,b,a) return string.format("|c%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a)) end --- Converts color to 3 decimal values as a string, no alpha, decho style -- @return The color formatted as a decho() style string function Geyser.Color.hdec (r,g,b) return string.format("<%d,%d,%d>", Geyser.Color.parse(r, g, b)) end --- Converts color to 4 decimal values as a string, with alpha, decho style -- @return The color formatted as a decho() style string function Geyser.Color.hdeca (r,g,b,a) return string.format("<%d,%d,%d,%d>", Geyser.Color.parse(r, g, b, a)) end --- Returns 4 color components from (nearly any) acceptable format. Colors can be -- specified in two ways. First: as a single word in english ("purple") or -- hex ("#AA00FF", "|cAA00FF", or "0xAA00FF") or decimal ("<190,0,255>"). If -- the hex or decimal representations contain a fourth element then alpha is -- set too - otherwise alpha can't be set this way. Second: by passing in -- distinct components as unsigned integers (e.g. 23 or 0xA7). When using the -- second way, at least three values must be passed. If only three are -- passed, then alpha is 255. Third: by passing in a table that has explicit -- values for some, all or none of the keys r,g,b, and a. -- @param red Either a valid string representation or the red component. -- @param green The green component. -- @param blue The blue component. -- @param alpha The alpha component. function Geyser.Color.parse(red, green, blue, alpha) local r,g,b,a = 0,0,0,255 -- have to have something to set, else can't do anything! if not red then print("No color supplied.\n") return end -- function to return next number local next_num = nil local base = 10 -- assigns all the colors, used after we figure out how the color is -- represented as a string local assign_colors = function () r = tonumber(next_num(), base) g = tonumber(next_num(), base) b = tonumber(next_num(), base) local has_a = next_num() if has_a then a = tonumber(has_a, base) end end -- Check if we were passed a string or table that needs to be parsed, i.e., -- there is only a valid red value, and other params are nil. if not green or not blue then if type(red) == "table" then -- Here just copy over the appropriate values with sensible defaults r = red.r or 127 g = red.g or 127 b = red.b or 127 a = red.a or 255 return r,g,b,a elseif type(red) == "string" then -- first case is a hex string, where first char is '#' if string.find(red, "^#") then local pure_hex = string.sub(red, 2) -- strip format char next_num = string.gmatch(pure_hex, "%w%w") base = 16 -- second case is a hex string, where first chars are '|c' or '0x' elseif string.find(red, "^[|0][cx]") then local pure_hex = string.sub(red, 3) -- strip format chars next_num = string.gmatch(pure_hex, "%w%w") base = 16 -- third case is a decimal string, of the format "<dd,dd,dd>" elseif string.find(red, "^<") then next_num = string.gmatch(red, "%d+") -- fourth case is a named string elseif color_table[red] then local i = 0 local n = #color_table[red] next_num = function () -- create a simple iterator i = i + 1 if i <= n then return color_table[red][i] else return nil end end else -- finally, no matches, do nothing return end end else -- Otherwise we weren't passed a complete string, but instead discrete -- components as either decimal or hex -- Yes, this is a little silly to do this way, but it fits with the -- rest of the parsing going on... local i = 0 next_num = function () i = i + 1 if i == 1 then return red elseif i == 2 then return green elseif i == 3 then return blue elseif i == 4 then return alpha else return nil end end end assign_colors() return r,g,b,a end --- Applies colors to a window drawing from defaults and overridden values. -- @param cons The window to apply colors to function Geyser.Color.applyColors(cons) cons:setFgColor(cons.fgColor) cons:setBgColor(cons.bgColor) cons:setColor(cons.color) end
gpl-2.0
lukasc-ch/nn
MM.lua
46
2695
--[[ Module to perform matrix multiplication on two minibatch inputs, producing a minibatch. ]] local MM, parent = torch.class('nn.MM', 'nn.Module') --[[ The constructor takes two optional arguments, specifying whether or not transpose any of the input matrices before perfoming the multiplication. ]] function MM:__init(transA, transB) parent.__init(self) self.transA = transA or false self.transB = transB or false self.gradInput = {torch.Tensor(), torch.Tensor()} end function MM:updateOutput(input) assert(#input == 2, 'input must be a pair of minibatch matrices') local a, b = table.unpack(input) assert(a:nDimension() == 2 or a:nDimension() == 3, 'input tensors must be 2D or 3D') if a:nDimension() == 2 then assert(b:nDimension() == 2, 'second input tensor must be 2D') if self.transA then a = a:t() end if self.transB then b = b:t() end assert(a:size(2) == b:size(1), 'matrix sizes do not match') self.output:resize(a:size(1), b:size(2)) self.output:mm(a, b) else assert(b:nDimension() == 3, 'second input tensor must be 3D') assert(a:size(1) == b:size(1), 'inputs must contain the same number of minibatches') if self.transA then a = a:transpose(2, 3) end if self.transB then b = b:transpose(2, 3) end assert(a:size(3) == b:size(2), 'matrix sizes do not match') self.output:resize(a:size(1), a:size(2), b:size(3)) self.output:bmm(a, b) end return self.output end function MM:updateGradInput(input, gradOutput) assert(#input == 2, 'input must be a pair of tensors') local a, b = table.unpack(input) self.gradInput[1]:resizeAs(a) self.gradInput[2]:resizeAs(b) assert(gradOutput:nDimension() == 2 or gradOutput:nDimension() == 3, 'arguments must be a 2D or 3D Tensor') local h_dim, w_dim, f if gradOutput:nDimension() == 2 then assert(a:nDimension() == 2, 'first input tensor must be 2D') assert(b:nDimension() == 2, 'second input tensor must be 2D') h_dim, w_dim = 1, 2 f = "mm" else assert(a:nDimension() == 3, 'first input tensor must be 3D') assert(b:nDimension() == 3, 'second input tensor must be 3D') h_dim, w_dim = 2, 3 f = "bmm" end if self.transA == self.transB then a = a:transpose(h_dim, w_dim) b = b:transpose(h_dim, w_dim) end if self.transA then self.gradInput[1][f](self.gradInput[1], b, gradOutput:transpose(h_dim, w_dim)) else self.gradInput[1][f](self.gradInput[1], gradOutput, b) end if self.transB then self.gradInput[2][f](self.gradInput[2], gradOutput:transpose(h_dim, w_dim), a) else self.gradInput[2][f](self.gradInput[2], a, gradOutput) end return self.gradInput end
bsd-3-clause
hongling0/skynet
test/testcrypt.lua
12
1179
local skynet = require "skynet" local crypt = require "skynet.crypt" local text = "hello world" local key = "12345678" local function desencode(key, text, padding) local c = crypt.desencode(key, text, crypt.padding[padding or "iso7816_4"]) return crypt.base64encode(c) end local function desdecode(key, text, padding) text = crypt.base64decode(text) return crypt.desdecode(key, text, crypt.padding[padding or "iso7816_4"]) end local etext = desencode(key, text) assert( etext == "KNugLrX23UcGtcVlk9y+LA==") assert(desdecode(key, etext) == text) local etext = desencode(key, text, "pkcs7") assert(desdecode(key, etext, "pkcs7") == text) assert(desencode(key, "","pkcs7")=="/rlZt9RkL8s=") assert(desencode(key, "1","pkcs7")=="g6AtgJul6q0=") assert(desencode(key, "12","pkcs7")=="NefFpG+m1O4=") assert(desencode(key, "123","pkcs7")=="LDiFUdf0iew=") assert(desencode(key, "1234","pkcs7")=="T9u7dzBdi+w=") assert(desencode(key, "12345","pkcs7")=="AGgKdx/Qic8=") assert(desencode(key, "123456","pkcs7")=="ED5wLgc3Mnw=") assert(desencode(key, "1234567","pkcs7")=="mYo+BYIT41M=") assert(desencode(key, "12345678","pkcs7")=="ltACiHjVjIn+uVm31GQvyw==") skynet.start(skynet.exit)
mit
CaptainCN/QCEditor
cocos2d/cocos/scripting/lua-bindings/auto/api/NavMeshObstacle.lua
10
2763
-------------------------------- -- @module NavMeshObstacle -- @extend Component -- @parent_module cc -------------------------------- -- -- @function [parent=#NavMeshObstacle] getSyncFlag -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#NavMeshObstacle] initWith -- @param self -- @param #float radius -- @param #float height -- @return bool#bool ret (return value: bool) -------------------------------- -- synchronize parameter to obstacle. -- @function [parent=#NavMeshObstacle] syncToObstacle -- @param self -- @return NavMeshObstacle#NavMeshObstacle self (return value: cc.NavMeshObstacle) -------------------------------- -- synchronize parameter to node. -- @function [parent=#NavMeshObstacle] syncToNode -- @param self -- @return NavMeshObstacle#NavMeshObstacle self (return value: cc.NavMeshObstacle) -------------------------------- -- Get height of obstacle -- @function [parent=#NavMeshObstacle] getHeight -- @param self -- @return float#float ret (return value: float) -------------------------------- -- synchronization between node and obstacle is time consuming, you can skip some synchronization using this function -- @function [parent=#NavMeshObstacle] setSyncFlag -- @param self -- @param #int flag -- @return NavMeshObstacle#NavMeshObstacle self (return value: cc.NavMeshObstacle) -------------------------------- -- Get radius of obstacle -- @function [parent=#NavMeshObstacle] getRadius -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Create obstacle, shape is cylinder<br> -- param radius The radius of obstacle.<br> -- param height The height of obstacle. -- @function [parent=#NavMeshObstacle] create -- @param self -- @param #float radius -- @param #float height -- @return NavMeshObstacle#NavMeshObstacle ret (return value: cc.NavMeshObstacle) -------------------------------- -- -- @function [parent=#NavMeshObstacle] getNavMeshObstacleComponentName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#NavMeshObstacle] onEnter -- @param self -- @return NavMeshObstacle#NavMeshObstacle self (return value: cc.NavMeshObstacle) -------------------------------- -- -- @function [parent=#NavMeshObstacle] onExit -- @param self -- @return NavMeshObstacle#NavMeshObstacle self (return value: cc.NavMeshObstacle) -------------------------------- -- -- @function [parent=#NavMeshObstacle] NavMeshObstacle -- @param self -- @return NavMeshObstacle#NavMeshObstacle self (return value: cc.NavMeshObstacle) return nil
mit
wsenafranca/urban
examples/UrbanSprawl_figure_05.lua
1
1509
--@example Relationship between Gini’s coefficient and income segregation indicators. import("urban") local dataFigA = {} local dataFigB = {} local ginis = {0.1, 0.2, 0.3, 0.4, 0.5} local stdIncomes = {300, 400, 500, 600, 700, 800} sessionInfo().graphics = false for meanIncome = 900, 1500, 300 do local rowFigA = {} local rowFigB = {} for i = 1, #ginis do model = UrbanSprawl{meanIncome = meanIncome, stdIncome = stdIncomes[i]} model:run() rowFigA[ginis[i]] = model:nsi() rowFigB[ginis[i]] = model:cgi() end dataFigA[meanIncome] = rowFigA dataFigB[meanIncome] = rowFigB end sessionInfo().graphics = true local mean900 = {} local mean1200 = {} local mean1500 = {} for _, gini in pairs(ginis) do table.insert(mean900, dataFigA[900][gini]) table.insert(mean1200, dataFigA[1200][gini]) table.insert(mean1500, dataFigA[1500][gini]) end local df1 = DataFrame{ mean900 = mean900, mean1200 = mean1200, mean1500 = mean1500, ginis = ginis } Chart{ target = df1, select = {"mean900", "mean1200", "mean1500"}, xAxis = "ginis", yLabel = "NSI" } mean900 = {} mean1200 = {} mean1500 = {} for _, gini in pairs(ginis) do table.insert(mean900, dataFigB[900][gini]) table.insert(mean1200, dataFigB[1200][gini]) table.insert(mean1500, dataFigB[1500][gini]) end local df2 = DataFrame{ mean900 = mean900, mean1200 = mean1200, mean1500 = mean1500, giniCoefficient = ginis } Chart{ target = df2, select = {"mean900", "mean1200", "mean1500"}, xAxis = "giniCoefficient", yLabel = "CGI" }
gpl-3.0
joeyhng/nn
VolumetricMaxUnpooling.lua
17
1804
local VolumetricMaxUnpooling, parent = torch.class('nn.VolumetricMaxUnpooling', 'nn.Module') function VolumetricMaxUnpooling:__init(poolingModule) parent.__init(self) assert(torch.type(poolingModule)=='nn.VolumetricMaxPooling', 'Argument must be a nn.VolumetricMaxPooling module') assert(poolingModule.kT==poolingModule.dT and poolingModule.kH==poolingModule.dH and poolingModule.kW==poolingModule.dW, "The size of pooling module's kernel must be equal to its stride") self.pooling = poolingModule end function VolumetricMaxUnpooling:setParams() self.indices = self.pooling.indices self.otime = self.pooling.itime self.oheight = self.pooling.iheight self.owidth = self.pooling.iwidth self.dT = self.pooling.dT self.dH = self.pooling.dH self.dW = self.pooling.dW self.padT = self.pooling.padT self.padH = self.pooling.padH self.padW = self.pooling.padW end function VolumetricMaxUnpooling:updateOutput(input) self:setParams() input.THNN.VolumetricMaxUnpooling_updateOutput( input:cdata(), self.output:cdata(), self.indices:cdata(), self.otime, self.owidth, self.oheight, self.dT, self.dW, self.dH, self.padT, self.padW, self.padH ) return self.output end function VolumetricMaxUnpooling:updateGradInput(input, gradOutput) self:setParams() input.THNN.VolumetricMaxUnpooling_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.indices:cdata(), self.otime, self.owidth, self.oheight, self.dT, self.dW, self.dH, self.padT, self.padW, self.padH ) return self.gradInput end function VolumetricMaxUnpooling:empty() self:clearState() end function VolumetricMaxUnpooling:__tostring__() return 'nn.VolumetricMaxUnpooling associated to '..tostring(self.pooling) end
bsd-3-clause
coronalabs/plugins-source-openssl
Corona/luasec/main.lua
1
1944
-------------------------------------------------------------------------------- -- Sample code is MIT licensed, see http://www.coronalabs.com/links/code/license -- Copyright (C) 2013 Corona Labs Inc. All Rights Reserved. -------------------------------------------------------------------------------- -- -- To test this client-side code, use this server: -- -- openssl s_server \ -- -key path/to/my/private_key.pem \ -- -cert path/to/my/signed_public_key_certificate.pem \ -- -accept 64001 -www print( "lua-openssl secure socket test start." ) local openssl = require('plugin.openssl') local socket = require('socket') local plugin_luasec_ssl = require('plugin_luasec_ssl') lua_openssl_version, lua_version, openssl_version = openssl.version() print( "lua-openssl version: " .. lua_openssl_version, lua_version, openssl_version ) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- TLS/SSL client parameters (omitted) local params = { mode = "client", protocol = "tlsv1", verify = "none", options = "all", } local conn = socket.tcp() local server_address = "10.3.3.106" local server_port = 64001 local result, error = conn:connect( server_address, server_port ) if result then -- We're connected. else print( "Failed to connect to: " .. server_address .. ":" .. tostring( server_port ) .. " Error: " .. error ) return end -- TLS/SSL initialization conn = plugin_luasec_ssl.wrap(conn, params) conn:dohandshake() -- conn:send( "GET / HTTP/1.0\n\n" ) local data, status, partial_data = conn:receive("*a") if data then print( data ) end if partial_data then print( partial_data ) end conn:close() -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- print( "lua-openssl secure socket test done." )
mit
aderiabin/sdl_atf
modules/mobile_connection.lua
1
2221
local ph = require('protocol_handler/protocol_handler') local file_connection = require("file_connection") local module = { mt = { __index = {} } } function module.MobileConnection(connection) res = { } res.connection = connection setmetatable(res, module.mt) return res end function module.mt.__index:Connect() self.connection:Connect() end function module.mt.__index:Send(data) local messages = { } local protocol_handler = ph.ProtocolHandler() for _, msg in ipairs(data) do atf_logger.LOG("MOBtoSDL", msg) local msgs = protocol_handler:Compose(msg) for _, m in ipairs(msgs) do table.insert(messages, m) end end self.connection:Send(messages) end function module.mt.__index:StartStreaming(session, service, filename, bandwidth) if getmetatable(self.connection) ~= file_connection.mt then error("Data streaming is impossible unless underlying connection is FileConnection") end xmlReporter.AddMessage("mobile_connection","StartStreaming", {["Session"]=session, ["Service"]=service,["FileName"]=filename,["Bandwidth"]=bandwidth }) self.connection:StartStreaming(session, service, filename, bandwidth) end function module.mt.__index:StopStreaming(filename) xmlReporter.AddMessage("mobile_connection","StopStreaming", {["FileName"]=filename}) self.connection:StopStreaming(filename) end function module.mt.__index:OnInputData(func) local this = self local protocol_handler = ph.ProtocolHandler() local f = function(self, binary) local msg = protocol_handler:Parse(binary) for _, v in ipairs(msg) do -- After refactoring should be moved in mobile session atf_logger.LOG("SDLtoMOB", v) func(this, v) end end self.connection:OnInputData(f) end function module.mt.__index:OnDataSent(func) self.connection:OnDataSent(func) end function module.mt.__index:OnMessageSent(func) self.connection:OnMessageSent(func) end function module.mt.__index:OnConnected(func) self.connection:OnConnected(function() func(self) end) end function module.mt.__index:OnDisconnected(func) self.connection:OnDisconnected(function() func(self) end) end function module.mt.__index:Close() self.connection:Close() end return module
bsd-3-clause
kennyballou/blingbling
udisks_glue.lua
5
10051
--@author cedlemo local helpers = require("blingbling.helpers") local awful = require("awful") local naughty = require("naughty") local string = string local math = math local ipairs = ipairs local next = next local pairs = pairs local type = type local setmetatable = setmetatable local table = table local wibox = require("wibox") local debug = debug ---A menu for udisks-glue informations and actions --@module blingbling.udisks_glue local udisks_glue = { mt = {} } local data = setmetatable( {}, { __mode = "k"}) local function udisks_send(ud_menu,command,a_device) local s="" data[ud_menu].menu_visible = "false" data[ud_menu].menu:hide() s=s .. "udisks --"..command.." "..a_device return s end local function mounted_submenu(ud_menu, a_device) local my_submenu= { { "umount",udisks_send(ud_menu,"unmount", a_device),data[ud_menu].umount_icon}--, } return my_submenu end local function unmounted_submenu(ud_menu,a_device) local my_submenu= { { "mount",udisks_send(ud_menu,"mount", a_device),data[ud_menu].mount_icon}--, } return my_submenu end local function unmount_multiple_partitions(ud_menu, a_device, mount_points) local command = "bash -c \"" for _,m in ipairs(mount_points) do command = command .. udisks_send(ud_menu, "unmount", m)..";" end command = command .. udisks_send(ud_menu, "detach", a_device) .. "\"" return command end local function generate_menu(ud_menu) --all_devices={device_name={partition_1,partition_2} --devices_type={device_name=Usb or Cdrom} --partition_state={partition_name = mounted or unmounted} local my_menu={} if next(data[ud_menu].all_devices) ~= nil then for k,v in pairs(data[ud_menu].all_devices) do local device_type=data[ud_menu].devices_type[k] local action="" if device_type == "Usb" then action="detach" else action="eject" end local check_remain_mounted_partition =0 my_submenu={} local mounted_partitions = {} for j,x in ipairs(v) do if data[ud_menu].partition_state[x] == "mounted" then check_remain_mounted_partition = 1 table.insert(my_submenu,{x, mounted_submenu(ud_menu, x), data[ud_menu][device_type.."_icon"]}) table.insert(mounted_partitions,x) else table.insert(my_submenu,{x, unmounted_submenu(ud_menu, x), data[ud_menu][device_type.."_icon"]}) end end if check_remain_mounted_partition == 1 then table.insert(my_submenu,{"unmount all", unmount_multiple_partitions(ud_menu, k, mounted_partitions ), data[ud_menu]["umount_icon"]}) --table.insert(my_submenu,{"Can\'t "..action, {{k .." busy"}}, data[ud_menu][action.."_icon"]}) else table.insert(my_submenu,{action, udisks_send(ud_menu, action, k), data[ud_menu][action.."_icon"]}) end table.insert(my_menu, {k, my_submenu, data[ud_menu][device_type.."_icon"]}) end else my_menu={{"No media",""}} end data[ud_menu].menu= awful.menu({ items = my_menu, }) return ud_menu end local function display_menu(ud_menu) ud_menu:buttons(awful.util.table.join( awful.button({ }, 1, function() if data[ud_menu].menu_visible == "false" then data[ud_menu].menu_visible = "true" generate_menu(ud_menu ) data[ud_menu].menu:show() else data[ud_menu].menu:hide() data[ud_menu].menu_visible = "false" end end), awful.button({ }, 3, function() data[ud_menu].menu:hide() data[ud_menu].menu_visible = "false" end) )) end function udisks_glue.insert_device(ud_menu,device, mount_point, device_type) -- generate the device_name if device_type == "Usb" then device_name = string.gsub(device,"%d*","") else device_name=device end -- add all_devices entry: -- check if device is already registred if data[ud_menu].all_devices[device_name] == nil then data[ud_menu].all_devices[device_name]={device} data[ud_menu].devices_type[device_name] = device_type else partition_already_registred = 0 for i, v in ipairs(data[ud_menu].all_devices[device_name]) do if v == device then partition_already_registred = 1 end end if partition_already_registred == 0 then table.insert(data[ud_menu].all_devices[device_name],device) end end data[ud_menu].partition_state[device]="unmounted" data[ud_menu].menu:hide() data[ud_menu].menu_visible = "false" naughty.notify({title = device_type..":", text = device .." inserted", timeout = 10}) end function udisks_glue.mount_device(ud_menu,device, mount_point, device_type) -- generate the device_name if device_type == "Usb" then device_name = string.gsub(device,"%d*","") else device_name=device end -- add all_devices entry: -- check if device is already registred if data[ud_menu].all_devices[device_name] == nil then data[ud_menu].all_devices[device_name]={device} data[ud_menu].devices_type[device_name] = device_type else partition_already_registred = 0 for i, v in ipairs(data[ud_menu].all_devices[device_name]) do if v == device then partition_already_registred = 1 end end if partition_already_registred == 0 then table.insert(data[ud_menu].all_devices[device_name],device) end end data[ud_menu].partition_state[device]="mounted" data[ud_menu].menu:hide() data[ud_menu].menu_visible = "false" naughty.notify({title = device_type..":", text =device .. " mounted on" .. mount_point, timeout = 10}) return ud_menu end function unmount_device(ud_menu, device, mount_point, device_type) data[ud_menu].partition_state[device]="unmounted" data[ud_menu].menu:hide() data[ud_menu].menu_visible = "false" naughty.notify({title = device_type..":", text = device .." unmounted", timeout = 10}) end function remove_device(ud_menu, device, mount_point, device_type ) local device_name="" if device_type == "Usb" then device_name=string.gsub(device,"%d*","") else device_name = device end --Remove the partitions if data[ud_menu].all_devices[device_name] ~= nil then for i,v in ipairs(data[ud_menu].all_devices[device_name]) do if v == device then table.remove(data[ud_menu].all_devices[device_name],i) helpers.hash_remove(data[ud_menu].partition_state, device) end end end --Remove the device if no remaining partition if data[ud_menu].all_devices[device_name] ~= nil and #data[ud_menu].all_devices[device_name] == 0 then helpers.hash_remove(data[ud_menu].all_devices, device_name) helpers.hash_remove(data[ud_menu].devices_type, device_name) end data[ud_menu].menu:hide() data[ud_menu].menu_visible = "false" naughty.notify({title = device_type ..":", text = device .." removed", timeout = 10}) end ---Define the icon for the mount action in the menu. --@usage ud_widget:set_mount_icon(icon) --@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_mount_icon --@param an_image an image file name function set_mount_icon(ud_menu,an_image) data[ud_menu].mount_icon=an_image return ud_menu end ---Define the icon for the umount action in the menu. --@usage ud_widget:set_umount_icon(icon) --@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_umount_icon --@param an_image an image file name function set_umount_icon(ud_menu,an_image) data[ud_menu].umount_icon=an_image return ud_menu end ---Define the icon for the detach action in the menu. --@usage ud_widget:set_detach_icon(icon) --@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_detach_icon --@param an_image an image file name function set_detach_icon(ud_menu,an_image) data[ud_menu].detach_icon=an_image return ud_menu end ---Define the icon for eject action in the menu. --@usage ud_widget:set_eject_icon(icon) --@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_eject_icon --@param an_image an image file name function set_eject_icon(ud_menu,an_image) data[ud_menu].eject_icon=an_image return ud_menu end ---Define the icon for usb devices in the menu. --@usage ud_widget:set_Usb_icon(icon) --@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_Usb_icon --@param an_image an image file name function set_Usb_icon(ud_menu,an_image) data[ud_menu].Usb_icon=an_image return ud_menu end ---Define the icon for Cdrom devices in the menu. --@usage ud_widget:set_Cdrom_icon(icon) --@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_Cdrom_icon --@param an_image an image file name function set_Cdrom_icon(ud_menu,an_image) data[ud_menu].Cdrom_icon=an_image return ud_menu end function udisks_glue.new(args) local args = args or {} local ud_menu ud_menu = wibox.widget.imagebox() ud_menu:set_image(args.menu_icon) data[ud_menu]={ image = menu_icon, all_devices= {}, devices_type={}, partition_state={}, menu_visible = "false", menu={}, Cdrom_icon=args.Cdrom_icon, Usb_icon=args.Usb_icon, mount_icon=args.mount_icon, umount_icon=args.umount_icon, detach_icon=args.detach_icon, eject_icon=args.eject_icon, } ud_menu.insert_device = udisks_glue.insert_device ud_menu.mount_device = udisks_glue.mount_device ud_menu.unmount_device = unmount_device ud_menu.remove_device = remove_device ud_menu.set_mount_icon = set_mount_icon ud_menu.set_umount_icon = set_umount_icon ud_menu.set_detach_icon = set_detach_icon ud_menu.set_eject_icon = set_eject_icon ud_menu.set_Usb_icon = set_Usb_icon ud_menu.set_Cdrom_icon = set_Cdrom_icon generate_menu(ud_menu) display_menu(ud_menu) return ud_menu end function udisks_glue.mt:__call(...) return udisks_glue.new(...) end return setmetatable(udisks_glue, udisks_glue.mt)
gpl-2.0
Whit3Tig3R/z1z1z1z1
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
siktirmirza/CroCodile
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
zactelegram12/TeleSeed
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
samael65535/skynet
lualib/redis.lua
8
6174
local skynet = require "skynet" local socket = require "socket" local socketchannel = require "socketchannel" local table = table local string = string local assert = assert local redis = {} local command = {} local meta = { __index = command, -- DO NOT close channel in __gc } ---------- redis response local redcmd = {} redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = fd:read(bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = fd:readline "\r\n" local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} local noerr = true for i = 1,n do local ok, v = read_response(fd) if ok then bulk[i] = v else noerr = false end end return noerr, bulk end ------------------- local function redis_login(auth, db) if auth == nil and db == nil then return end return function(so) if auth then so:request("AUTH "..auth.."\r\n", read_response) end if db then so:request("SELECT "..db.."\r\n", read_response) end end end function redis.connect(db_conf) local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = redis_login(db_conf.auth, db_conf.db), nodelay = true, } -- try connect first only once channel:connect(true) return setmetatable( { channel }, meta ) end function command:disconnect() self[1]:close() setmetatable(self, nil) end -- msg could be any type of value local function make_cache(f) return setmetatable({}, { __mode = "kv", __index = f, }) end local header_cache = make_cache(function(t,k) local s = "\r\n$" .. k .. "\r\n" t[k] = s return s end) local command_cache = make_cache(function(t,cmd) local s = "\r\n$"..#cmd.."\r\n"..cmd:upper() t[cmd] = s return s end) local count_cache = make_cache(function(t,k) local s = "*" .. k t[k] = s return s end) local function compose_message(cmd, msg) local t = type(msg) local lines = {} if t == "table" then lines[1] = count_cache[#msg+1] lines[2] = command_cache[cmd] local idx = 3 for _,v in ipairs(msg) do v= tostring(v) lines[idx] = header_cache[#v] lines[idx+1] = v idx = idx + 2 end lines[idx] = "\r\n" else msg = tostring(msg) lines[1] = "*2" lines[2] = command_cache[cmd] lines[3] = header_cache[#msg] lines[4] = msg lines[5] = "\r\n" end return lines end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, v, ...) if type(v) == "table" then return self[1]:request(compose_message(cmd, v), read_response) else return self[1]:request(compose_message(cmd, {v, ...}), read_response) end end t[k] = f return f end}) local function read_boolean(so) local ok, result = read_response(so) return ok, result ~= 0 end function command:exists(key) local fd = self[1] return fd:request(compose_message ("EXISTS", key), read_boolean) end function command:sismember(key, value) local fd = self[1] return fd:request(compose_message ("SISMEMBER", {key, value}), read_boolean) end local function compose_table(lines, msg) local tinsert = table.insert tinsert(lines, count_cache[#msg]) for _,v in ipairs(msg) do v = tostring(v) tinsert(lines,header_cache[#v]) tinsert(lines,v) end tinsert(lines, "\r\n") return lines end function command:pipeline(ops,resp) assert(ops and #ops > 0, "pipeline is null") local fd = self[1] local cmds = {} for _, cmd in ipairs(ops) do compose_table(cmds, cmd) end if resp then return fd:request(cmds, function (fd) for i=1, #ops do local ok, out = read_response(fd) table.insert(resp, {ok = ok, out = out}) end return true, resp end) else return fd:request(cmds, function (fd) local ok, out for i=1, #ops do ok, out = read_response(fd) end -- return last response return ok,out end) end end --- watch mode local watch = {} local watchmeta = { __index = watch, __gc = function(self) self.__sock:close() end, } local function watch_login(obj, auth) return function(so) if auth then so:request("AUTH "..auth.."\r\n", read_response) end for k in pairs(obj.__psubscribe) do so:request(compose_message ("PSUBSCRIBE", k)) end for k in pairs(obj.__subscribe) do so:request(compose_message("SUBSCRIBE", k)) end end end function redis.watch(db_conf) local obj = { __subscribe = {}, __psubscribe = {}, } local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = watch_login(obj, db_conf.auth), nodelay = true, } obj.__sock = channel -- try connect first only once channel:connect(true) return setmetatable( obj, watchmeta ) end function watch:disconnect() self.__sock:close() setmetatable(self, nil) end local function watch_func( name ) local NAME = string.upper(name) watch[name] = function(self, ...) local so = self.__sock for i = 1, select("#", ...) do local v = select(i, ...) so:request(compose_message(NAME, v)) end end end watch_func "subscribe" watch_func "psubscribe" watch_func "unsubscribe" watch_func "punsubscribe" function watch:message() local so = self.__sock while true do local ret = so:response(read_response) local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4] if type == "message" then return data, channel elseif type == "pmessage" then return data2, data, channel elseif type == "subscribe" then self.__subscribe[channel] = true elseif type == "psubscribe" then self.__psubscribe[channel] = true elseif type == "unsubscribe" then self.__subscribe[channel] = nil elseif type == "punsubscribe" then self.__psubscribe[channel] = nil end end end return redis
mit
deplinenoise/tundra
scripts/tundra/test/t_env.lua
22
2324
module(..., package.seeall) unit_test('scalar interpolation', function (t) local e = require 'tundra.environment' local e1, e2, e3 e1 = e.create(nil, { Foo="Foo", Baz="Strut" }) e2 = e1:clone({ Foo="Bar" }) e3 = e1:clone({ Baz="c++" }) t:check_equal(e1:get("Foo"), "Foo") t:check_equal(e1:get("Baz"), "Strut") t:check_equal(e2:get("Foo"), "Bar") t:check_equal(e2:get("Baz"), "Strut") t:check_equal(e3:get("Fransos", "Ost"), "Ost") e1:set("Foo", "Foo") t:check_equal(e1:interpolate("$(Foo)"), "Foo") t:check_equal(e1:interpolate("$(Foo:u)"), "FOO") t:check_equal(e1:interpolate("$(Foo:l)"), "foo") t:check_equal(e1:interpolate("$(Foo) $(Baz)"), "Foo Strut") t:check_equal(e2:interpolate("$(Foo) $(Baz)"), "Bar Strut") t:check_equal(e3:interpolate("$(Foo) $(Baz)"), "Foo c++") t:check_equal(e1:interpolate("a $(<)", { ['<'] = "foo" }), "a foo") e1:set("FILE", "foo/bar.txt") t:check_equal(e1:interpolate("$(FILE:B)"), "foo/bar") t:check_equal(e1:interpolate("$(FILE:F)"), "bar.txt") t:check_equal(e1:interpolate("$(FILE:D)"), "foo") e1:set("FILEQ", '"foo/bar.txt"') t:check_equal(e1:interpolate("$(FILEQ:q)"), '"foo/bar.txt"') end) unit_test('list interpolation', function (t) local e = require 'tundra.environment' local e1 = e.create() e1:set("Foo", { "Foo" }) t:check_equal(e1:interpolate("$(Foo)"), "Foo") e1:set("Foo", { "Foo", "Bar" } ) t:check_equal(e1:interpolate("$(Foo)") , "Foo Bar") t:check_equal(e1:interpolate("$(Foo:j,)"), "Foo,Bar") t:check_equal(e1:interpolate("$(Foo:p!)") , "!Foo !Bar") t:check_equal(e1:interpolate("$(Foo:a!)") , "Foo! Bar!") t:check_equal(e1:interpolate("$(Foo:p-I:j__)") , "-IFoo__-IBar") t:check_equal(e1:interpolate("$(Foo:j\\:)"), "Foo:Bar") t:check_equal(e1:interpolate("$(Foo:u)"), "FOO BAR") t:check_equal(e1:interpolate("$(Foo:[2])"), "Bar") t:check_equal(e1:interpolate("$(Foo:Aoo)"), "Foo Baroo") t:check_equal(e1:interpolate("$(Foo:PF)"), "Foo FBar") local lookaside = { ['@'] = 'output', ['<'] = { 'a', 'b' }, } t:check_equal(e1:interpolate("$(Foo) $(<)=$(@)", lookaside), "Foo Bar a b=output") -- Verify interpolation caching is cleared when keys change. e1:set("Foo", { "Baz" }) t:check_equal(e1:interpolate("$(Foo) $(<)=$(@)", lookaside), "Baz a b=output") end)
mit
hongling0/skynet
service/launcher.lua
9
4124
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local launch_session = {} -- for command.QUERY, service_address -> session local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end local function list_srv(ti, fmt_func, ...) local list = {} local sessions = {} local req = skynet.request() for addr in pairs(services) do local r = { addr, "debug", ... } req:add(r) sessions[r] = addr end for req, resp in req:select(ti) do local addr = req[1] if resp then local stat = resp[1] list[skynet.address(addr)] = fmt_func(stat, addr) else list[skynet.address(addr)] = fmt_func("ERROR", addr) end sessions[req] = nil end for session, addr in pairs(sessions) do list[skynet.address(addr)] = fmt_func("TIMEOUT", addr) end return list end function command.STAT(addr, ti) return list_srv(ti, function(v) return v end, "STAT") end function command.KILL(_, handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM(addr, ti) return list_srv(ti, function(kb, addr) local v = services[addr] if type(kb) == "string" then return string.format("%s (%s)", kb, v) else return string.format("%.2f Kb (%s)",kb,v) end end, "MEM") end function command.GC(addr, ti) for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM(addr, ti) end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil launch_session[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local session = skynet.context() local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response launch_session[inst] = session else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) launch_session[address] = nil instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil launch_session[address] = nil end return NORET end function command.QUERY(_, request_session) for address, session in pairs(launch_session) do if session == request_session then return address end end end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
mit