repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
ffxiphoenix/darkstar | scripts/zones/Cloister_of_Flames/Zone.lua | 32 | 1663 | -----------------------------------
--
-- Zone: Cloister_of_Flames (207)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Flames/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-698.729,-1.045,-646.659,184);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/items/slice_of_karakul_meat.lua | 18 | 1290 | -----------------------------------------
-- ID: 5571
-- Item: Slice of Karakul Meat
-- Effect: 5 Minutes, food effect, Galka Only
-----------------------------------------
-- Strength +2
-- Intelligence -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5571);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 2);
target:addMod(MOD_INT, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 2);
target:delMod(MOD_INT, -4);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Castle_Oztroja/npcs/qm3.lua | 1 | 1508 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: qm3 (???)
-- Used In Quest: A boy's Dream (temp spawn instead of fishing)
-- @pos -78 23 -35
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Castle_Oztroja/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
aBoysDreamCS = player:getVar("aBoysDreamCS");
if player:getQuestStatus(A_BOY_S_DREAM) == QUEST_ACCEPTED then
if (trade:hasItemQty(17001,1)) and aBoysDreamCS == 4 then
player:tradeComplete();
SpawnMob (17396141):updateClaim(player);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
function onMobDeath(mob, killer)
killer:setVar("aBoysDreamCS",5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
dail8859/ScintilluaPlusPlus | ext/scintillua/lexers/cuda.lua | 5 | 4318 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- CUDA LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local table = _G.table
local M = {_NAME = 'cuda'}
-- Whitespace
local ws = token(l.WHITESPACE, l.space^1)
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'__global__', '__host__', '__device__', '__constant__', '__shared__'
})
-- Functions.
local func = token(l.FUNCTION, word_match{
-- Atom.
'atomicAdd', 'atomicAnd', 'atomicCAS', 'atomicDec', 'atomicExch', 'atomicInc',
'atomicMax', 'atomicMin', 'atomicOr', 'atomicSub', 'atomicXor',
-- Dev.
'tex1D', 'tex1Dfetch', 'tex2D', '__float_as_int', '__int_as_float',
'__float2int_rn', '__float2int_rz', '__float2int_ru', '__float2int_rd',
'__float2uint_rn', '__float2uint_rz', '__float2uint_ru', '__float2uint_rd',
'__int2float_rn', '__int2float_rz', '__int2float_ru', '__int2float_rd',
'__uint2float_rn', '__uint2float_rz', '__uint2float_ru', '__uint2float_rd',
'__fadd_rz', '__fmul_rz', '__fdividef', '__mul24', '__umul24', '__mulhi',
'__umulhi', '__mul64hi', '__umul64hi', 'min', 'umin', 'fminf', 'fmin', 'max',
'umax', 'fmaxf', 'fmax', 'abs', 'fabsf', 'fabs', 'sqrtf', 'sqrt', 'sinf',
'__sinf', 'sin', 'cosf', '__cosf', 'cos', 'sincosf', '__sincosf', 'expf',
'__expf', 'exp', 'logf', '__logf', 'log',
-- Runtime.
'cudaBindTexture', 'cudaBindTextureToArray', 'cudaChooseDevice',
'cudaConfigureCall', 'cudaCreateChannelDesc', 'cudaD3D10GetDevice',
'cudaD3D10MapResources', 'cudaD3D10RegisterResource',
'cudaD3D10ResourceGetMappedArray', 'cudaD3D10ResourceGetMappedPitch',
'cudaD3D10ResourceGetMappedPointer', 'cudaD3D10ResourceGetMappedSize',
'cudaD3D10ResourceGetSurfaceDimensions', 'cudaD3D10ResourceSetMapFlags',
'cudaD3D10SetDirect3DDevice', 'cudaD3D10UnmapResources',
'cudaD3D10UnregisterResource', 'cudaD3D9GetDevice',
'cudaD3D9GetDirect3DDevice', 'cudaD3D9MapResources',
'cudaD3D9RegisterResource', 'cudaD3D9ResourceGetMappedArray',
'cudaD3D9ResourceGetMappedPitch', 'cudaD3D9ResourceGetMappedPointer',
'cudaD3D9ResourceGetMappedSize', 'cudaD3D9ResourceGetSurfaceDimensions',
'cudaD3D9ResourceSetMapFlags', 'cudaD3D9SetDirect3DDevice',
'cudaD3D9UnmapResources', 'cudaD3D9UnregisterResource', 'cudaEventCreate',
'cudaEventDestroy', 'cudaEventElapsedTime', 'cudaEventQuery',
'cudaEventRecord', 'cudaEventSynchronize', 'cudaFree', 'cudaFreeArray',
'cudaFreeHost', 'cudaGetChannelDesc', 'cudaGetDevice', 'cudaGetDeviceCount',
'cudaGetDeviceProperties', 'cudaGetErrorString', 'cudaGetLastError',
'cudaGetSymbolAddress', 'cudaGetSymbolSize', 'cudaGetTextureAlignmentOffset',
'cudaGetTextureReference', 'cudaGLMapBufferObject',
'cudaGLRegisterBufferObject', 'cudaGLSetGLDevice', 'cudaGLUnmapBufferObject',
'cudaGLUnregisterBufferObject', 'cudaLaunch', 'cudaMalloc', 'cudaMalloc3D',
'cudaMalloc3DArray', 'cudaMallocArray', 'cudaMallocHost', 'cudaMallocPitch',
'cudaMemcpy', 'cudaMemcpy2D', 'cudaMemcpy2DArrayToArray',
'cudaMemcpy2DFromArray', 'cudaMemcpy2DToArray', 'cudaMemcpy3D',
'cudaMemcpyArrayToArray', 'cudaMemcpyFromArray', 'cudaMemcpyFromSymbol',
'cudaMemcpyToArray', 'cudaMemcpyToSymbol', 'cudaMemset', 'cudaMemset2D',
'cudaMemset3D', 'cudaSetDevice', 'cudaSetupArgument', 'cudaStreamCreate',
'cudaStreamDestroy', 'cudaStreamQuery', 'cudaStreamSynchronize',
'cudaThreadExit', 'cudaThreadSynchronize', 'cudaUnbindTexture'
})
-- Types.
local type = token(l.TYPE, word_match{
'uint', 'int1', 'uint1', 'int2', 'uint2', 'int3', 'uint3', 'int4', 'uint4',
'float1', 'float2', 'float3', 'float4', 'char1', 'char2', 'char3', 'char4',
'uchar1', 'uchar2', 'uchar3', 'uchar4', 'short1', 'short2', 'short3',
'short4', 'dim1', 'dim2', 'dim3', 'dim4'
})
-- Variables.
local variable = token(l.VARIABLE, word_match{
'gridDim', 'blockIdx', 'blockDim', 'threadIdx'
})
-- Extend cpp lexer to include CUDA elements.
local cpp = l.load('cpp')
local _rules = cpp._rules
_rules[1] = {'whitespace', ws}
table.insert(_rules, 2, {'cuda_keyword', keyword})
table.insert(_rules, 3, {'cuda_function', func})
table.insert(_rules, 4, {'cuda_type', type})
table.insert(_rules, 5, {'cuda_variable', variable})
M._rules = _rules
M._foldsymbols = cpp._foldsymbols
return M
| gpl-2.0 |
vilarion/Illarion-Content | alchemy/lte/id_330_language.lua | 3 | 1907 | --[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- LTE für das Druidensystem
-- by Falk
-- reworked by Merung
local common = require("base.common")
local M = {}
-- INSERT INTO longtimeeffects VALUES (330, 'alchemy_language', 'alchemy.lte.id_330_language');
local ListLanguages={Character.commonLanguage,Character.humanLanguage,Character.dwarfLanguage,Character.elfLanguage,Character.lizardLanguage,Character.orcLanguage,Character.halflingLanguage,Character.ancientLanguage}
function M.addEffect(Effect, User)
--Nur beim ersten Aufruf
--User:inform("debug func addEffect")
end
function M.callEffect(Effect,User)
common.InformNLS( User, "Du fühlst, dass der Sprachtrank seine Wirkung verliert.", "You feel that the language potion loses its effect.")
return false
end
function M.removeEffect(Effect,User)
--[[
local find,languageId = Effect:findValue("languageId")
local skillName = ListLanguages[languageId]
local find,oldSkill = Effect:findValue( "oldSkill")
local find,newSkill = Effect:findValue( "newSkill")
--original skill level
User:increaseSkill(skillName,(-(newSkill-oldSkill))) ]]
end
function M.loadEffect(Effect,User)
end
return M
| agpl-3.0 |
RodneyMcKay/x_hero_siege | game/scripts/vscripts/components/demo/init.lua | 1 | 4996 | --------------------------------------------------------------------------------
-- GameEvent:OnGameRulesStateChange
--------------------------------------------------------------------------------
ListenToGameEvent('game_rules_state_change', function()
local state = GameRules:State_Get()
if GetMapName() ~= "x_hero_siege_demo" then return end
if state == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP then
GameMode:InitDemo()
-- elseif state == DOTA_GAMERULES_STATE_PRE_GAME then
-- SendToServerConsole( "dota_dev forcegamestart" )
end
end, nil)
function GameMode:InitDemo()
GameRules:GetGameModeEntity():SetTowerBackdoorProtectionEnabled( true )
GameRules:GetGameModeEntity():SetFixedRespawnTime( 4 )
-- GameRules:GetGameModeEntity():SetBotThinkingEnabled( true ) -- the ConVar is currently disabled in C++
-- Set bot mode difficulty: can try GameRules:GetGameModeEntity():SetCustomGameDifficulty( 1 )
GameRules:SetUseUniversalShopMode(true)
GameRules:SetPreGameTime(10.0)
GameRules:SetStrategyTime(0.0)
GameRules:SetCustomGameSetupTimeout(0.0) -- skip the custom team UI with 0, or do indefinite duration with -1
GameRules:SetSafeToLeave(true)
-- Events
CustomGameEventManager:RegisterListener( "WelcomePanelDismissed", function(...) return self:OnWelcomePanelDismissed( ... ) end )
CustomGameEventManager:RegisterListener( "RefreshButtonPressed", function(...) return self:OnRefreshButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "LevelUpButtonPressed", function(...) return self:OnLevelUpButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "MaxLevelButtonPressed", function(...) return self:OnMaxLevelButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "FranticButtonPressed", function(...) return self:OnFranticButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "FreeSpellsButtonPressed", function(...) return self:OnFreeSpellsButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "InvulnerabilityButtonPressed", function(...) return self:OnInvulnerabilityButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "SpawnAllyButtonPressed", function(...) return self:OnSpawnAllyButtonPressed( ... ) end ) -- deprecated
CustomGameEventManager:RegisterListener( "SpawnEnemyButtonPressed", function(...) return self:OnSpawnEnemyButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "LevelUpEnemyButtonPressed", function(...) return self:OnLevelUpEnemyButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "DummyTargetButtonPressed", function(...) return self:OnDummyTargetButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "RemoveSpawnedUnitsButtonPressed", function(...) return self:OnRemoveSpawnedUnitsButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "LaneCreepsButtonPressed", function(...) return self:OnLaneCreepsButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "ChangeHeroButtonPressed", function(...) return self:OnChangeHeroButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "ChangeCosmeticsButtonPressed", function(...) return self:OnChangeCosmeticsButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "PauseButtonPressed", function(...) return self:OnPauseButtonPressed( ... ) end )
CustomGameEventManager:RegisterListener( "LeaveButtonPressed", function(...) return self:OnLeaveButtonPressed( ... ) end )
-- CustomGameEventManager:RegisterListener("fix_newly_picked_hero", Dynamic_Wrap(self, 'OnNewHeroChosen'))
CustomGameEventManager:RegisterListener("demo_select_hero", Dynamic_Wrap(self, 'OnNewHeroSelected'))
GameRules:SetCustomGameTeamMaxPlayers(2, 1)
GameRules:SetCustomGameTeamMaxPlayers(3, 0)
SendToServerConsole( "sv_cheats 1" )
SendToServerConsole( "dota_hero_god_mode 0" )
SendToServerConsole( "dota_ability_debug 0" )
SendToServerConsole( "dota_creeps_no_spawning 0" )
SendToServerConsole( "dota_easybuy 1" )
-- SendToServerConsole( "dota_bot_mode 1" )
self.m_bPlayerDataCaptured = false
self.m_nPlayerID = 0
-- self.m_nHeroLevelBeforeMaxing = 1 -- unused now
-- self.m_bHeroMaxedOut = false -- unused now
self.m_nALLIES_TEAM = 2
self.m_tAlliesList = {}
self.m_nAlliesCount = 0
self.m_nENEMIES_TEAM = 3
self.m_tEnemiesList = {}
self.m_bFreeSpellsEnabled = false
self.m_bInvulnerabilityEnabled = false
self.m_bCreepsEnabled = true
self.i_broadcast_message_duration = 5.0
local hNeutralSpawn = Entities:FindByName( nil, "neutral_caster_spawn" )
self.hNeutralCaster = CreateUnitByName( "npc_dota_neutral_caster", hNeutralSpawn:GetAbsOrigin(), false, nil, nil, DOTA_TEAM_GOODGUYS )
end
function GameMode:BroadcastMsg(message, iDuration)
if iDuration == nil then
iDuration = GameMode.i_broadcast_message_duration
elseif iDuration == -1 then
iDuration = 99999
end
Notifications:BottomToAll({ text = message, duration = iDuration, style = {color = "white"}})
end
require("components/demo/events")
| gpl-2.0 |
Quenty/NevermoreEngine | src/fakeskybox/src/Client/FakeSkybox.lua | 1 | 3225 | --[=[
Allow transitions between skyboxes
@class FakeSkybox
]=]
local require = require(script.Parent.loader).load(script)
local Workspace = game:GetService("Workspace")
local AccelTween = require("AccelTween")
local FakeSkyboxSide = require("FakeSkyboxSide")
local Maid = require("Maid")
local Signal = require("Signal")
local SKYBOX_PROPERTY_IMAGE_MAP = {} do
local properties = {
Top = "Up";
Bottom = "Dn";
-- Bind backwards
Right = "Lf";
Left = "Rt";
Front = "Ft";
Back = "Bk";
}
for Surface, Direction in pairs(properties) do
SKYBOX_PROPERTY_IMAGE_MAP[Enum.NormalId[Surface]] = "Skybox" .. Direction
end
end
local FakeSkybox = {}
FakeSkybox.__index = FakeSkybox
FakeSkybox.ClassName = "FakeSkybox"
FakeSkybox._partSize = 1024
--[=[
Creates a new FakeSkybox
@param skybox Skybox
@return FakeSkybox
]=]
function FakeSkybox.new(skybox)
local self = setmetatable({}, FakeSkybox)
self._maid = Maid.new()
self._parentFolder = Instance.new("Folder")
self._parentFolder.Name = "Skybox"
self._maid:GiveTask(self._parentFolder)
self._sides = {}
for _, NormalId in pairs(Enum.NormalId:GetEnumItems()) do
self._sides[NormalId] = FakeSkyboxSide.new(self._partSize, NormalId, self._parentFolder)
--self._maid[NormalId] = self._sides[NormalId]
end
self._visible = false
self.VisibleChanged = Signal.new()
self._percentVisible = AccelTween.new(0.25)
self._percentVisible.t = 0
self._percentVisible.p = 0
if skybox then
self:SetSkybox(skybox)
end
self._parentFolder.Parent = Workspace.CurrentCamera
return self
end
--[=[
@param partSize number
@return FakeSkybox -- self
]=]
function FakeSkybox:SetPartSize(partSize)
self._partSize = partSize or error("No partSize")
for _, side in pairs(self._sides) do
side:SetPartSize(self._partSize)
end
return self
end
--[=[
@param doNotAnimate boolean
]=]
function FakeSkybox:Show(doNotAnimate)
if self._visible then
return
end
self._visible = true
self._percentVisible.t = 1
if doNotAnimate then
self._percentVisible.p = 1
end
self.VisibleChanged:Fire(self._visible, doNotAnimate)
end
--[=[
@param doNotAnimate boolean
]=]
function FakeSkybox:Hide(doNotAnimate)
if not self._visible then
return
end
self._visible = false
self._percentVisible.t = 0
if doNotAnimate then
self._percentVisible.p = 0
end
self.VisibleChanged:Fire(self._visible, doNotAnimate)
end
--[=[
@param skybox Skybox
@return FakeSkybox -- self
]=]
function FakeSkybox:SetSkybox(skybox)
self._skybox = skybox or error("No skybox")
for normal, side in pairs(self._sides) do
local propertyName = SKYBOX_PROPERTY_IMAGE_MAP[normal]
side:SetImage(skybox[propertyName])
end
return self
end
--[=[
Returns whether the skybox is visible.
@return boolean
]=]
function FakeSkybox:IsVisible()
return self._visible
end
--[=[
Updates the rendering
@param baseCFrame CFrame
]=]
function FakeSkybox:UpdateRender(baseCFrame)
local transparency = 1-self._percentVisible.p
for _, side in pairs(self._sides) do
side:UpdateRender(baseCFrame)
side:SetTransparency(transparency)
end
end
--[=[
Cleans up the fake skybox
]=]
function FakeSkybox:Destroy()
self._maid:DoCleaning()
self._maid = nil
end
return FakeSkybox | mit |
lxl1140989/sdk-for-tb | feeds/routing/luci-app-bmx6/files/usr/lib/lua/luci/model/bmx6json.lua | 16 | 5303 | --[[
Copyright (C) 2011 Pau Escrich <pau@dabax.net>
Contributors Jo-Philipp Wich <xm@subsignal.org>
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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
local ltn12 = require("luci.ltn12")
local json = require("luci.json")
local util = require("luci.util")
local uci = require("luci.model.uci")
local sys = require("luci.sys")
local template = require("luci.template")
local http = require("luci.http")
local string = require("string")
local table = require("table")
local nixio = require("nixio")
local nixiofs = require("nixio.fs")
local ipairs = ipairs
module "luci.model.bmx6json"
-- Returns a LUA object from bmx6 JSON daemon
function get(field, host)
local url
if host ~= nil then
if host:match(":") then
url = 'http://[%s]/cgi-bin/bmx6-info?' % host
else
url = 'http://%s/cgi-bin/bmx6-info?' % host
end
else
url = uci.cursor():get("luci-bmx6","luci","json")
end
if url == nil then
print_error("bmx6 json url not configured, cannot fetch bmx6 daemon data",true)
return nil
end
local json_url = util.split(url,":")
local raw = ""
if json_url[1] == "http" then
raw,err = wget(url..field,1000)
else
if json_url[1] == "exec" then
raw = sys.exec(json_url[2]..' '..field)
else
print_error("bmx6 json url not recognized, cannot fetch bmx6 daemon data. Use http: or exec:",true)
return nil
end
end
local data = nil
if raw and raw:len() > 10 then
local decoder = json.Decoder()
ltn12.pump.all(ltn12.source.string(raw), decoder:sink())
data = decoder:get()
-- else
-- print_error("Cannot get data from bmx6 daemon",true)
-- return nil
end
return data
end
function print_error(txt,popup)
util.perror(txt)
sys.call("logger -t bmx6json " .. txt)
if popup then
http.write('<script type="text/javascript">alert("Some error detected, please check it: '..txt..'");</script>')
else
http.write("<h1>Dammit! some error detected</h1>")
http.write("bmx6-luci: " .. txt)
http.write('<p><FORM><INPUT TYPE="BUTTON" VALUE="Go Back" ONCLICK="history.go(-1)"></FORM></p>')
end
end
function text2html(txt)
txt = string.gsub(txt,"<","{")
txt = string.gsub(txt,">","}")
txt = util.striptags(txt)
return txt
end
function wget(url, timeout)
local rfd, wfd = nixio.pipe()
local pid = nixio.fork()
if pid == 0 then
rfd:close()
nixio.dup(wfd, nixio.stdout)
local candidates = { "/usr/bin/wget", "/bin/wget" }
local _, bin
for _, bin in ipairs(candidates) do
if nixiofs.access(bin, "x") then
nixio.exec(bin, "-q", "-O", "-", url)
end
end
return
else
wfd:close()
rfd:setblocking(false)
local buffer = { }
local err1, err2
while true do
local ready = nixio.poll({{ fd = rfd, events = nixio.poll_flags("in") }}, timeout)
if not ready then
nixio.kill(pid, nixio.const.SIGKILL)
err1 = "timeout"
break
end
local rv = rfd:read(4096)
if rv then
-- eof
if #rv == 0 then
break
end
buffer[#buffer+1] = rv
else
-- error
if nixio.errno() ~= nixio.const.EAGAIN and
nixio.errno() ~= nixio.const.EWOULDBLOCK then
err1 = "error"
err2 = nixio.errno()
end
end
end
nixio.waitpid(pid, "nohang")
if not err1 then
return table.concat(buffer)
else
return nil, err1, err2
end
end
end
function getOptions(name)
-- Getting json and Checking if bmx6-json is avaiable
local options = get("options")
if options == nil or options.OPTIONS == nil then
m.message = "bmx6-json plugin is not running or some mistake in luci-bmx6 configuration, check /etc/config/luci-bmx6"
return nil
else
options = options.OPTIONS
end
-- Filtering by the option name
local i,_
local namedopt = nil
if name ~= nil then
for _,i in ipairs(options) do
if i.name == name and i.CHILD_OPTIONS ~= nil then
namedopt = i.CHILD_OPTIONS
break
end
end
end
return namedopt
end
-- Rturns a help string formated to be used in HTML scope
function getHtmlHelp(opt)
if opt == nil then return nil end
local help = ""
if opt.help ~= nil then
help = text2html(opt.help)
end
if opt.syntax ~= nil then
help = help .. "<br/><b>Syntax: </b>" .. text2html(opt.syntax)
end
return help
end
function testandreload()
local test = sys.call('bmx6 -c --test > /tmp/bmx6-luci.err.tmp')
if test ~= 0 then
return sys.exec("cat /tmp/bmx6-luci.err.tmp")
end
local err = sys.call('bmx6 -c --configReload > /tmp/bmx6-luci.err.tmp')
if err ~= 0 then
return sys.exec("cat /tmp/bmx6-luci.err.tmp")
end
return nil
end
| gpl-2.0 |
rigeirani/crd | plugins/Boobs.lua | 150 | 1613 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. ًں”",
"!butts: Get a butts NSFW image. ًں”"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
ffxiphoenix/darkstar | scripts/globals/mobskills/Ill_Wind.lua | 10 | 1508 | ---------------------------------------------
-- Ill Wind
-- Description: Deals Wind damage to enemies within an area of effect. Additional effect: Dispel
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes Shadows
-- Range: Unknown radial
-- Notes: Only used by Puks in Mamook, Besieged, and the following Notorious Monsters: Vulpangue, Nis Puk, Nguruvilu, Seps , Phantom Puk and Waugyl. Dispels one effect.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1746) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
target:dispelStatusEffect();
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*2.5,ELE_WIND,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
--printf("[TP MOVE] Zone: %u Monster: %u Mob lvl: %u TP: %u TP Move: %u Damage: %u on Player: %u Level: %u HP: %u",mob:getZoneID(),mob:getID(),mob:getMainLvl(),skill:getTP(),skill:getID(),dmg,target:getID(),target:getMainLvl(),target:getMaxHP());
return dmg;
end;
| gpl-3.0 |
Quenty/NevermoreEngine | src/camera/src/Client/Input/CameraInputUtils.lua | 1 | 1272 | --[=[
@class CameraInputUtils
]=]
local UserGameSettings = UserSettings():GetService("UserGameSettings")
local Workspace = game:GetService("Workspace")
local CameraInputUtils = {}
function CameraInputUtils.getPanBy(panDelta, sensivity)
local viewportSize = Workspace.CurrentCamera.ViewportSize
local aspectRatio = CameraInputUtils.getCappedAspectRatio(viewportSize)
local inversionVector = CameraInputUtils.getInversionVector(UserGameSettings)
if CameraInputUtils.isPortraitMode(aspectRatio) then
sensivity = CameraInputUtils.invertSensitivity(sensivity)
end
return inversionVector*sensivity*panDelta
end
function CameraInputUtils.convertToPanDelta(vector3)
return Vector2.new(vector3.x, vector3.y)
end
function CameraInputUtils.getInversionVector(userGameSettings)
return Vector2.new(1, userGameSettings:GetCameraYInvertValue())
end
function CameraInputUtils.invertSensitivity(sensivity)
return Vector2.new(sensivity.y, sensivity.x)
end
function CameraInputUtils.isPortraitMode(aspectRatio)
if aspectRatio < 1 then
return true
end
return false
end
function CameraInputUtils.getCappedAspectRatio(viewportSize)
local x = math.clamp(viewportSize.x, 0, 1920)
local y = math.clamp(viewportSize.y, 0, 1080)
return x/y
end
return CameraInputUtils | mit |
ffxiphoenix/darkstar | scripts/globals/weaponskills/seraph_strike.lua | 30 | 1314 | -----------------------------------
-- Seraph Strike
-- Club weapon skill
-- Skill level: 40
-- Deals light elemental damage to enemy. Damage varies with TP.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: None
-- Modifiers: STR:40% ; MND:40%
-- 100%TP 200%TP 300%TP
-- 2.125 3.675 6.125
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 3;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0;
params.ele = ELE_LIGHT;
params.skill = SKILL_CLB;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 2.125; params.ftp200 = 3.675; params.ftp300 = 6.125;
params.str_wsc = 0.4; params.mnd_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Phrohdoh/OpenRA | mods/d2k/maps/ordos-04/ordos04.lua | 3 | 5429 | --[[
Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
Base =
{
Harkonnen = { HConyard, HRefinery, HHeavyFactory, HLightFactory, HGunTurret1, HGunTurret2, HGunTurret3, HGunTurret4, HGunTurret5, HBarracks, HPower1, HPower2, HPower3, HPower4 },
Smugglers = { SOutpost, SHeavyFactory, SLightFactory, SGunTurret1, SGunTurret2, SGunTurret3, SGunTurret4, SBarracks, SPower1, SPower2, SPower3 }
}
HarkonnenLightInfantryRushers =
{
easy = { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" },
normal = { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" },
hard = { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" }
}
HarkonnenAttackDelay =
{
easy = DateTime.Minutes(3) + DateTime.Seconds(30),
normal = DateTime.Minutes(2) + DateTime.Seconds(30),
hard = DateTime.Minutes(1) + DateTime.Seconds(30)
}
InitialReinforcements =
{
Harkonnen = { "combat_tank_h", "combat_tank_h", "trike", "quad" },
Smugglers = { "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper" }
}
LightInfantryRushersPaths =
{
{ HarkonnenEntry1.Location, HarkonnenRally1.Location },
{ HarkonnenEntry2.Location, HarkonnenRally2.Location },
{ HarkonnenEntry3.Location, HarkonnenRally3.Location }
}
InitialReinforcementsPaths =
{
Harkonnen = { HarkonnenEntry4.Location, HarkonnenRally4.Location },
Smugglers = { SmugglerEntry.Location, SmugglerRally.Location }
}
OrdosReinforcements = { "light_inf", "light_inf", "light_inf", "light_inf" }
OrdosPath = { OrdosEntry.Location, OrdosRally.Location }
SendHarkonnen = function(path)
Trigger.AfterDelay(HarkonnenAttackDelay[Difficulty], function()
if player.IsObjectiveCompleted(KillHarkonnen) then
return
end
local units = Reinforcements.ReinforceWithTransport(harkonnen, "carryall.reinforce", HarkonnenLightInfantryRushers[Difficulty], path, { path[1] })[2]
Utils.Do(units, function(unit)
unit.AttackMove(HarkonnenAttackLocation)
IdleHunt(unit)
end)
end)
end
Hunt = function(house)
Trigger.OnAllKilledOrCaptured(Base[house.Name], function()
Utils.Do(house.GetGroundAttackers(), IdleHunt)
end)
end
CheckHarvester = function(house)
if DateTime.GameTime % DateTime.Seconds(10) == 0 and LastHarvesterEaten[house] then
local units = house.GetActorsByType("harvester")
if #units > 0 then
LastHarvesterEaten[house] = false
ProtectHarvester(units[1], house, AttackGroupSize[Difficulty])
end
end
end
AttackNotifier = 0
Tick = function()
if player.HasNoRequiredUnits() then
harkonnen.MarkCompletedObjective(KillOrdosH)
smuggler.MarkCompletedObjective(KillOrdosS)
smuggler.MarkCompletedObjective(DefendOutpost)
end
if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then
Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat")
player.MarkCompletedObjective(KillHarkonnen)
end
CheckHarvester(harkonnen)
CheckHarvester(smuggler)
AttackNotifier = AttackNotifier - 1
end
WorldLoaded = function()
harkonnen = Player.GetPlayer("Harkonnen")
smuggler = Player.GetPlayer("Smugglers")
player = Player.GetPlayer("Ordos")
InitObjectives(player)
KillOrdosH = harkonnen.AddPrimaryObjective("Kill all Ordos units.")
KillOrdosS = smuggler.AddSecondaryObjective("Kill all Ordos units.")
DefendOutpost = smuggler.AddPrimaryObjective("Don't let the outpost to be captured or destroyed.")
CaptureOutpost = player.AddPrimaryObjective("Capture the Smuggler Outpost.")
KillHarkonnen = player.AddSecondaryObjective("Destroy the Harkonnen.")
SOutpost.GrantCondition("modified")
Camera.Position = OConyard.CenterPosition
HarkonnenAttackLocation = OConyard.Location
Hunt(harkonnen)
Hunt(smuggler)
SendHarkonnen(LightInfantryRushersPaths[1])
SendHarkonnen(LightInfantryRushersPaths[2])
SendHarkonnen(LightInfantryRushersPaths[3])
Actor.Create("upgrade.barracks", true, { Owner = harkonnen })
Actor.Create("upgrade.light", true, { Owner = harkonnen })
Actor.Create("upgrade.barracks", true, { Owner = smuggler })
Actor.Create("upgrade.light", true, { Owner = smuggler })
Trigger.AfterDelay(0, ActivateAI)
Trigger.OnKilled(SOutpost, function()
player.MarkFailedObjective(CaptureOutpost)
end)
Trigger.OnCapture(SOutpost, function()
Trigger.AfterDelay(DateTime.Seconds(2), function()
player.MarkCompletedObjective(CaptureOutpost)
smuggler.MarkFailedObjective(DefendOutpost)
end)
end)
Trigger.OnDamaged(SOutpost, function()
if SOutpost.Owner ~= smuggler then
return
end
if AttackNotifier <= 0 then
AttackNotifier = DateTime.Seconds(10)
Media.DisplayMessage("Don't destroy the Outpost!", "Mentat")
end
end)
Trigger.AfterDelay(HarkonnenAttackDelay[Difficulty] - DateTime.Seconds(5), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, OrdosReinforcements, OrdosPath)
end)
Trigger.AfterDelay(HarkonnenAttackDelay[Difficulty], function()
Media.DisplayMessage("WARNING: Large force approaching!", "Mentat")
end)
end
| gpl-3.0 |
zneext/mtasa-blue | utils/buildactions/install_cef.lua | 3 | 1869 | require 'utils'
premake.modules.install_cef = {}
-- Config variables
local CEF_PATH = "vendor/cef3/"
local CEF_URL = "https://mirror.mtasa.com/bdata/cef-latest.tar.bz2"
local CEF_URL_MD5 = "https://mirror.mtasa.com/bdata/cef-latest.tar.bz2.md5"
newaction {
trigger = "install_cef",
description = "Downloads and installs CEF",
execute = function()
-- Only execute on Windows
if os.host() ~= "windows" then return end
-- Download md5
local correct_checksum, result_string = http.get(CEF_URL_MD5)
if result_string ~= "OK" and result_string then
print("Could not check CEF checksum: "..result_string)
return -- Do nothing and rely on earlier installed files (to allow working offline)
end
-- Trim whitespace
correct_checksum = correct_checksum:gsub("[%s%c]", "")
-- Check md5
local archive_path = CEF_PATH.."temp.tar.bz2"
if os.md5_file(archive_path) == correct_checksum then
print("CEF is already up-to-date")
return
end
-- Download CEF
print("Downloading CEF...")
http.download(CEF_URL, archive_path)
-- Delete old CEF files
-- TODO: It might be better to download the files into a new folder and delete this folder at once
os.rmdir(CEF_PATH.."cmake")
os.rmdir(CEF_PATH.."include")
os.rmdir(CEF_PATH.."libcef_dll")
os.rmdir(CEF_PATH.."Release")
os.rmdir(CEF_PATH.."Resources")
os.remove_wildcard(CEF_PATH.."*.txt")
-- Extract first bz2 and then tar
os.extract_archive(archive_path, CEF_PATH, true) -- Extract .tar.bz2 to .tar
os.extract_archive(CEF_PATH.."temp.tar", CEF_PATH, true) -- Extract .tar
-- Move all files from cef_binary*/* to ./
os.expanddir_wildcard(CEF_PATH.."cef_binary*", CEF_PATH)
-- Delete .tar archive, but keep .tar.bz2 for checksumming
os.remove(CEF_PATH.."temp.tar")
end
}
return premake.modules.install_cef
| gpl-3.0 |
0x0mar/ettercap | src/lua/share/third-party/stdlib/src/string_ext.lua | 12 | 9440 | --- Additions to the string module
-- TODO: Pretty printing (use in getopt); see source for details.
require "table_ext"
local list = require "list"
local strbuf = require "strbuf"
-- Write pretty-printing based on:
--
-- John Hughes's and Simon Peyton Jones's Pretty Printer Combinators
--
-- Based on "The Design of a Pretty-printing Library in Advanced
-- Functional Programming", Johan Jeuring and Erik Meijer (eds), LNCS 925
-- http://www.cs.chalmers.se/~rjmh/Papers/pretty.ps
-- Heavily modified by Simon Peyton Jones, Dec 96
--
-- Haskell types:
-- data Doc list of lines
-- quote :: Char -> Char -> Doc -> Doc Wrap document in ...
-- (<>) :: Doc -> Doc -> Doc Beside
-- (<+>) :: Doc -> Doc -> Doc Beside, separated by space
-- ($$) :: Doc -> Doc -> Doc Above; if there is no overlap it "dovetails" the two
-- nest :: Int -> Doc -> Doc Nested
-- punctuate :: Doc -> [Doc] -> [Doc] punctuate p [d1, ... dn] = [d1 <> p, d2 <> p, ... dn-1 <> p, dn]
-- render :: Int Line length
-- -> Float Ribbons per line
-- -> (TextDetails -> a -> a) What to do with text
-- -> a What to do at the end
-- -> Doc The document
-- -> a Result
--- Give strings a subscription operator.
-- @param s string
-- @param i index
-- @return <code>string.sub (s, i, i)</code> if i is a number, or
-- falls back to any previous metamethod (by default, string methods)
local old__index = getmetatable ("").__index
getmetatable ("").__index = function (s, i)
if type (i) == "number" then
return s:sub (i, i)
-- Fall back to old metamethods
elseif type (old__index) == "function" then
return old__index (s, i)
else
return old__index[i]
end
end
--- Give strings an append metamethod.
-- @param s string
-- @param c character (1-character string)
-- @return <code>s .. c</code>
getmetatable ("").__append = function (s, c)
return s .. c
end
--- Give strings a concat metamethod.
-- @param s string
-- @param o object
-- @return s .. tostring (o)
getmetatable ("").__concat = function (s, o)
return tostring (s) .. tostring (o)
end
--- Capitalise each word in a string.
-- @param s string
-- @return capitalised string
local function caps (s)
return (string.gsub (s, "(%w)([%w]*)",
function (l, ls)
return string.upper (l) .. ls
end))
end
--- Remove any final newline from a string.
-- @param s string to process
-- @return processed string
local function chomp (s)
return (string.gsub (s, "\n$", ""))
end
--- Escape a string to be used as a pattern
-- @param s string to process
-- @return
-- @param s_: processed string
local function escape_pattern (s)
return (string.gsub (s, "(%W)", "%%%1"))
end
-- Escape a string to be used as a shell token.
-- Quotes spaces, parentheses, brackets, quotes, apostrophes and
-- whitespace.
-- @param s string to process
-- @return processed string
local function escape_shell (s)
return (string.gsub (s, "([ %(%)%\\%[%]\"'])", "\\%1"))
end
--- Return the English suffix for an ordinal.
-- @param n number of the day
-- @return suffix
local function ordinal_suffix (n)
n = math.abs (n) % 100
local d = n % 10
if d == 1 and n ~= 11 then
return "st"
elseif d == 2 and n ~= 12 then
return "nd"
elseif d == 3 and n ~= 13 then
return "rd"
else
return "th"
end
end
--- Extend to work better with one argument.
-- If only one argument is passed, no formatting is attempted.
-- @param f format
-- @param ... arguments to format
-- @return formatted string
local _format = string.format
local function format (f, arg1, ...)
if arg1 == nil then
return f
else
return _format (f, arg1, ...)
end
end
--- Justify a string.
-- When the string is longer than w, it is truncated (left or right
-- according to the sign of w).
-- @param s string to justify
-- @param w width to justify to (-ve means right-justify; +ve means
-- left-justify)
-- @param p string to pad with (default: <code>" "</code>)
-- @return justified string
local function pad (s, w, p)
p = string.rep (p or " ", math.abs (w))
if w < 0 then
return string.sub (p .. s, w)
end
return string.sub (s .. p, 1, w)
end
--- Wrap a string into a paragraph.
-- @param s string to wrap
-- @param w width to wrap to (default: 78)
-- @param ind indent (default: 0)
-- @param ind1 indent of first line (default: ind)
-- @return wrapped paragraph
local function wrap (s, w, ind, ind1)
w = w or 78
ind = ind or 0
ind1 = ind1 or ind
assert (ind1 < w and ind < w,
"the indents must be less than the line width")
assert (type (s) == "string",
"bad argument #1 to 'wrap' (string expected, got " .. type (s) .. ")")
local r = strbuf.new ():concat (string.rep (" ", ind1))
local i, lstart, len = 1, ind1, #s
while i <= #s do
local j = i + w - lstart
while #s[j] > 0 and s[j] ~= " " and j > i do
j = j - 1
end
local ni = j + 1
while s[j] == " " do
j = j - 1
end
r:concat (s:sub (i, j))
i = ni
if i < #s then
r:concat ("\n" .. string.rep (" ", ind))
lstart = ind
end
end
return r:tostring ()
end
--- Write a number using SI suffixes.
-- The number is always written to 3 s.f.
-- @param n number
-- @return string
local function numbertosi (n)
local SIprefix = {
[-8] = "y", [-7] = "z", [-6] = "a", [-5] = "f",
[-4] = "p", [-3] = "n", [-2] = "mu", [-1] = "m",
[0] = "", [1] = "k", [2] = "M", [3] = "G",
[4] = "T", [5] = "P", [6] = "E", [7] = "Z",
[8] = "Y"
}
local t = string.format("% #.2e", n)
local _, _, m, e = t:find(".(.%...)e(.+)")
local man, exp = tonumber (m), tonumber (e)
local siexp = math.floor (exp / 3)
local shift = exp - siexp * 3
local s = SIprefix[siexp] or "e" .. tostring (siexp)
man = man * (10 ^ shift)
return tostring (man) .. s
end
--- Do find, returning captures as a list.
-- @param s target string
-- @param p pattern
-- @param init start position (default: 1)
-- @param plain inhibit magic characters (default: nil)
-- @return start of match, end of match, table of captures
local function tfind (s, p, init, plain)
assert (type (s) == "string",
"bad argument #1 to 'tfind' (string expected, got " .. type (s) .. ")")
assert (type (p) == "string",
"bad argument #2 to 'tfind' (string expected, got " .. type (p) .. ")")
local function pack (from, to, ...)
return from, to, {...}
end
return pack (p.find (s, p, init, plain))
end
--- Do multiple <code>find</code>s on a string.
-- @param s target string
-- @param p pattern
-- @param init start position (default: 1)
-- @param plain inhibit magic characters (default: nil)
-- @return list of <code>{from, to; capt = {captures}}</code>
local function finds (s, p, init, plain)
init = init or 1
local l = {}
local from, to, r
repeat
from, to, r = tfind (s, p, init, plain)
if from ~= nil then
table.insert (l, {from, to, capt = r})
init = to + 1
end
until not from
return l
end
--- Split a string at a given separator.
-- FIXME: Consider Perl and Python versions.
-- @param s string to split
-- @param sep separator pattern
-- @return list of strings
local function split (s, sep)
-- finds gets a list of {from, to, capt = {}} lists; we then
-- flatten the result, discarding the captures, and prepend 0 (1
-- before the first character) and append 0 (1 after the last
-- character), and then read off the result in pairs.
local pairs = list.concat ({0}, list.flatten (finds (s, sep)), {0})
local l = {}
for i = 1, #pairs, 2 do
table.insert (l, string.sub (s, pairs[i] + 1, pairs[i + 1] - 1))
end
return l
end
--- Remove leading matter from a string.
-- @param s string
-- @param r leading pattern (default: <code>"%s+"</code>)
-- @return string without leading r
local function ltrim (s, r)
r = r or "%s+"
return (string.gsub (s, "^" .. r, ""))
end
--- Remove trailing matter from a string.
-- @param s string
-- @param r trailing pattern (default: <code>"%s+"</code>)
-- @return string without trailing r
local function rtrim (s, r)
r = r or "%s+"
return (string.gsub (s, r .. "$", ""))
end
--- Remove leading and trailing matter from a string.
-- @param s string
-- @param r leading/trailing pattern (default: <code>"%s+"</code>)
-- @return string without leading/trailing r
local function trim (s, r)
return rtrim (ltrim (s, r), r)
end
-- Save original unextended table.
local unextended = table.clone (string)
local M = {
__index = old__index,
caps = caps,
chomp = chomp,
escape_pattern = escape_pattern,
escape_shell = escape_shell,
finds = finds,
format = format,
ltrim = ltrim,
numbertosi = numbertosi,
ordinal_suffix = ordinal_suffix,
pad = pad,
rtrim = rtrim,
split = split,
tfind = tfind,
trim = trim,
wrap = wrap,
-- camelCase compatibility:
escapePattern = escape_pattern,
escapeShell = escape_shell,
ordinalSuffix = ordinal_suffix,
}
-- Inject stdlib extensions directly into the string package.
_G.string = table.merge (string, M)
return unextended
| gpl-2.0 |
noooway/love2d_arkanoid_tutorial | 3-16_FinalScreen/buttons.lua | 8 | 2279 | local vector = require "vector"
local buttons = {}
function buttons.new_button( o )
return( { position = o.position or vector( 300, 300 ),
width = o.width or 100,
height = o.height or 50,
text = o.text or "hello",
image = o.image or nil,
quad = o.quad or nil,
quad_when_selected = o.quad_when_selected or nil,
selected = false } )
end
function buttons.update_button( single_button, dt )
local mouse_pos = vector( love.mouse.getPosition() )
if( buttons.inside( single_button, mouse_pos ) ) then
single_button.selected = true
else
single_button.selected = false
end
end
function buttons.draw_button( single_button )
if single_button.selected then
if single_button.image and single_button.quad_when_selected then
love.graphics.draw( single_button.image,
single_button.quad_when_selected,
single_button.position.x,
single_button.position.y )
else
love.graphics.rectangle( 'line',
single_button.position.x,
single_button.position.y,
single_button.width,
single_button.height )
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor( 255, 0, 0, 100 )
love.graphics.print( single_button.text,
single_button.position.x,
single_button.position.y )
love.graphics.setColor( r, g, b, a )
end
else
if single_button.image and single_button.quad then
love.graphics.draw( single_button.image,
single_button.quad,
single_button.position.x,
single_button.position.y )
else
love.graphics.rectangle( 'line',
single_button.position.x,
single_button.position.y,
single_button.width,
single_button.height )
love.graphics.print( single_button.text,
single_button.position.x,
single_button.position.y )
end
end
end
function buttons.inside( single_button, pos )
return
single_button.position.x < pos.x and
pos.x < ( single_button.position.x + single_button.width ) and
single_button.position.y < pos.y and
pos.y < ( single_button.position.y + single_button.height )
end
function buttons.mousereleased( single_button, x, y, button )
return single_button.selected
end
return buttons
| mit |
ffxiphoenix/darkstar | scripts/globals/mobskills/Necropurge.lua | 43 | 1080 | ---------------------------------------------
-- Necropurge
--
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1839) then
return 0;
else
return 1;
end
end
if(mob:getFamily() == 91) then
local mobSkin = mob:getModelId();
if (mobSkin == 1840) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 10;
local dmgmod = 2;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
MobStatusEffectMove(mob, target, EFFECT_CURSE_I, 1, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
JamesPan/orz-ops | nginx/lua/dynamic-upstream-weight.lua | 1 | 4830 |
local string2array = function (str)
local arr = {}
if str == nil or str == '' then
return arr
end
for field in string.gmatch(str, "([^, ]+)") do
table.insert(arr, field)
end
return arr
end
local update_server_res_time = function (addr, time, dict, passed_weight, current_weight)
local passed_time = dict:get(addr) or 0
local current_time = tonumber(time)
if current_time == nil then
current_time = passed_time
end
local new_time = passed_time * passed_weight + current_time * current_weight
dict:set(addr, new_time)
return new_time, passed_time
end
--check if we need to update the weights, with some strategy
local check_if_update_weight = function (addr, new_time, old_time, dict)
local diff = math.abs((new_time - old_time) / old_time)
local threshold = 3
if diff > threshold then
ngx.log(ngx.ALERT, "need to update upstream weight because diff " .. diff .. " greater than ".. threshold .. " on " .. addr)
return true
end
local ever_max = dict:get("max") or -math.huge
if new_time > ever_max then
ngx.log(ngx.ALERT, "need to update upstream weight because max value outdated")
return true
end
local ever_min = dict:get("min") or math.huge
if new_time < ever_min then
ngx.log(ngx.ALERT, "need to update upstream weight because min value outdated")
return true
end
return false
end
local check_if_weight_changed_unexpected = function (ups, upsteam_name, dict)
local servers, err = ups.get_primary_peers(upsteam_name)
if not servers then
ngx.log(ngx.ALERT, "get upstream " .. upsteam_name .. " fail, " .. err)
return false
end
for _, server in ipairs(servers) do
local server_name = server["name"]
local actual = server["weight"]
local expect = dict:get(server_name) or 1
if actual ~= expect then
ngx.log(ngx.ALERT, "need to update upstream weight because different config found " .. server_name .. "~" .. expect .. "~" .. actual)
return true
end
end
return false
end
local gen_server_time_map = function(dict)
local keys = dict:get_keys(100)
local map = {}
for _, key in ipairs(keys) do
local time = dict:get(key)
map[key] = time
end
return map
end
local min_max = function (t)
local max = -math.huge
local min = math.huge
for k, v in pairs(t) do
max = math.max(max, v)
min = math.min(min, v)
end
return min, max
end
local update_server_weight = function (ups, upsteam_name, dict, server_time_map, max_time)
local servers, err = ups.get_primary_peers(upsteam_name)
if not servers then
ngx.log(ngx.ALERT, "get upstream " .. upsteam_name .. " fail, " .. err)
return
end
for _, server in ipairs(servers) do
local server_name = server["name"]
local id = server["id"]
local fails = server["fails"]
local time = server_time_map[server_name]
local weight = 0
if fails > 0 then
weight = 1
ngx.log(ngx.ALERT, "down grade " .. server_name .. " because it fail " .. fails .. " times")
elseif time ~= nil and time > 0 then
weight = math.ceil(max_time / time)
end
if weight > 0 then
ups.set_peer_weight(upsteam_name, false, id, weight)
ups.set_peer_effective_weight(upsteam_name, false, id, weight)
ups.set_peer_current_weight(upsteam_name, false, id, 0)
dict:set(server_name, weight)
end
end
end
local res_time_dict = ngx.shared.upstream_res_time_dict
local weight_dict = ngx.shared.upstream_weight_dict
local upstream = require "ngx.upstream"
local ups_identity = "backend_blog_jamespan_me"
--it may have multi address and times if nginx tried more than 1 upstream servers
--but most of the time, there's only one address and time
local addrs = string2array(ngx.var.upstream_addr)
local times = string2array(ngx.var.upstream_response_time)
local need_update_weight = false
for idx, addr in ipairs(addrs) do
local time = times[idx]
local new_time, old_time = update_server_res_time(addr, time, res_time_dict, 0.3, 0.7)
need_update_weight = check_if_update_weight(addr, new_time, old_time, res_time_dict)
end
if not need_update_weight then
need_update_weight = check_if_weight_changed_unexpected(upstream, ups_identity, weight_dict)
end
if need_update_weight then
local server_time_map = gen_server_time_map(res_time_dict)
local min_time, max_time = min_max(server_time_map)
res_time_dict:set("max", max_time)
res_time_dict:set("min", min_time)
update_server_weight(upstream, ups_identity, weight_dict, server_time_map, max_time)
end
| gpl-2.0 |
ffxiphoenix/darkstar | scripts/globals/spells/bluemagic/poison_breath.lua | 18 | 2069 | -----------------------------------------
-- Spell: Poison Breath
-- Deals water damage to enemies within a fan-shaped area originating from the caster. Additional effect: Poison
-- Spell cost: 22 MP
-- Monster Type: Hound
-- Spell Type: Magical (Water)
-- Blue Magic Points: 1
-- Stat Bonus: MND+1
-- Level: 22
-- Casting Time: 3 seconds
-- Recast Time: 19.5 seconds
-- Magic Bursts on: Reverberation, Distortion, and Darkness
-- Combos: Clear Mind
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0);
local multi = 1.08;
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.multiplier = multi;
params.tMultiplier = 1.5;
params.duppercap = 69;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.3;
params.chr_wsc = 0.0;
damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then
multi = multi + 0.50;
end
if (damage > 0 and resist > 0.3) then
local typeEffect = EFFECT_POISON;
target:delStatusEffect(typeEffect);
target:addStatusEffect(typeEffect,3,0,getBlueEffectDuration(caster,resist,typeEffect));
end
return damage;
end; | gpl-3.0 |
gregier/libpeas | loaders/lua5.1/resources/peas-lua-strict.lua | 4 | 1512 | --
-- Copyright (C) 2015 - Garrett Regier
--
-- libpeas is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- libpeas is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
--
-- Modified version of: http://metalua.luaforge.net/src/lib/strict.lua.html
__STRICT = true
local mt = getmetatable(_G)
if mt == nil then
mt = {}
setmetatable(_G, mt)
end
function mt:__newindex(name, value)
if __STRICT then
local what = debug.getinfo(2, 'S').what
if what ~= 'C' then
error("Attempted to create global variable '" ..
tostring(name) .. "'", 2)
end
end
rawset(self, name, value)
end
function mt:__index(name)
if not __STRICT or debug.getinfo(2, 'S').what == 'C' then
return rawget(self, name)
end
error("Attempted to access nonexistent " ..
"global variable '" .. tostring(name) .. "'", 2)
end
-- ex:ts=4:et:
| lgpl-2.1 |
jledet/backfire-git | package/uci/trigger/lib/trigger.lua | 40 | 8391 | module("uci.trigger", package.seeall)
require("posix")
require("uci")
local path = "/lib/config/trigger"
local triggers = nil
local tmp_cursor = nil
function load_modules()
if triggers ~= nil then
return
end
triggers = {
list = {},
uci = {},
active = {}
}
local modules = posix.glob(path .. "/*.lua")
if modules == nil then
return
end
local oldpath = package.path
package.path = path .. "/?.lua"
for i, v in ipairs(modules) do
pcall(require(string.gsub(v, path .. "/(%w+)%.lua$", "%1")))
end
package.path = oldpath
end
function check_table(table, name)
if table[name] == nil then
table[name] = {}
end
return table[name]
end
function get_table_val(val, vtype)
if type(val) == (vtype or "string") then
return { val }
elseif type(val) == "table" then
return val
end
return nil
end
function get_name_list(name)
return get_table_val(name or ".all")
end
function add_trigger_option(list, t)
local name = get_name_list(t.option)
for i, n in ipairs(name) do
option = check_table(list, n)
table.insert(option, t)
end
end
function add_trigger_section(list, t)
local name = get_name_list(t.section)
for i, n in ipairs(name) do
section = check_table(list, n)
add_trigger_option(section, t)
end
end
function check_insert_triggers(dest, list, tuple)
if list == nil then
return
end
for i, t in ipairs(list) do
local add = true
if type(t.check) == "function" then
add = t.check(tuple)
end
if add then
dest[t.id] = t
end
end
end
function find_section_triggers(tlist, pos, tuple)
if pos == nil then
return
end
check_insert_triggers(tlist, pos[".all"], tuple)
if tuple.option then
check_insert_triggers(tlist, pos[tuple.option], tuple)
end
end
function check_recursion(name, seen)
if seen == nil then
seen = {}
end
if seen[name] then
return nil
end
seen[name] = true
return seen
end
function find_recursive_depends(list, name, seen)
seen = check_recursion(name, seen)
if not seen then
return
end
local bt = get_table_val(triggers.list[name].belongs_to) or {}
for i, n in ipairs(bt) do
table.insert(list, n)
find_recursive_depends(list, n, seen)
end
end
function check_trigger_depth(list, name)
if name == nil then
return
end
local n = list[name]
if n == nil then
return
end
list[name] = nil
return check_trigger_depth(list, n)
end
function find_triggers(tuple)
local pos = triggers.uci[tuple.package]
if pos == nil then
return {}
end
local tlist = {}
find_section_triggers(tlist, pos[".all"], tuple)
find_section_triggers(tlist, pos[tuple.section[".type"]], tuple)
for n, t in pairs(tlist) do
local dep = {}
find_recursive_depends(dep, t.id)
for i, depname in ipairs(dep) do
check_trigger_depth(tlist, depname)
end
end
local nlist = {}
for n, t in pairs(tlist) do
if t then
table.insert(nlist, t)
end
end
return nlist
end
function reset_state()
assert(io.open("/var/run/uci_trigger", "w")):close()
if tctx then
tctx:unload("uci_trigger")
end
end
function load_state()
-- make sure the config file exists before we attempt to load it
-- uci doesn't like loading nonexistent config files
local f = assert(io.open("/var/run/uci_trigger", "a")):close()
load_modules()
triggers.active = {}
if tctx then
tctx:unload("uci_trigger")
else
tctx = uci.cursor()
end
assert(tctx:load("/var/run/uci_trigger"))
tctx:foreach("uci_trigger", "trigger",
function(section)
trigger = triggers.list[section[".name"]]
if trigger == nil then
return
end
active = {}
triggers.active[trigger.id] = active
local s = get_table_val(section["sections"]) or {}
for i, v in ipairs(s) do
active[v] = true
end
end
)
end
function get_names(list)
local slist = {}
for name, val in pairs(list) do
if val then
table.insert(slist, name)
end
end
return slist
end
function check_cancel(name, seen)
local t = triggers.list[name]
local dep = get_table_val(t.belongs_to)
seen = check_recursion(name, seen)
if not t or not dep or not seen then
return false
end
for i, v in ipairs(dep) do
-- only cancel triggers for all sections
-- if both the current and the parent trigger
-- are per-section
local section_only = false
if t.section_only then
local tdep = triggers.list[v]
if tdep then
section_only = tdep.section_only
end
end
if check_cancel(v, seen) then
return true
end
if triggers.active[v] then
if section_only then
for n, active in pairs(triggers.active[v]) do
triggers.active[name][n] = false
end
else
return true
end
end
end
return false
end
-- trigger api functions
function add(ts)
for i,t in ipairs(ts) do
triggers.list[t.id] = t
match = {}
if t.package then
local package = check_table(triggers.uci, t.package)
add_trigger_section(package, t)
triggers.list[t.id] = t
end
end
end
function save_trigger(name)
if triggers.active[name] then
local slist = get_names(triggers.active[name])
if #slist > 0 then
tctx:set("uci_trigger", name, "sections", slist)
end
else
tctx:delete("uci_trigger", name)
end
end
function set(data, cursor)
assert(data ~= nil)
if cursor == nil then
cursor = tmp_cursor or uci.cursor()
tmp_cursor = uci.cursor
end
local tuple = {
package = data[1],
section = data[2],
option = data[3],
value = data[4]
}
assert(cursor:load(tuple.package))
load_state()
local section = cursor:get_all(tuple.package, tuple.section)
if (section == nil) then
if option ~= nil then
return
end
section = {
[".type"] = value
}
if tuple.section == nil then
tuple.section = ""
section[".anonymous"] = true
end
section[".name"] = tuple.section
end
tuple.section = section
local ts = find_triggers(tuple)
for i, t in ipairs(ts) do
local active = triggers.active[t.id]
if not active then
active = {}
triggers.active[t.id] = active
tctx:set("uci_trigger", t.id, "trigger")
end
if section[".name"] then
active[section[".name"]] = true
end
save_trigger(t.id)
end
tctx:save("uci_trigger")
end
function get_description(trigger, sections)
if not trigger.title then
return trigger.id
end
local desc = trigger.title
if trigger.section_only and sections and #sections > 0 then
desc = desc .. " (" .. table.concat(sections, ", ") .. ")"
end
return desc
end
function get_active()
local slist = {}
if triggers == nil then
load_state()
end
for name, val in pairs(triggers.active) do
if val and not check_cancel(name) then
local sections = {}
for name, active in pairs(triggers.active[name]) do
if active then
table.insert(sections, name)
end
end
table.insert(slist, { triggers.list[name], sections })
end
end
return slist
end
function set_active(trigger, sections)
if triggers == nil then
load_state()
end
if not triggers.list[trigger] then
return
end
if triggers.active[trigger] == nil then
tctx:set("uci_trigger", trigger, "trigger")
triggers.active[trigger] = {}
end
local active = triggers.active[trigger]
if triggers.list[trigger].section_only or sections ~= nil then
for i, t in ipairs(sections) do
triggers.active[trigger][t] = true
end
end
save_trigger(trigger)
tctx:save("uci_trigger")
end
function clear_active(trigger, sections)
if triggers == nil then
load_state()
end
if triggers.list[trigger] == nil or triggers.active[trigger] == nil then
return
end
local active = triggers.active[trigger]
if not triggers.list[trigger].section_only or sections == nil then
triggers.active[trigger] = nil
else
for i, t in ipairs(sections) do
triggers.active[trigger][t] = false
end
end
save_trigger(trigger)
tctx:save("uci_trigger")
end
function run(ts)
if ts == nil then
ts = get_active()
end
for i, t in ipairs(ts) do
local trigger = t[1]
local sections = t[2]
local actions = get_table_val(trigger.action, "function") or {}
for ai, a in ipairs(actions) do
if not trigger.section_only then
sections = { "" }
end
for si, s in ipairs(sections) do
if a(s) then
tctx:delete("uci_trigger", trigger.id)
tctx:save("uci_trigger")
end
end
end
end
end
-- helper functions
function system_command(arg)
local cmd = arg
return function(arg)
return os.execute(cmd:format(arg)) == 0
end
end
function service_restart(arg)
return system_command("/etc/init.d/" .. arg .. " restart")
end
| gpl-2.0 |
PouriaDev/Signal-New | plugins/Plugins.lua | 1 | 4080 | do
local function plugin_enabled(name)
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
return false
end
local function plugin_exists(name)
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
local status = '➖'
nsum = nsum+1
nact = 0
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '➕'
end
nact = nact+1
end
if not only_enabled or status == '➕' then
v = string.match (v, "(.*)%.lua")
text = text..nsum..'.'..status..' '..v..' \n'
end
end
local text = text..'\n\n'..nsum..' پلاگین های نصب شده\n\n'..nact..' پلاگین های فعال\n\n'..nsum-nact..' پلاگین های غیرفعال'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
local status = '➖'
nsum = nsum+1
nact = 0
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '➕'
end
nact = nact+1
end
if not only_enabled or status == '➕' then
v = string.match (v, "(.*)%.lua")
end
end
local text = text..'\nپلاگین ها بروزرسانی شدند\n\n'..nact..' پلاگین های فعال\n'..nsum..' پلاگین های نصب شده\n'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
local function enable_plugin(plugin_name)
print('checking if '..plugin_name..' exists')
if plugin_enabled(plugin_name) then
text = 'پلاگین[ '..plugin_name..' ] فعال است'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
elseif plugin_exists(plugin_name) then
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
text = 'پلاگین [ '..plugin_name..' ]فعال شد'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
save_config()
return reloadplugins( )
else
text = 'پلاگین [ '..plugin_name..' ]وجود ندارد.'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
end
local function disable_plugin(name, chat)
if not plugin_exists(name) then
text = 'پلاگین [ '..name..' ]وجود ندارد'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
local k = plugin_enabled(name)
if not k then
text = 'پلاگین[ '..name..' ] فعال نیست'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
table.remove(_config.enabled_plugins, k)
save_config( )
text = 'پلاگین[ '..name..' ] غیر فعال شد.'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
return reloadplugins(true)
end
local function run(msg, matches)
if matches[1] == 'plugins' and is_sudo(msg) then
return list_all_plugins()
end
if matches[2] == '+' and is_sudo(msg) then
local plugin_name = matches[3]
print("enable: "..matches[3])
return enable_plugin(plugin_name)
end
end
if matches[2] == '-' and is_sudo(msg) then
if matches[3] == 'plugins' then
text = 'This plugin can\'t be disabled'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
print("disable: "..matches[3])
return disable_plugin(matches[3])
end
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
text = 'بارگذاری مجدد انجام شد.'
bot.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
return reloadplugins(true)
end
end
return {
patterns = {
"^[/#!](plugins)$",
"^[/#!](reload)$",
"^[/#!]plugins? (+) ([%w_%.%-]+)$",
"^[/#!]plugins? (-) ([%w_%.%-]+)$",
"^!!!edit:[/#!]plugins? (+) ([%w_%.%-]+)$",
"^!!!edit:[/#!]plugins? (+) ([%w_%.%-]+)$",
"^!!!edit:[/#!]plugins? (-) ([%w_%.%-]+)$",
"^!!!edit:[/#!]plugins? (-) ([%w_%.%-]+)$",
},
run = run,
}
| gpl-3.0 |
moonlight/blues-brothers-rpg | data/scripts/MusicController.lua | 2 | 3503 | --
-- This file contains the music controller. It can be told to play and stop
-- songs. As a bonus, it can also dynamically change the parameters of a
-- channel over a period of time. Using this feature it can fade from one
-- music to another.
--
-- By Bjorn Lindeijer
MC_NORMAL = 0
MC_FADE_IN = 1
MC_FADE_OUT = 2
MC_FADE_BETWEEN = 3
MusicControl = {
state = MC_NORMAL,
currentChannel = -1,
fadeInChannel = 1,
fadeProgress = 0,
fadeTime = 0,
}
function MusicControl:init()
self.channels = m_get_number_of_channels() or 0
end
function MusicControl:update()
if (self.state == MC_FADE_BETWEEN or self.state == MC_FADE_IN or self.state == MC_FADE_OUT) then
self.fadeProgress = self.fadeProgress + 1
if (self.state == MC_FADE_BETWEEN) then
if (self.fadeProgress > self.fadeTime or self.fadeTime <= 0) then
self.state = MC_NORMAL
self.fadeProgress = self.fadeTime
m_stop_music(self.currentChannel)
self.currentChannel = self.fadeInChannel
m_adjust_channel(self.currentChannel, 255, 128, 1000)
else
m_adjust_channel(self.fadeInChannel, (self.fadeProgress / self.fadeTime) * 255, 128, 1000)
m_adjust_channel(self.currentChannel, ((self.fadeTime - self.fadeProgress) / self.fadeTime) * 255, 128, 1000)
end
end
if (self.state == MC_FADE_IN) then
if (self.fadeProgress > self.fadeTime or self.fadeTime <= 0) then
self.state = MC_NORMAL
self.fadeProgress = self.fadeTime
m_adjust_channel(self.currentChannel, 255, 128, 1000)
else
m_adjust_channel(self.currentChannel, (self.fadeProgress / self.fadeTime) * 255, 128, 1000)
end
end
if (self.state == MC_FADE_OUT) then
if (self.fadeProgress > self.fadeTime or self.fadeTime <= 0) then
self.state = MC_NORMAL
self.fadeProgress = self.fadeTime
m_stop_music(self.currentChannel)
self.currentChannel = -1
else
m_adjust_channel(self.currentChannel, ((self.fadeTime - self.fadeProgress) / self.fadeTime) * 255, 128, 1000)
end
end
end
end
function MusicControl:play_song(filename)
self:stop_all_music()
-- play this song on the first channel
self.currentChannel = 0
self.currentSong = filename
m_play_music(filename, self.currentChannel)
m_adjust_channel(self.currentChannel, 255, 128, 1000)
end
function MusicControl:stop_all_music()
-- stop music on all channels
for i = 0,self.channels-1 do
m_stop_music(i)
end
end
function MusicControl:fade_to_song(filename, time)
if (not (time > 0)) then
self:play_song(filename)
return
end
if (self.currentChannel == -1) then
self:fade_in(filename, time)
return
end
self.state = MC_FADE_BETWEEN
self.fadeTime = time
self.fadeProgress = 0
self.fadeInChannel = self.currentChannel + 1
if (self.fadeInChannel == self.channels) then self.fadeInChannel = 0 end
-- Start playing music and set volume to 0
self.currentSong = filename
m_play_music(filename, self.fadeInChannel)
self:update()
end
function MusicControl:fade_out(time)
if (self.currentChannel >= 0) then
self.state = MC_FADE_OUT
self.fadeTime = time
self.fadeProgress = 0
else
m_message("MusicControl:fade_out - Warning, no music to fade out")
end
end
function MusicControl:fade_in(filename, time)
self:play_song(filename)
self.state = MC_FADE_IN
self.fadeTime = time
self.fadeProgress = 0
m_adjust_channel(self.currentChannel, 0, 128, 1000)
end | gpl-2.0 |
vilarion/Illarion-Content | triggerfield/akaltutschamber_mudwarp.lua | 5 | 1625 | --[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- Mudslide triggerfield in Akaltutschamber
-- INSERT INTO triggerfields VALUES (481,812,-9,'triggerfield.akaltutschamber_mudwarp');
-- INSERT INTO triggerfields VALUES (482,812,-9,'triggerfield.akaltutschamber_mudwarp');
local common = require("base.common")
local M = {}
function M.MoveToField(Character)
-- mudslide: 481 812 -9 and 482 812 -9
local destination
if Character.pos == position(481, 812, -9) or Character.pos == position(482, 812, -9) then --mudslide
destination = position(484, 821, -9)
common.HighInformNLS(Character,
"Du stolperst und fällst von der Brücke und rutscht in den Schlamm.",
"You stumble, falling down the bridge, sliding and slipping into the mud.")
end
--Warping the character
world:gfx(41, Character.pos)
world:makeSound(13, Character.pos)
Character:warp(destination)
world:makeSound(13, destination)
world:gfx(41, Character.pos)
end
return M
| agpl-3.0 |
AfuSensi/Mr.Green-MTA-Resources | resources/[admin]/anti/colstate_c.lua | 4 | 1240 | local theCollisionlessTable = {}
addEventHandler("onClientResourceStart",resourceRoot,function() triggerServerEvent("onClientRequestCollisionlessTable",resourceRoot) end)
addEvent("onClientReceiveCollisionlessTable",true)
addEventHandler("onClientReceiveCollisionlessTable",root,function(t)
theCollisionlessTable = t
for _, p in ipairs(getElementsByType'player') do
setElementData(p, 'markedlagger', t[p] or nil, false)
end
setCollision("refresh")
end)
-- addEvent("onPlayerVehicleIDChange",true)
function setCollision()
local mode = getResourceFromName'race' and getResourceState(getResourceFromName'race')=='running' and exports.race:getRaceMode()
if not mode or mode == "Shooter" then return end
for p,_ in pairs(theCollisionlessTable) do
if p ~= localPlayer then
local vehMe = getPedOccupiedVehicle(localPlayer)
local vehCollLess = getPedOccupiedVehicle(p)
if vehMe and vehCollLess then
setElementCollidableWith(vehMe, vehCollLess, false)
setElementAlpha(vehCollLess, 140)
end
end
end
end
setTimer(setCollision,50,0)
-- addEventHandler("onPlayerVehicleIDChange",root,setCollision)
addEventHandler("onClientExplosion",root,function() if theCollisionlessTable[source] then cancelEvent() end end) | mit |
aqasaeed/tele | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
moonlight/blues-brothers-rpg | data/scripts/GuiTheme.lua | 1 | 2791 | --
-- The GUI theme
-- By Bjorn Lindeijer
import("Object.lua")
GuiTheme = Object:subclass
{
name = "GuiTheme";
init = function(self)
self.cornerUL = m_create_sub_bitmap(self.bitmap, 1, 0, 2, 2)
self.cornerUR = m_create_sub_bitmap(self.bitmap, 3, 0, 2, 2)
self.cornerLL = m_create_sub_bitmap(self.bitmap, 1, 2, 2, 2)
self.cornerLR = m_create_sub_bitmap(self.bitmap, 3, 2, 2, 2)
self.borderU = m_create_sub_bitmap(self.bitmap, 9, 0, 2, 2)
self.borderL = m_create_sub_bitmap(self.bitmap, 11, 0, 2, 2)
self.borderR = m_create_sub_bitmap(self.bitmap, 11, 2, 2, 2)
self.borderD = m_create_sub_bitmap(self.bitmap, 9, 2, 2, 2)
self.bg = m_create_sub_bitmap(self.bitmap, 0, 0, 1, 1)
self.shadow = m_create_sub_bitmap(self.bitmap, 0, 1, 1, 1)
self.shadowUL = m_create_sub_bitmap(self.bitmap, 5, 0, 2, 2)
self.shadowUR = m_create_sub_bitmap(self.bitmap, 7, 0, 2, 2)
self.shadowLL = m_create_sub_bitmap(self.bitmap, 5, 2, 2, 2)
self.shadowLR = m_create_sub_bitmap(self.bitmap, 7, 2, 2, 2)
self.canvas = Canvas()
end;
drawBox = function(self, x, y, w, h)
self.canvas:setDrawMode(DM_TRANS)
-- Shadow
local alpha = m_set_alpha(64)
self:drawBoxEx(
self.shadow,
self.shadowUL, self.shadowUR, self.shadowLL, self.shadowLR,
self.shadow, self.shadow, self.shadow, self.shadow,
x+2, y+2, w, h
)
-- The actual box
m_set_alpha(192)
self:drawBoxEx(
self.bg,
self.cornerUL, self.cornerUR, self.cornerLL, self.cornerLR,
self.borderU, self.borderL, self.borderR, self.borderD,
x, y, w, h
)
m_set_alpha(alpha)
end;
drawLightBox = function(self, x, y, w, h)
self.canvas:setDrawMode(DM_TRANS)
local alpha = m_set_alpha(192)
self:drawBoxEx(
self.bg,
self.cornerUL, self.cornerUR, self.cornerLL, self.cornerLR,
self.borderU, self.borderL, self.borderR, self.borderD,
x, y, w, h
)
m_set_alpha(alpha)
end;
getTextColor = function(self)
return 170, 170, 170
end;
drawBoxEx = function(self, bg, ul, ur, ll, lr, bu, bl, br, bd, x, y, w, h)
m_set_cursor(x, y)
self.canvas:drawIcon(ul)
self.canvas:drawRect(bu, w - (self.borderWidth * 2), self.borderWidth)
self.canvas:drawIcon(ur)
m_set_cursor(x, y + self.borderWidth)
self.canvas:drawRect(bl, self.borderWidth, h - (self.borderWidth * 2))
self.canvas:drawRect(bg, w - (self.borderWidth * 2), h - (self.borderWidth * 2))
self.canvas:drawRect(br, self.borderWidth, h - (self.borderWidth * 2))
m_set_cursor(x, y + h - self.borderWidth)
self.canvas:drawIcon(ll)
self.canvas:drawRect(bd, w - (self.borderWidth * 2), self.borderWidth)
self.canvas:drawIcon(lr)
end;
defaultproperties =
{
bitmap = m_get_bitmap("gui_green.bmp"),
font = "font_sansserif_8",
borderWidth = 2,
canvas = nil,
};
}
| gpl-2.0 |
crzang/awesome-config | crzang/widget/temp_widget.lua | 1 | 1683 | --
-- Created by IntelliJ IDEA.
-- User: crzang
-- Date: 12.01.15
-- Time: 0:01
-- To change this template use File | Settings | File Templates.
--
local setmetatable = setmetatable
local first_line = require("crzang.lib").helpers.first_line
local temp_widget = { mt = {} }
local indicator = require("crzang.widget.indicator")
local io = { open = io.open }
local tonumber = tonumber
local temp = {
}
local function get_temp()
temp_now={}
local tempfile ="/sys/class/thermal/thermal_zone0/temp"
local trip_tempfile = "/sys/class/thermal/thermal_zone0/trip_point_0_temp"
local f = io.open(tempfile)
if f ~= nil
then
temp_now.coretemp = tonumber(f:read("*a")) / 1000
f:close()
else
temp_now.coretemp = 0
end
local max_f = io.open(trip_tempfile)
if max_f ~= nil
then
temp_now.max = tonumber(max_f:read("*a")) / 1000
max_f:close()
else
temp_now.max = 0
end
return temp_now
end
local function new(image)
local args = {
max_value = function()
temp_now = get_temp()
return temp_now.max
end,
get_value = function()
temp_now = get_temp()
return temp_now.coretemp
end,
icon = image,
get_hint = function()
temp_now = get_temp()
local hint = "Temp \n" ..
"Max : " .. temp_now.max .. "\n" ..
"Current : " .. temp_now.coretemp .. "\n"
return hint
end
}
return indicator(args)
end
function temp_widget.mt:__call(...)
return new(...)
end
return setmetatable(temp_widget, temp_widget.mt) | apache-2.0 |
ffxiphoenix/darkstar | scripts/globals/items/boiled_crayfish.lua | 35 | 1248 | -----------------------------------------
-- ID: 4535
-- Item: Boiled Crayfish
-- Food Effect: 30Min, All Races
-----------------------------------------
-- defense % 30
-- defense % 25
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4535);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_DEFP, 30);
target:addMod(MOD_FOOD_DEF_CAP, 25);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_DEFP, 30);
target:delMod(MOD_FOOD_DEF_CAP, 25);
end;
| gpl-3.0 |
kondrak/ProDBG | bin/win32/scripts/tundra/syntax/rust-cargo.lua | 5 | 7385 | -- rust-cargo.lua - Support for Rust and Cargo
module(..., package.seeall)
local nodegen = require "tundra.nodegen"
local files = require "tundra.syntax.files"
local path = require "tundra.path"
local util = require "tundra.util"
local depgraph = require "tundra.depgraph"
local native = require "tundra.native"
_rust_cargo_program_mt = nodegen.create_eval_subclass { }
_rust_cargo_shared_lib_mt = nodegen.create_eval_subclass { }
_rust_cargo_crate_mt = nodegen.create_eval_subclass { }
-- This function will gather up so extra dependencies. In the case when we depend on a Rust crate
-- We simply return the sources to allow the the unit being built to depend on it. The reason
-- for this is that Cargo will not actually link with this step but it's only used to make
-- sure it gets built when a Crate changes
function get_extra_deps(data, env)
local libsuffix = { env:get("LIBSUFFIX") }
local sources = data.Sources
local source_depts = {}
local extra_deps = {}
for _, dep in util.nil_ipairs(data.Depends) do
if dep.Keyword == "StaticLibrary" then
local node = dep:get_dag(env:get_parent())
extra_deps[#extra_deps + 1] = node
node:insert_output_files(sources, libsuffix)
elseif dep.Keyword == "RustCrate" then
local node = dep:get_dag(env:get_parent())
source_depts[#source_depts + 1] = dep.Decl.Sources
end
end
return extra_deps, source_depts
end
local cmd_line_type_prog = 0
local cmd_line_type_shared_lib = 1
local cmd_line_type_crate = 2
function build_rust_action_cmd_line(env, data, program)
local static_libs = ""
-- build an string with all static libs this code depends on
for _, dep in util.nil_ipairs(data.Depends) do
if dep.Keyword == "StaticLibrary" then
local node = dep:get_dag(env:get_parent())
static_libs = static_libs .. dep.Decl.Name .. " "
end
end
-- The way Cargo sets it's target directory is by using a env variable which is quite ugly but that is the way it works.
-- So before running the command we set the target directory of
-- We also set the tundra cmd line as env so we can use that inside the build.rs
-- to link with the libs in the correct path
local target = path.join("$(OBJECTDIR)", "__" .. data.Name)
local target_dir = ""
local tundra_dir = "$(OBJECTDIR)";
local export = "export ";
local merge = " ; ";
if native.host_platform == "windows" then
export = "set "
merge = "&&"
end
target_dir = export .. "CARGO_TARGET_DIR=" .. target .. merge
tundra_dir = export .. "TUNDRA_OBJECTDIR=" .. tundra_dir .. merge
if static_libs ~= "" then
-- Remove trailing " "
local t = string.sub(static_libs, 1, string.len(static_libs) - 1)
static_libs = export .. "TUNDRA_STATIC_LIBS=" .. t .. merge
end
local variant = env:get('CURRENT_VARIANT')
local release = ""
local output_target = ""
local output_name = ""
-- Make sure output_name gets prefixed/sufixed correctly
if program == cmd_line_type_prog then
output_name = data.Name .. "$(HOSTPROGSUFFIX)"
elseif program == cmd_line_type_shared_lib then
output_name = "$(SHLIBPREFIX)" .. data.Name .. "$(HOSTSHLIBSUFFIX)"
else
output_name = "$(SHLIBPREFIX)" .. data.Name .. ".rlib"
end
-- If variant is debug (default) we assume that we should use debug and not release mode
if variant == "debug" then
output_target = path.join(target, "debug$(SEP)" .. output_name)
else
output_target = path.join(target, "release$(SEP)" .. output_name)
release = " --release "
end
-- If user hasn't set any specific cargo opts we use build as default
-- Setting RUST_CARGO_OPTS = "build" by default doesn't seem to work as if user set
-- RUST_CARGO_OPTS = "test" the actual string is "build test" which doesn't work
local cargo_opts = env:interpolate("$(RUST_CARGO_OPTS)")
if cargo_opts == "" then
cargo_opts = "build"
end
local action_cmd_line = tundra_dir .. target_dir .. static_libs .. "$(RUST_CARGO) " .. cargo_opts .. " --manifest-path=" .. data.CargoConfig .. release
return action_cmd_line, output_target
end
function _rust_cargo_program_mt:create_dag(env, data, deps)
local action_cmd_line, output_target = build_rust_action_cmd_line(env, data, cmd_line_type_prog)
local extra_deps, dep_sources = get_extra_deps(data, env)
local build_node = depgraph.make_node {
Env = env,
Pass = data.Pass,
InputFiles = util.merge_arrays({ data.CargoConfig }, data.Sources, util.flatten(dep_sources)),
Annotation = path.join("$(OBJECTDIR)", data.Name),
Label = "Cargo Program $(@)",
Action = action_cmd_line,
OutputFiles = { output_target },
Dependencies = util.merge_arrays(deps, extra_deps),
}
-- No copy if we are running in test mode (as the executable will be executed directly)
if string.match(env:interpolate("$(RUST_CARGO_OPTS)"), "test") then
return build_node
else
local dst ="$(OBJECTDIR)" .. "$(SEP)" .. path.get_filename(env:interpolate(output_target))
local src = output_target
return files.copy_file(env, src, dst, data.Pass, { build_node })
end
end
function _rust_cargo_shared_lib_mt:create_dag(env, data, deps)
local action_cmd_line, output_target = build_rust_action_cmd_line(env, data, cmd_line_type_shared_lib)
local extra_deps, dep_sources = get_extra_deps(data, env)
local build_node = depgraph.make_node {
Env = env,
Pass = data.Pass,
InputFiles = util.merge_arrays({ data.CargoConfig }, data.Sources, util.flatten(dep_sources)),
Annotation = path.join("$(OBJECTDIR)", data.Name),
Label = "Cargo SharedLibrary $(@)",
Action = action_cmd_line,
OutputFiles = { output_target },
Dependencies = util.merge_arrays(deps, extra_deps),
}
-- No copy if we are running in test mode (as the executable will be executed directly)
if string.match(env:interpolate("$(RUST_CARGO_OPTS)"), "test") then
return build_node
else
local dst ="$(OBJECTDIR)" .. "$(SEP)" .. path.get_filename(env:interpolate(output_target))
local src = output_target
return files.copy_file(env, src, dst, data.Pass, { build_node })
end
end
function _rust_cargo_crate_mt:create_dag(env, data, deps)
local action_cmd_line, output_target = build_rust_action_cmd_line(env, data, cmd_line_type_crate)
local extra_deps, dep_sources = get_extra_deps(data, env)
local build_node = depgraph.make_node {
Env = env,
Pass = data.Pass,
InputFiles = util.merge_arrays({ data.CargoConfig }, data.Sources, util.flatten(dep_sources)),
Annotation = path.join("$(OBJECTDIR)", data.Name),
Label = "Cargo Crate $(@)",
Action = action_cmd_line,
OutputFiles = { output_target },
Dependencies = util.merge_arrays(deps, extra_deps),
}
return build_node
end
local rust_blueprint = {
Name = {
Type = "string",
Required = true,
Help = "Name of the project. Must match the name in Cargo.toml"
},
CargoConfig = {
Type = "string",
Required = true,
Help = "Path to Cargo.toml"
},
Sources = {
Required = true,
Help = "List of source files",
Type = "source_list",
ExtensionKey = "RUST_SUFFIXES",
},
}
nodegen.add_evaluator("RustProgram", _rust_cargo_program_mt, rust_blueprint)
nodegen.add_evaluator("RustSharedLibrary", _rust_cargo_shared_lib_mt, rust_blueprint)
nodegen.add_evaluator("RustCrate", _rust_cargo_crate_mt, rust_blueprint)
| mit |
Quenty/NevermoreEngine | src/remoting/src/Shared/GetRemoteEvent.lua | 1 | 2095 | --[=[
Provides getting named global [RemoteEvent] resources.
@class GetRemoteEvent
]=]
--[=[
Retrieves a global remote event from the store. On the server, it constructs a new one,
and on the client, it waits for it to exist.
:::tip
Consider using [PromiseGetRemoteEvent] for a non-yielding version
:::
```lua
-- server.lua
local GetRemoteEvent = require("GetRemoteEvent")
local remoteEvent = GetRemoteEvent("testing")
remoteEvent.OnServerEvent:Connect(print)
-- client.lua
local GetRemoteEvent = require("GetRemoteEvent")
local remoteEvent = GetRemoteEvent("testing")
remoteEvent:FireServer("Hello") --> Hello (on the server)
```
:::info
If the game is not running, then a mock remote event will be created
for use in testing.
:::
@yields
@function GetRemoteEvent
@within GetRemoteEvent
@param name string
@return RemoteEvent
]=]
local require = require(script.Parent.loader).load(script)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local ResourceConstants = require("ResourceConstants")
if not RunService:IsRunning() then
return function(name)
local event = Instance.new("RemoteEvent")
event.Archivable = false
event.Name = "Mock" .. name
return event
end
elseif RunService:IsServer() then
return function(name)
assert(type(name) == "string", "Bad name")
local storage = ReplicatedStorage:FindFirstChild(ResourceConstants.REMOTE_EVENT_STORAGE_NAME)
if not storage then
storage = Instance.new("Folder")
storage.Name = ResourceConstants.REMOTE_EVENT_STORAGE_NAME
storage.Archivable = false
storage.Parent = ReplicatedStorage
end
local event = storage:FindFirstChild(name)
if event then
return event
end
event = Instance.new("RemoteEvent")
event.Name = name
event.Archivable = false
event.Parent = storage
return event
end
else -- RunService:IsClient()
return function(name)
assert(type(name) == "string", "Bad name")
return ReplicatedStorage:WaitForChild(ResourceConstants.REMOTE_EVENT_STORAGE_NAME):WaitForChild(name)
end
end | mit |
ffxiphoenix/darkstar | scripts/zones/Abyssea-Grauberg/npcs/Cavernous_Maw.lua | 29 | 1242 | -----------------------------------
-- Area: Abyssea - Grauberg
-- NPC: Cavernous Maw
-- @pos -564.000, 30.300, -760.000 254
-- Teleports Players to North Gustaberg
-----------------------------------
package.loaded["scripts/zones/Abyssea-Grauberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Abyssea-Grauberg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00C8);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00C8 and option == 1) then
player:setPos(-71,0.001,601,126,106);
end
end; | gpl-3.0 |
ostinelli/gin | gin/db/sql/mysql/adapter_detached.lua | 1 | 2910 | -- dep
local dbi = require 'DBI'
-- gin
local Gin = require 'gin.core.gin'
local helpers = require 'gin.helpers.common'
-- perf
local assert = assert
local ipairs = ipairs
local pairs = pairs
local pcall = pcall
local setmetatable = setmetatable
local smatch = string.match
local tonumber = tonumber
local function tappend(t, v) t[#t+1] = v end
local MySql = {}
MySql.default_database = 'mysql'
local function mysql_connect(options)
local db = assert(dbi.Connect("MySQL", options.database, options.user, options.password, options.host, options.port))
db:autocommit(true)
return db
end
local function mysql_close(db)
db:close()
end
-- quote
function MySql.quote(options, str)
local db = mysql_connect(options)
local quoted_str = "'" .. db:quote(str) .. "'"
mysql_close(db)
return quoted_str
end
-- return list of tables
function MySql.tables(options)
local res = MySql.execute(options, "SHOW TABLES IN " .. options.database .. ";")
local tables = {}
for _, v in pairs(res) do
for _, table_name in pairs(v) do
tappend(tables, table_name)
end
end
return tables
end
-- return schema as a table
function MySql.schema(options)
local Migration = require 'gin.db.migrations'
local schema = {}
local tables = MySql.tables(options)
for _, table_name in ipairs(tables) do
if table_name ~= Migration.migrations_table_name then
local table_info = MySql.execute(options, "SHOW COLUMNS IN " .. table_name .. ";")
tappend(schema, { [table_name] = table_info })
end
end
return schema
end
-- execute query on db
local function db_execute(db, sql)
-- execute
local sth = assert(db:prepare(sql))
local ok, err = sth:execute()
if ok == false then error(err) end
-- get first returned row (if any)
local ok, row = pcall(function() return sth:fetch(true) end)
if ok == false then row = nil end
return sth, row
end
-- execute a query
function MySql.execute(options, sql)
-- connect
local db = mysql_connect(options)
-- execute
local sth, row = db_execute(db, sql)
if row == nil then return {} end
-- build res
local res = {}
while row do
local irow = helpers.shallowcopy(row)
tappend(res, irow)
row = sth:fetch(true)
end
-- close
sth:close()
mysql_close(db)
-- return
return res
end
-- execute a query and return the last ID
function MySql.execute_and_return_last_id(options, sql, id_col)
-- connect
local db = mysql_connect(options)
-- execute sql
local sth, row = db_execute(db, sql)
sth:close()
-- get last id
local sth, row = db_execute(db, "SELECT BINARY LAST_INSERT_ID() AS " .. id_col .. ";")
local id = row[id_col]
-- close
sth:close()
mysql_close(db)
-- return
return tonumber(id)
end
return MySql
| mit |
Phrohdoh/OpenRA | mods/ra/maps/soviet-06a/soviet06a.lua | 4 | 6436 | --[[
Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
ArmorAttack = { }
AttackPaths = { { AttackWaypoint1 }, { AttackWaypoint2 } }
BaseAttackers = { BaseAttacker1, BaseAttacker2 }
InfAttack = { }
IntroAttackers = { IntroEnemy1, IntroEnemy2, IntroEnemy3 }
Trucks = { Truck1, Truck2 }
AlliedInfantryTypes = { "e1", "e1", "e3" }
AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "2tnk", "2tnk", "arty" }
SovietReinforcements1 = { "e6", "e6", "e6", "e6", "e6" }
SovietReinforcements2 = { "e4", "e4", "e2", "e2", "e2" }
SovietReinforcements1Waypoints = { McvWaypoint.Location, APCWaypoint1.Location }
SovietReinforcements2Waypoints = { McvWaypoint.Location, APCWaypoint2.Location }
TruckGoalTrigger = { CPos.New(83, 7), CPos.New(83, 8), CPos.New(83, 9), CPos.New(83, 10), CPos.New(84, 10), CPos.New(84, 11), CPos.New(84, 12), CPos.New(85, 12), CPos.New(86, 12), CPos.New(87, 12), CPos.New(87, 13), CPos.New(88, 13), CPos.New(89, 13), CPos.New(90, 13), CPos.New(90, 14), CPos.New(90, 15), CPos.New(91, 15), CPos.New(92, 15), CPos.New(93, 15), CPos.New(94, 15) }
CameraBarrierTrigger = { CPos.New(65, 39), CPos.New(65, 40), CPos.New(66, 40), CPos.New(66, 41), CPos.New(67, 41), CPos.New(67, 42), CPos.New(68, 42), CPos.New(68, 43), CPos.New(68, 44) }
CameraBaseTrigger = { CPos.New(53, 42), CPos.New(54, 42), CPos.New(54, 41), CPos.New(55, 41), CPos.New(56, 41), CPos.New(56, 40), CPos.New(57, 40), CPos.New(57, 39), CPos.New(58, 39), CPos.New(59, 39), CPos.New(59, 38), CPos.New(60, 38), CPos.New(61, 38) }
Trigger.OnEnteredFootprint(TruckGoalTrigger, function(a, id)
if not truckGoalTrigger and a.Owner == player and a.Type == "truk" then
truckGoalTrigger = true
player.MarkCompletedObjective(sovietObjective)
player.MarkCompletedObjective(SaveAllTrucks)
end
end)
Trigger.OnEnteredFootprint(CameraBarrierTrigger, function(a, id)
if not cameraBarrierTrigger and a.Owner == player then
cameraBarrierTrigger = true
local cameraBarrier = Actor.Create("camera", true, { Owner = player, Location = CameraBarrier.Location })
Trigger.AfterDelay(DateTime.Seconds(15), function()
cameraBarrier.Destroy()
end)
end
end)
Trigger.OnEnteredFootprint(CameraBaseTrigger, function(a, id)
if not cameraBaseTrigger and a.Owner == player then
cameraBaseTrigger = true
local cameraBase1 = Actor.Create("camera", true, { Owner = player, Location = CameraBase1.Location })
local cameraBase2 = Actor.Create("camera", true, { Owner = player, Location = CameraBase2.Location })
local cameraBase3 = Actor.Create("camera", true, { Owner = player, Location = CameraBase3.Location })
local cameraBase4 = Actor.Create("camera", true, { Owner = player, Location = CameraBase4.Location })
Trigger.AfterDelay(DateTime.Minutes(1), function()
cameraBase1.Destroy()
cameraBase2.Destroy()
cameraBase3.Destroy()
cameraBase4.Destroy()
end)
end
end)
Trigger.OnAllKilled(Trucks, function()
enemy.MarkCompletedObjective(alliedObjective)
end)
Trigger.OnAnyKilled(Trucks, function()
player.MarkFailedObjective(SaveAllTrucks)
end)
Trigger.OnKilled(Apwr, function(building)
BaseApwr.exists = false
end)
Trigger.OnKilled(Barr, function(building)
BaseTent.exists = false
end)
Trigger.OnKilled(Proc, function(building)
BaseProc.exists = false
end)
Trigger.OnKilled(Weap, function(building)
BaseWeap.exists = false
end)
Trigger.OnKilled(Apwr2, function(building)
BaseApwr2.exists = false
end)
Trigger.OnKilledOrCaptured(Dome, function()
Trigger.AfterDelay(DateTime.Seconds(2), function()
player.MarkCompletedObjective(sovietObjective2)
Media.PlaySpeechNotification(player, "ObjectiveMet")
end)
end)
-- Activate the AI once the player deployed the Mcv
Trigger.OnRemovedFromWorld(Mcv, function()
if not mcvDeployed then
mcvDeployed = true
BuildBase()
SendEnemies()
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor)
Trigger.AfterDelay(DateTime.Minutes(2), function()
Utils.Do(BaseAttackers, function(actor)
IdleHunt(actor)
end)
end)
end
end)
WorldLoaded = function()
player = Player.GetPlayer("USSR")
enemy = Player.GetPlayer("Greece")
Camera.Position = CameraStart.CenterPosition
Mcv.Move(McvWaypoint.Location)
Harvester.FindResources()
Utils.Do(IntroAttackers, function(actor)
IdleHunt(actor)
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements1, SovietReinforcements1Waypoints)
Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements2, SovietReinforcements2Waypoints)
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
alliedObjective = enemy.AddPrimaryObjective("Destroy all Soviet troops.")
sovietObjective = player.AddPrimaryObjective("Escort the Convoy.")
sovietObjective2 = player.AddSecondaryObjective("Destroy or capture the Allied radar dome to stop\nenemy reinforcements.")
SaveAllTrucks = player.AddSecondaryObjective("Keep all trucks alive.")
end
Tick = function()
if player.HasNoRequiredUnits() then
enemy.MarkCompletedObjective(alliedObjective)
end
if enemy.Resources >= enemy.ResourceCapacity * 0.75 then
enemy.Cash = enemy.Cash + enemy.Resources - enemy.ResourceCapacity * 0.25
enemy.Resources = enemy.ResourceCapacity * 0.25
end
end
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Kazham/npcs/Lalapp.lua | 15 | 3856 | -----------------------------------
-- Area: Kazham
-- NPC: Lalapp
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
require("scripts/globals/pathfind");
local path = {
-63.243702, -11.000023, -97.916130,
-63.970551, -11.000027, -97.229286,
-64.771614, -11.000030, -96.499062
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
-- item IDs
-- 483 Broken Mithran Fishing Rod
-- 22 Workbench
-- 1008 Ten of Coins
-- 1157 Sands of Silence
-- 1158 Wandering Bulb
-- 904 Giant Fish Bones
-- 4599 Blackened Toad
-- 905 Wyvern Skull
-- 1147 Ancient Salt
-- 4600 Lucky Egg
function onTrade(player,npc,trade)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local goodtrade = trade:hasItemQty(1147,1);
local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1157,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(904,1) or trade:hasItemQty(1008,1) or trade:hasItemQty(905,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(4600,1));
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if progress == 8 or failed == 9 then
if goodtrade then
player:startEvent(0x00E3);
elseif badtrade then
player:startEvent(0x00ED);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local retry = player:getVar("OPO_OPO_RETRY");
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if retry >= 1 then -- has failed on future npc so disregard previous successful trade
player:startEvent(0x00CD);
npc:wait(-1);
elseif (progress == 8 or failed == 9) then
player:startEvent(0x00D6); -- asking for ancient salt
elseif (progress >= 9 or failed >= 10) then
player:startEvent(0x00FA); -- happy with ancient salt
end
else
player:startEvent(0x00CD);
npc:wait(-1);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x00E3) then -- correct trade, onto next opo
if player:getVar("OPO_OPO_PROGRESS") == 8 then
player:tradeComplete();
player:setVar("OPO_OPO_PROGRESS",9);
player:setVar("OPO_OPO_FAILED",0);
else
player:setVar("OPO_OPO_FAILED",10);
end
elseif (csid == 0x00ED) then -- wrong trade, restart at first opo
player:setVar("OPO_OPO_FAILED",1);
player:setVar("OPO_OPO_RETRY",9);
else
npc:wait(0);
end
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/weaponskills/decimation.lua | 30 | 1511 | -----------------------------------
-- Decimation
-- Axe weapon skill
-- Skill level: 240
-- In order to obtain Decimation, the quest Axe the Competition must be completed.
-- Delivers a three-hit attack. params.accuracy varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget.
-- Aligned with the Flame Belt, Light Belt & Aqua Belt.
-- Element: None
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1.25 1.25 1.25
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 3;
params.ftp100 = 1.25; params.ftp200 = 1.25; params.ftp300 = 1.25;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.75; params.ftp200 = 1.75; params.ftp300 = 1.75;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
noooway/love2d_arkanoid_tutorial | 3-06_GlueBonus/walls.lua | 8 | 1601 | local vector = require "vector"
local walls = {}
walls.side_walls_thickness = 34
walls.top_wall_thickness = 26
walls.right_border_x_pos = 576
walls.current_level_walls = {}
function walls.new_wall( position, width, height )
return( { position = position,
width = width,
height = height } )
end
function walls.update_wall( single_wall )
end
function walls.draw_wall( single_wall )
love.graphics.rectangle( 'line',
single_wall.position.x,
single_wall.position.y,
single_wall.width,
single_wall.height )
local r, g, b, a = love.graphics.getColor( )
love.graphics.setColor( 255, 0, 0, 100 )
love.graphics.rectangle( 'fill',
single_wall.position.x,
single_wall.position.y,
single_wall.width,
single_wall.height )
love.graphics.setColor( r, g, b, a )
end
function walls.construct_walls()
local left_wall = walls.new_wall(
vector( 0, 0 ),
walls.side_walls_thickness,
love.graphics.getHeight()
)
local right_wall = walls.new_wall(
vector( walls.right_border_x_pos, 0 ),
walls.side_walls_thickness,
love.graphics.getHeight()
)
local top_wall = walls.new_wall(
vector( 0, 0 ),
walls.right_border_x_pos,
walls.top_wall_thickness
)
walls.current_level_walls["left"] = left_wall
walls.current_level_walls["right"] = right_wall
walls.current_level_walls["top"] = top_wall
end
function walls.update( dt )
end
function walls.draw()
for _, wall in pairs( walls.current_level_walls ) do
walls.draw_wall( wall )
end
end
return walls
| mit |
dail8859/ScintilluaPlusPlus | extra/npp.lua | 1 | 2241 | -- Notepad++ lexer theme for Scintillua.
local property = require('lexer').property
property['color.black'] = '#000000'
property['color.green'] = '#008000'
property['color.maroon'] = '#95004A'
property['color.brown'] = '#804000'
property['color.blue'] = '#0000FF'
property['color.yellow'] = '#FF8000'
property['color.grey'] = '#808080'
property['color.darkblue'] = '#000080'
property['color.lightblue'] = '#0080C0'
property['color.purple'] = '#8000FF'
property['color.darkerblue'] = '#0000A0'
property['color.red'] = '#7F0000'
property['color.teal'] = '#007F7F'
property['color.white'] = '#FFFFFF'
property['color.orange'] = '#FF8000'
-- Default styles.
local font = 'Courier New'
local size = 10
property['style.default'] = 'font:'..font..',size:'..size..
',fore:$(color.black),back:$(color.white)'
-- Token styles.
property['style.nothing'] = ''
property['style.class'] = 'fore:$(color.black),bold'
property['style.comment'] = 'fore:$(color.green)'
property['style.constant'] = 'fore:$(color.teal),bold' -- Change to lightblue?
property['style.definition'] = 'fore:$(color.black),bold'
property['style.error'] = 'fore:$(color.red)'
property['style.function'] = 'fore:$(color.lightblue),bold'
property['style.keyword'] = 'fore:$(color.blue),bold'
property['style.label'] = 'fore:$(color.teal),bold'
property['style.number'] = 'fore:$(color.orange)'
property['style.operator'] = 'fore:$(color.darkblue),bold'
property['style.regex'] = 'fore:$(color.purple)'
property['style.string'] = 'fore:$(color.grey)'
property['style.preprocessor'] = 'fore:$(color.brown)'
property['style.tag'] = 'fore:$(color.blue)'
property['style.type'] = 'fore:$(color.purple)'
property['style.variable'] = 'fore:$(color.black)'
property['style.whitespace'] = ''
property['style.embedded'] = 'fore:$(color.blue)'
property['style.identifier'] = '$(style.nothing)'
-- Predefined styles.
property['style.linenumber'] = 'fore:$(color.grey),back:#E4E4E4'
property['style.bracelight'] = 'fore:#0000FF,bold'
property['style.bracebad'] = 'fore:#FF0000,bold'
property['style.controlchar'] = '$(style.nothing)'
property['style.indentguide'] = 'fore:#C0C0C0,back:$(color.white)'
property['style.calltip'] = 'fore:$(color.white),back:#444444'
| gpl-2.0 |
ffxiphoenix/darkstar | scripts/zones/FeiYin/npcs/Treasure_Chest.lua | 19 | 3069 | -----------------------------------
-- Area: Fei'Yin
-- NPC: Treasure Chest
-- @zone 204
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1037,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1037,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: Sorcery of the North QUEST -----------
if (player:getQuestStatus(SANDORIA,SORCERY_OF_THE_NORTH) == QUEST_ACCEPTED and player:hasKeyItem(FEIYIN_MAGIC_TOME) == false) then
questItemNeeded = 1;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addKeyItem(FEIYIN_MAGIC_TOME);
player:messageSpecial(KEYITEM_OBTAINED,FEIYIN_MAGIC_TOME); -- Fei'yin Magic Tome
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]);
player:messageSpecial(GIL_OBTAINED,loot[2]);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1037);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Eastern_Altepa_Desert/npcs/qm2.lua | 17 | 1773 | -----------------------------------
-- Area: Eastern Altepa Desert
-- NPC: qm2 (???)
-- Involved In Quest: 20 in Pirate Years
-- @pos 47.852 -7.808 403.391 114
-----------------------------------
package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Eastern_Altepa_Desert/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
twentyInPirateYearsCS = player:getVar("twentyInPirateYearsCS");
TsuchigumoKilled = player:getVar("TsuchigumoKilled");
if (twentyInPirateYearsCS == 3 and TsuchigumoKilled <= 1) then
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17244524,300):updateClaim(player);
SpawnMob(17244525,300):updateClaim(player);
elseif (twentyInPirateYearsCS == 3 and TsuchigumoKilled >= 2) then
player:addKeyItem(TRICK_BOX);
player:messageSpecial(KEYITEM_OBTAINED,TRICK_BOX);
player:setVar("twentyInPirateYearsCS",4);
player:setVar("TsuchigumoKilled",0);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
drcicero/docl | src/repr.lua | 1 | 1430 | --- Readable tostring
--[[
repr = (require "repr").repr
]]--@RUNHIDDEN
local M = {}
local function key_repr(value)
if type(value) == "string" then
return value:match("%l%w*") and
value or "[" .. M.repr(value) .. "]"
else
return tostring(value)
end
end
--- Generate a readable string out of any lua-value.
-- It is almost serialisation ;)
--
-- Examples:
--[[
return repr(nil)
]]--@EXPECT "nil"
--[[
return repr(1)
]]--@EXPECT "1"
--[[
return repr "test string"
]]--@RUN "\"test string\""
--[[
return repr {1, 2, b=7, 3, a=6,}
]]--@RUN "{1, 2, 3, a=6, b=7}"
--[[
return repr(function () end)
]]--@RUN
function M.repr(value)
if type(value) == "table" then
local t = {}
for k,v in ipairs(value) do
t[#t+1] = M.repr(v)
end
local len = #t
for k,v in pairs(value) do
if type(k) ~= "number" or k > len then
t[#t+1] = key_repr(k) .."=".. M.repr(v)
end
end
table.sort(t)
return "{" .. table.concat(t, ", ") .. "}"
elseif type(value) == "string" then
return ("%q"):format(value)
-- return '"' .. value:gsub("\n", "\\n") .. '"'
-- if value:find("\n") == nil then
-- return ("%q"):format(value)
-- else
-- return "[[" .. value:sub(1, -1) .. "]]"
-- end
else
return tostring(value)
end
end
return M
| mit |
AfuSensi/Mr.Green-MTA-Resources | resources/[gameplay]/gcshop/items/burn/burn_s.lua | 4 | 8707 | -----------------
-- Items stuff --
-----------------
local ID, IDextra, IDextra2 = 6, 7, 8
local g_PlayersBurn = {}
local g_PlayersBurnExtra = {}
local g_PlayersBurnTransfer = {}
function loadGCBurn ( player, bool, settings )
if bool then
g_PlayersBurn[player] = true
else
g_PlayersBurn[player] = nil
end
end
function loadGCBurnExtra ( player, bool, settings )
if bool then
g_PlayersBurnExtra[player] = true
else
g_PlayersBurnExtra[player] = nil
end
end
function loadGCBurnTransfer ( player, bool, settings )
if bool then
g_PlayersBurnTransfer[player] = true
else
g_PlayersBurnTransfer[player] = nil
end
end
addEventHandler('onPlayerQuit', root, function()
g_PlayersBurn[source] = nil
g_PlayersBurnExtra[source] = nil
end)
----------------
-- Burn stuff --
----------------
local busy_with_player = {}
local currentRaceState
local extratime = 2500 -- interval of how much time is added
local extra = 2 -- for the extra perk, how many times extratime is added (nonextra = 1 : 7.5secs, extra = 2 : 10secs)
function onRaceStateChanging( newStateName, oldStateName)
currentRaceState = newStateName
end
addEvent('onRaceStateChanging')
addEventHandler('onRaceStateChanging', root, onRaceStateChanging)
function onVehicleDamage(loss)
local veh = source
local player = getVehicleOccupant(veh)
if not isElement(player) then return end
local playerState = getElementData(player, 'state', false)
if busy_with_player[player] or getElementData(player,"race.finished") or not g_PlayersBurn[player]
or (currentRaceState and currentRaceState ~= "Running" and currentRaceState ~= "SomeoneWon") or playerState ~= "alive" then
return
elseif not isPerkAllowedInMode(ID) then
return
elseif isElement(veh) and getElementHealth(veh) - loss < 250 then
busy_with_player[player] = true
if not g_PlayersBurnExtra[player] then
return setTimer(resetBurnUpTime, 5000 - extratime, 1, player)
else
return setTimer(resetBurnUpTime, 5000 - extratime, 1, player, extra)
end
end
end
addEventHandler('onVehicleDamage', root, onVehicleDamage)
--addCommandHandler('gcblow', function(p,c,n) setElementHealth(getPedOccupiedVehicle(p), tonumber(n)) end )
function resetBurnUpTime(player, times, marker, marker1)
if not (isElement(player) and getPedOccupiedVehicle(player) and isElement(getPedOccupiedVehicle(player)) and getElementHealth(getPedOccupiedVehicle(player)) < 250)
or getElementData(player,"race.finished") or (currentRaceState and currentRaceState ~= "Running" and currentRaceState ~= "SomeoneWon") or getElementData(player, 'state', false) ~= "alive"
then
busy_with_player[player] = nil
if isElement(marker) then destroyElement(marker) end
if isElement(marker1) then destroyElement(marker1) end
return
end
busy_with_player[player] = true
local veh = getPedOccupiedVehicle(player)
setElementHealth(veh, 250)
setTimer(function(veh) if isElement(veh) then setElementHealth(veh,1)end end, 50, 1, veh)
if not (marker and marker1 and isElement(marker) and isElement(marker1)) then
local px, py, pz = getElementPosition(veh)
marker = createMarker( px, py, pz, 'corona', 2); setElementParent(marker, veh); attachElements(marker, veh)
marker1 = createMarker( px, py, pz, 'corona', 2); setElementParent(marker1, veh); attachElements(marker1, veh)
end
if type(times) ~= "number" or times <= 1 then
setTimer ( function(player, marker, marker1)
busy_with_player[player] = nil
if isElement(marker) then destroyElement(marker) end
if isElement(marker1) then destroyElement(marker1) end
end, 5000, 1, player, marker, marker1 )
else
setTimer ( resetBurnUpTime, extratime, 1, player, times - 1, marker, marker1 )
end
exports.messages:outputGameMessage('You burned a little longer! ' .. (times or ''), player)
end
-------------------------
-- Fire transfer stuff --
-------------------------
local g_Players = {}
local timers = {}
function onServerRecieveCollisionData(hitCar, usedCar)
local hitWho = getVehicleController(hitCar)
if not hitWho then return end --avoid unexpected error
g_Players[source] = hitWho
timers[source] = setTimer(function(player) g_Players[player] = nil end, 1000+getPlayerPing(hitWho), 1, source) --assume 1 second + other player's ping is the interval in which the parties can collide. If it should take more than 1 second then the collision is one-sided client
if g_Players[hitWho] == source then --we have a fully synced collision between 2 players' cars
triggerEvent('onPlayersVehicleCollide', root, source, usedCar, hitWho, hitCar)
g_Players[source] = nil
g_Players[hitWho] = nil
end
end
addEvent('onServerRecieveCollisionData', true)
addEventHandler('onServerRecieveCollisionData', root, onServerRecieveCollisionData)
local _getPlayerName = getPlayerName
local function getPlayerName(player)
return string.gsub(_getPlayerName(player),"#%x%x%x%x%x%x","")
end
-- function onPlayersVehicleCollide (player1, car1, player2, car2)
-- local saveFireHealth
-- if g_PlayersBurnTransfer[player1] and isPerkAllowedInMode(ID) and getElementHealth(car1) <= 245 and getElementHealth(car2) > 245 and not isVehicleBlown(car1) and not isVehicleBlown(car2) then --isOnFire?
-- saveFireHealth = getElementHealth(car1)
-- fixVehicle(car1)
-- setElementHealth(car1, getElementHealth(car2))
-- setElementHealth(car2, saveFireHealth) --transfer the fire !
-- outputChatBox('You have taken ' .. getPlayerName(player2).. '\'s health!', player1, 50, 202, 50)
-- exports.messages:outputGameMessage('You have taken ' .. getPlayerName(player2).. '\'s health!', player1, 2, 50, 202, 50, true)
-- outputChatBox(getPlayerName(player1).. ' has given you his vehicle fire! (fire transfer gc perk)', player2, 50, 202, 50)
-- exports.messages:outputGameMessage(getPlayerName(player1).. ' has given you his vehicle fire! ', player2,2, 50, 202, 50, true)
-- elseif g_PlayersBurnTransfer[player2] and isPerkAllowedInMode(ID) and getElementHealth(car2) <= 245 and getElementHealth(car1) > 245 and not isVehicleBlown(car1) and not isVehicleBlown(car2) then --isOnFire
-- saveFireHealth = getElementHealth(car2)
-- --fixVehicle(car2)
-- --setElementHealth(car2, getElementHealth(car1))
-- setElementHealth(car1, saveFireHealth) --transfer the fire !
-- outputChatBox('You have taken ' .. getPlayerName(player1).. '\'s health!', player2, 50, 202, 50)
-- exports.messages:outputGameMessage('You have taken ' .. getPlayerName(player1).. '\'s health!', player2, 2, 50, 202, 50, true)
-- outputChatBox(getPlayerName(player2).. ' has given you his vehicle fire! ', player1, 50, 202, 50)
-- exports.messages:outputGameMessage(getPlayerName(player2).. ' has given you his vehicle fire! ', player1,2, 50, 202, 50, true)
-- end
-- end
function onPlayersVehicleCollide (player1, car1, player2, car2)
local saveFireHealth
if g_PlayersBurnTransfer[player1] and isPerkAllowedInMode(ID) and getElementHealth(car1) <= 245 and getElementHealth(car2) > 245 and not isVehicleBlown(car1) and not isVehicleBlown(car2) then --isOnFire?
saveFireHealth = getElementHealth(car1)
fixVehicle(car1)
setElementHealth(car1, getElementHealth(car2))
setElementHealth(car2, saveFireHealth) --transfer the fire !
outputChatBox('You have taken ' .. getPlayerName(player2).. '\'s health!', player1, 50, 202, 50)
exports.messages:outputGameMessage('You have taken ' .. getPlayerName(player2).. '\'s health!', player1, 2, 50, 202, 50, true)
outputChatBox(getPlayerName(player1).. ' has given you his vehicle fire! (fire transfer gc perk)', player2, 50, 202, 50)
exports.messages:outputGameMessage(getPlayerName(player1).. ' has given you his vehicle fire! ', player2,2, 50, 202, 50, true)
elseif g_PlayersBurnTransfer[player2] and isPerkAllowedInMode(ID) and getElementHealth(car2) <= 245 and getElementHealth(car1) > 245 and not isVehicleBlown(car1) and not isVehicleBlown(car2) then --isOnFire
saveFireHealth = getElementHealth(car2)
fixVehicle(car2)
setElementHealth(car2, getElementHealth(car1))
setElementHealth(car1, saveFireHealth) --transfer the fire !
outputChatBox('You have taken ' .. getPlayerName(player1).. '\'s health!', player2, 50, 202, 50)
exports.messages:outputGameMessage('You have taken ' .. getPlayerName(player1).. '\'s health!', player2, 2, 50, 202, 50, true)
outputChatBox(getPlayerName(player2).. ' has given you his vehicle fire! ', player1, 50, 202, 50)
exports.messages:outputGameMessage(getPlayerName(player2).. ' has given you his vehicle fire! ', player1,2, 50, 202, 50, true)
end
end
addEvent('onPlayersVehicleCollide', true)
addEventHandler('onPlayersVehicleCollide', root,onPlayersVehicleCollide)
| mit |
ffxiphoenix/darkstar | scripts/zones/PsoXja/TextIDs.lua | 9 | 1673 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6384; -- Obtained: <item>
GIL_OBTAINED = 6385; -- Obtained <number> gil
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>
NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here.
DEVICE_IN_OPERATION = 7224; -- The device appears to be in operation...
DOOR_LOCKED = 7227; -- The door is locked.
ARCH_GLOW_BLUE = 7228; -- The arch above the door is glowing blue...
ARCH_GLOW_GREEN = 7229; -- The arch above the door is glowing green...
CANNOT_OPEN_SIDE = 7232; -- The door cannot be opened from this side.
TRAP_ACTIVATED = 7234; -- A trap connected to it has been activated!
TRAP_FAILS = 7235; -- The trap connected to it fails to activate.
HOMEPOINT_SET = 7469; -- Home point set!
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7456; -- You unlock the chest!
CHEST_FAIL = 7457; -- Fails to open the chest.
CHEST_TRAP = 7458; -- The chest was trapped!
CHEST_WEAK = 7459; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7460; -- The chest was a mimic!
CHEST_MOOGLE = 7461; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7462; -- The chest was but an illusion...
CHEST_LOCKED = 7463; -- The chest appears to be locked.
-- Other
BROKEN_KNIFE = 7464; -- A broken knife blade can be seen among the rubble...
-- conquest Base
CONQUEST_BASE = 7065; -- Tallying conquest results...
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Caedarva_Mire/npcs/qm2.lua | 16 | 1175 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: ??? (Spawn Experimental Lamia(ZNM T3))
-- @pos -773 -11 322 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(2595,1) and trade:getItemCount() == 1) then -- Trade Myrrh
player:tradeComplete();
SpawnMob(17101205,180):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/spells/bluemagic/temporal_shift.lua | 18 | 1436 | -----------------------------------------
-- Spell: Temporal Shift
-- Enemies within range are temporarily prevented from acting
-- Spell cost: 48 MP
-- Monster Type: Luminians
-- Spell Type: Magical (Lightning)
-- Blue Magic Points: 5
-- Stat Bonus: HP+10, MP+15
-- Level: 73
-- Casting Time: 0.5 seconds
-- Recast Time: 120 seconds
-- Magic Bursts on: Impaction, Fragmentation, and Light
-- Combos: Attack Bonus
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local typeEffect = EFFECT_STUN;
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,EFFECT_STUN);
local duration = 5 * resist;
if (resist > 0.0625) then -- Do it!
if (target:addStatusEffect(typeEffect,2,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end;
return typeEffect;
end;
| gpl-3.0 |
rezast/tabchichi | bot.lua | 1 | 34896 | redis = (loadfile "redis.lua")()
redis = redis.connect('127.0.0.1', 6379)
function dl_cb(arg, data)
end
function get_admin ()
if redis:get('botBOT-IDadminset') then
return true
else
print("\n\27[32m لازمه کارکرد صحیح ، فرامین و امورات مدیریتی ربات تبلیغ گر <<\n تعریف کاربری به عنوان مدیر است\n\27[34m ایدی خود را به عنوان مدیر وارد کنید\n\27[32m شما می توانید از ربات زیر شناسه عددی خود را بدست اورید\n\27[34m ربات: @id_ProBot")
print("\n\27[32m >> Tabchi Bot need a fullaccess user (ADMIN)\n\27[34m Imput Your ID as the ADMIN\n\27[32m You can get your ID of this bot\n\27[34m @id_ProBot")
print("\n\27[36m : شناسه عددی ادمین را وارد کنید << \n >> Imput the Admin ID :\n\27[31m ")
admin=io.read()
redis:del("botBOT-IDadmin")
redis:sadd("botBOT-IDadmin", admin)
redis:set('botBOT-IDadminset',true)
end
return print("\n\27[36m ADMIN ID |\27[32m ".. admin .." \27[36m| شناسه ادمین")
end
function get_bot (i, naji)
function bot_info (i, naji)
redis:set("botBOT-IDid",naji.id_)
if naji.first_name_ then
redis:set("botBOT-IDfname",naji.first_name_)
end
if naji.last_name_ then
redis:set("botBOT-IDlanme",naji.last_name_)
end
redis:set("botBOT-IDnum",naji.phone_number_)
return naji.id_
end
tdcli_function ({ID = "GetMe",}, bot_info, nil)
end
function reload(chat_id,msg_id)
loadfile("./bot-BOT-ID.lua")()
send(chat_id, msg_id, "<i>با موفقیت انجام شد.</i>")
end
function is_naji(msg)
local var = false
local hash = 'botBOT-IDadmin'
local user = msg.sender_user_id_
local Naji = redis:sismember(hash, user)
if Naji then
var = true
end
return var
end
function writefile(filename, input)
local file = io.open(filename, "w")
file:write(input)
file:flush()
file:close()
return true
end
function process_join(i, naji)
if naji.code_ == 429 then
local message = tostring(naji.message_)
local Time = message:match('%d+')
redis:setex("botBOT-IDmaxjoin", tonumber(Time), true)
else
redis:srem("botBOT-IDgoodlinks", i.link)
redis:sadd("botBOT-IDsavedlinks", i.link)
end
end
function process_link(i, naji)
if (naji.is_group_ or naji.is_supergroup_channel_) then
redis:srem("botBOT-IDwaitelinks", i.link)
redis:sadd("botBOT-IDgoodlinks", i.link)
elseif naji.code_ == 429 then
local message = tostring(naji.message_)
local Time = message:match('%d+')
redis:setex("botBOT-IDmaxlink", tonumber(Time), true)
else
redis:srem("botBOT-IDwaitelinks", i.link)
end
end
function find_link(text)
if text:match("https://telegram.me/joinchat/%S+") or text:match("https://t.me/joinchat/%S+") or text:match("https://telegram.dog/joinchat/%S+") then
local text = text:gsub("t.me", "telegram.me")
local text = text:gsub("telegram.dog", "telegram.me")
for link in text:gmatch("(https://telegram.me/joinchat/%S+)") do
if not redis:sismember("botBOT-IDalllinks", link) then
redis:sadd("botBOT-IDwaitelinks", link)
redis:sadd("botBOT-IDalllinks", link)
end
end
end
end
function add(id)
local Id = tostring(id)
if not redis:sismember("botBOT-IDall", id) then
if Id:match("^(%d+)$") then
redis:sadd("botBOT-IDusers", id)
redis:sadd("botBOT-IDall", id)
elseif Id:match("^-100") then
redis:sadd("botBOT-IDsupergroups", id)
redis:sadd("botBOT-IDall", id)
else
redis:sadd("botBOT-IDgroups", id)
redis:sadd("botBOT-IDall", id)
end
end
return true
end
function rem(id)
local Id = tostring(id)
if redis:sismember("botBOT-IDall", id) then
if Id:match("^(%d+)$") then
redis:srem("botBOT-IDusers", id)
redis:srem("botBOT-IDall", id)
elseif Id:match("^-100") then
redis:srem("botBOT-IDsupergroups", id)
redis:srem("botBOT-IDall", id)
else
redis:srem("botBOT-IDgroups", id)
redis:srem("botBOT-IDall", id)
end
end
return true
end
function send(chat_id, msg_id, text)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = msg_id,
disable_notification_ = 1,
from_background_ = 1,
reply_markup_ = nil,
input_message_content_ = {
ID = "InputMessageText",
text_ = text,
disable_web_page_preview_ = 1,
clear_draft_ = 0,
entities_ = {},
parse_mode_ = {ID = "TextParseModeHTML"},
},
}, dl_cb, nil)
end
get_admin()
function tdcli_update_callback(data)
if data.ID == "UpdateNewMessage" then
if not redis:get("botBOT-IDmaxlink") then
if redis:scard("botBOT-IDwaitelinks") ~= 0 then
local links = redis:smembers("botBOT-IDwaitelinks")
for x,y in pairs(links) do
if x == 11 then redis:setex("botBOT-IDmaxlink", 60, true) return end
tdcli_function({ID = "CheckChatInviteLink",invite_link_ = y},process_link, {link=y})
end
end
end
if not redis:get("botBOT-IDmaxjoin") then
if redis:scard("botBOT-IDgoodlinks") ~= 0 then
local links = redis:smembers("botBOT-IDgoodlinks")
for x,y in pairs(links) do
tdcli_function({ID = "ImportChatInviteLink",invite_link_ = y},process_join, {link=y})
if x == 5 then redis:setex("botBOT-IDmaxjoin", 60, true) return end
end
end
end
local msg = data.message_
local bot_id = redis:get("botBOT-IDid") or get_bot()
if (msg.sender_user_id_ == 777000 or msg.sender_user_id_ == 123654789) then
for k,v in pairs(redis:smembers('botBOT-IDadmin')) do
tdcli_function({
ID = "ForwardMessages",
chat_id_ = v,
from_chat_id_ = msg.chat_id_,
message_ids_ = {[0] = msg.id_},
disable_notification_ = 0,
from_background_ = 1
}, dl_cb, nil)
end
end
if tostring(msg.chat_id_):match("^(%d+)") then
if not redis:sismember("botBOT-IDall", msg.chat_id_) then
redis:sadd("botBOT-IDusers", msg.chat_id_)
redis:sadd("botBOT-IDall", msg.chat_id_)
end
end
add(msg.chat_id_)
if msg.date_ < os.time() - 150 then
return false
end
if msg.content_.ID == "MessageText" then
local text = msg.content_.text_
local matches
find_link(text)
if is_naji(msg) then
if text:match("^(افزودن مدیر) (%d+)$") then
local matches = text:match("%d+")
if redis:sismember('botBOT-IDadmin', matches) then
return send(msg.chat_id_, msg.id_, "<i>کاربر مورد نظر در حال حاضر مدیر است.</i>")
elseif redis:sismember('botBOT-IDmod', msg.sender_user_id_) then
return send(msg.chat_id_, msg.id_, "شما دسترسی ندارید.")
else
redis:sadd('botBOT-IDadmin', matches)
redis:sadd('botBOT-IDmod', matches)
return send(msg.chat_id_, msg.id_, "<i>مقام کاربر به مدیر ارتقا یافت</i>")
end
elseif text:match("^(افزودن مدیرکل) (%d+)$") then
local matches = text:match("%d+")
if redis:sismember('botBOT-IDmod',msg.sender_user_id_) then
return send(msg.chat_id_, msg.id_, "شما دسترسی ندارید.")
end
if redis:sismember('botBOT-IDmod', matches) then
redis:srem("botBOT-IDmod",matches)
redis:sadd('botBOT-IDadmin'..tostring(matches),msg.sender_user_id_)
return send(msg.chat_id_, msg.id_, "مقام کاربر به مدیریت کل ارتقا یافت .")
elseif redis:sismember('botBOT-IDadmin',matches) then
return send(msg.chat_id_, msg.id_, 'درحال حاضر مدیر هستند.')
else
redis:sadd('botBOT-IDadmin', matches)
redis:sadd('botBOT-IDadmin'..tostring(matches),msg.sender_user_id_)
return send(msg.chat_id_, msg.id_, "کاربر به مقام مدیرکل منصوب شد.")
end
elseif text:match("^(حذف مدیر) (%d+)$") then
local matches = text:match("%d+")
if redis:sismember('botBOT-IDmod', msg.sender_user_id_) then
if tonumber(matches) == msg.sender_user_id_ then
redis:srem('botBOT-IDadmin', msg.sender_user_id_)
redis:srem('botBOT-IDmod', msg.sender_user_id_)
return send(msg.chat_id_, msg.id_, "شما دیگر مدیر نیستید.")
end
return send(msg.chat_id_, msg.id_, "شما دسترسی ندارید.")
end
if redis:sismember('botBOT-IDadmin', matches) then
if redis:sismember('botBOT-IDadmin'..msg.sender_user_id_ ,matches) then
return send(msg.chat_id_, msg.id_, "شما نمی توانید مدیری که به شما مقام داده را عزل کنید.")
end
redis:srem('botBOT-IDadmin', matches)
redis:srem('botBOT-IDmod', matches)
return send(msg.chat_id_, msg.id_, "کاربر از مقام مدیریت خلع شد.")
end
return send(msg.chat_id_, msg.id_, "کاربر مورد نظر مدیر نمی باشد.")
elseif text:match("^(تازه سازی ربات)$") then
get_bot()
return send(msg.chat_id_, msg.id_, "<i>مشخصات فردی ربات بروز شد.</i>")
elseif text:match("ریپورت") then
tdcli_function ({
ID = "SendBotStartMessage",
bot_user_id_ = 123654789,
chat_id_ = 123654789,
parameter_ = 'start'
}, dl_cb, nil)
elseif text:match("^(/reload)$") then
return reload(msg.chat_id_,msg.id_)
elseif text:match("^بروزرسانی ربات$") then
io.popen("git fetch --all && git reset --hard origin/persian && git pull origin persian && chmod +x bot"):read("*all")
local text,ok = io.open("bot.lua",'r'):read('*a'):gsub("BOT%-ID",BOT-ID)
io.open("bot-BOT-ID.lua",'w'):write(text):close()
return reload(msg.chat_id_,msg.id_)
elseif text:match("^همگام سازی با تبچی$") then
local botid = BOT-ID - 1
redis:sunionstore("botBOT-IDall","tabchi:"..tostring(botid)..":all")
redis:sunionstore("botBOT-IDusers","tabchi:"..tostring(botid)..":pvis")
redis:sunionstore("botBOT-IDgroups","tabchi:"..tostring(botid)..":groups")
redis:sunionstore("botBOT-IDsupergroups","tabchi:"..tostring(botid)..":channels")
redis:sunionstore("botBOT-IDsavedlinks","tabchi:"..tostring(botid)..":savedlinks")
return send(msg.chat_id_, msg.id_, "<b>همگام سازی اطلاعات با تبچی شماره</b><code> "..tostring(botid).." </code><b>انجام شد.</b>")
elseif text:match("^(لیست) (.*)$") then
local matches = text:match("^لیست (.*)$")
local naji
if matches == "مخاطبین" then
return tdcli_function({
ID = "SearchContacts",
query_ = nil,
limit_ = 999999999
},
function (I, Naji)
local count = Naji.total_count_
local text = "مخاطبین : \n"
for i =0 , tonumber(count) - 1 do
local user = Naji.users_[i]
local firstname = user.first_name_ or ""
local lastname = user.last_name_ or ""
local fullname = firstname .. " " .. lastname
text = tostring(text) .. tostring(i) .. ". " .. tostring(fullname) .. " [" .. tostring(user.id_) .. "] = " .. tostring(user.phone_number_) .. " \n"
end
writefile("botBOT-ID_contacts.txt", text)
tdcli_function ({
ID = "SendMessage",
chat_id_ = I.chat_id,
reply_to_message_id_ = 0,
disable_notification_ = 0,
from_background_ = 1,
reply_markup_ = nil,
input_message_content_ = {ID = "InputMessageDocument",
document_ = {ID = "InputFileLocal",
path_ = "botBOT-ID_contacts.txt"},
caption_ = "مخاطبین تبلیغگر شماره BOT-ID"}
}, dl_cb, nil)
return io.popen("rm -rf botBOT-ID_contacts.txt"):read("*all")
end, {chat_id = msg.chat_id_})
elseif matches == "پاسخ های خودکار" then
local text = "<i>لیست پاسخ های خودکار :</i>\n\n"
local answers = redis:smembers("botBOT-IDanswerslist")
for k,v in pairs(answers) do
text = tostring(text) .. "<i>l" .. tostring(k) .. "l</i> " .. tostring(v) .. " : " .. tostring(redis:hget("botBOT-IDanswers", v)) .. "\n"
end
if redis:scard('botBOT-IDanswerslist') == 0 then text = "<code> EMPTY</code>" end
return send(msg.chat_id_, msg.id_, text)
elseif matches == "مسدود" then
naji = "botBOT-IDblockedusers"
elseif matches == "شخصی" then
naji = "botBOT-IDusers"
elseif matches == "گروه" then
naji = "botBOT-IDgroups"
elseif matches == "سوپرگروه" then
naji = "botBOT-IDsupergroups"
elseif matches == "لینک" then
naji = "botBOT-IDsavedlinks"
elseif matches == "ویت" then
naji = "botBOT-IDwaitelinks"
elseif matches == "مدیر" then
naji = "botBOT-IDadmin"
else
return true
end
local list = redis:smembers(naji)
local text = tostring(matches).." : \n"
for i, v in pairs(list) do
text = tostring(text) .. tostring(i) .. "- " .. tostring(v).."\n"
end
writefile(tostring(naji)..".txt", text)
tdcli_function ({
ID = "SendMessage",
chat_id_ = msg.chat_id_,
reply_to_message_id_ = 0,
disable_notification_ = 0,
from_background_ = 1,
reply_markup_ = nil,
input_message_content_ = {ID = "InputMessageDocument",
document_ = {ID = "InputFileLocal",
path_ = tostring(naji)..".txt"},
caption_ = "لیست "..tostring(matches).." های تبلیغ گر شماره BOT-ID"}
}, dl_cb, nil)
return io.popen("rm -rf "..tostring(naji)..".txt"):read("*all")
elseif text:match("^(وضعیت مشاهده) (.*)$") then
local matches = text:match("^وضعیت مشاهده (.*)$")
if matches == "روشن" then
redis:set("botBOT-IDmarkread", true)
return send(msg.chat_id_, msg.id_, "<i>وضعیت پیام ها >> خوانده شده ✔️✔️\n</i><code>(تیک دوم فعال)</code>")
elseif matches == "خاموش" then
redis:del("botBOT-IDmarkread")
return send(msg.chat_id_, msg.id_, "<i>وضعیت پیام ها >> خوانده نشده ✔️\n</i><code>(بدون تیک دوم)</code>")
end
elseif text:match("^(افزودن با پیام) (.*)$") then
local matches = text:match("^افزودن با پیام (.*)$")
if matches == "روشن" then
redis:set("botBOT-IDaddmsg", true)
return send(msg.chat_id_, msg.id_, "<i>پیام افزودن مخاطب فعال شد</i>")
elseif matches == "خاموش" then
redis:del("botBOT-IDaddmsg")
return send(msg.chat_id_, msg.id_, "<i>پیام افزودن مخاطب غیرفعال شد</i>")
end
elseif text:match("^(افزودن با شماره) (.*)$") then
local matches = text:match("افزودن با شماره (.*)$")
if matches == "روشن" then
redis:set("botBOT-IDaddcontact", true)
return send(msg.chat_id_, msg.id_, "<i>ارسال شماره هنگام افزودن مخاطب فعال شد</i>")
elseif matches == "خاموش" then
redis:del("botBOT-IDaddcontact")
return send(msg.chat_id_, msg.id_, "<i>ارسال شماره هنگام افزودن مخاطب غیرفعال شد</i>")
end
elseif text:match("^(تنظیم پیام افزودن مخاطب) (.*)") then
local matches = text:match("^تنظیم پیام افزودن مخاطب (.*)")
redis:set("botBOT-IDaddmsgtext", matches)
return send(msg.chat_id_, msg.id_, "<i>پیام افزودن مخاطب ثبت شد </i>:\n🔹 "..matches.." 🔹")
elseif text:match('^(تنظیم جواب) "(.*)" (.*)') then
local txt, answer = text:match('^تنظیم جواب "(.*)" (.*)')
redis:hset("botBOT-IDanswers", txt, answer)
redis:sadd("botBOT-IDanswerslist", txt)
return send(msg.chat_id_, msg.id_, "<i>جواب برای | </i>" .. tostring(txt) .. "<i> | تنظیم شد به :</i>\n" .. tostring(answer))
elseif text:match("^(حذف جواب) (.*)") then
local matches = text:match("^حذف جواب (.*)")
redis:hdel("botBOT-IDanswers", matches)
redis:srem("botBOT-IDanswerslist", matches)
return send(msg.chat_id_, msg.id_, "<i>جواب برای | </i>" .. tostring(matches) .. "<i> | از لیست جواب های خودکار پاک شد.</i>")
elseif text:match("^(پاسخگوی خودکار) (.*)$") then
local matches = text:match("^پاسخگوی خودکار (.*)$")
if matches == "روشن" then
redis:set("botBOT-IDautoanswer", true)
return send(msg.chat_id_, 0, "<i>پاسخگویی خودکار تبلیغ گر فعال شد</i>")
elseif matches == "خاموش" then
redis:del("botBOT-IDautoanswer")
return send(msg.chat_id_, 0, "<i>حالت پاسخگویی خودکار تبلیغ گر غیر فعال شد.</i>")
end
elseif text:match("^(تازه سازی)$")then
local list = {redis:smembers("botBOT-IDsupergroups"),redis:smembers("botBOT-IDgroups")}
tdcli_function({
ID = "SearchContacts",
query_ = nil,
limit_ = 999999999
}, function (i, naji)
redis:set("botBOT-IDcontacts", naji.total_count_)
end, nil)
for i, v in pairs(list) do
for a, b in pairs(v) do
tdcli_function ({
ID = "GetChatMember",
chat_id_ = b,
user_id_ = bot_id
}, function (i,naji)
if naji.ID == "Error" then rem(i.id)
end
end, {id=b})
end
end
return send(msg.chat_id_,msg.id_,"<i>تازهسازی آمار تبلیغگر شماره </i><code> BOT-ID </code> با موفقیت انجام شد.")
elseif text:match("^(وضعیت)$") then
local s = redis:get("botBOT-IDmaxjoin") and redis:ttl("botBOT-IDmaxjoin") or 0
local ss = redis:get("botBOT-IDmaxlink") and redis:ttl("botBOT-IDmaxlink") or 0
local msgadd = redis:get("botBOT-IDaddmsg") and "☑️" or "❎"
local numadd = redis:get("botBOT-IDaddcontact") and "✅" or "❎"
local txtadd = redis:get("botBOT-IDaddmsgtext") or "اددی گلم خصوصی پیام بده"
local autoanswer = redis:get("botBOT-IDautoanswer") and "✅" or "❎"
local wlinks = redis:scard("botBOT-IDwaitelinks")
local glinks = redis:scard("botBOT-IDgoodlinks")
local links = redis:scard("botBOT-IDsavedlinks")
local txt = "<i>⚙️ وضعیت اجرایی تبلیغگر</i><code> BOT-ID </code>⛓\n\n" .. tostring(autoanswer) .."<code> حالت پاسخگویی خودکار 🗣 </code>\n" .. tostring(numadd) .. "<code> افزودن مخاطب با شماره 📞 </code>\n" .. tostring(msgadd) .. "<code> افزودن مخاطب با پیام 🗞</code>\n〰〰〰ا〰〰〰\n<code>📄 پیام افزودن مخاطب :</code>\n📍 " .. tostring(txtadd) .. " 📍\n〰〰〰ا〰〰〰\n<code>📁 لینک های ذخیره شده : </code><b>" .. tostring(links) .. "</b>\n<code>⏲ لینک های در انتظار عضویت : </code><b>" .. tostring(glinks) .. "</b>\n🕖 <b>" .. tostring(s) .. " </b><code>ثانیه تا عضویت مجدد</code>\n<code>❄️ لینک های در انتظار تایید : </code><b>" .. tostring(wlinks) .. "</b>\n🕑️ <b>" .. tostring(ss) .. " </b><code>ثانیه تا تایید لینک مجدد</code>"
return send(msg.chat_id_, 0, txt)
elseif text:match("^(امار)$") or text:match("^(آمار)$") then
local gps = redis:scard("botBOT-IDgroups")
local sgps = redis:scard("botBOT-IDsupergroups")
local usrs = redis:scard("botBOT-IDusers")
local links = redis:scard("botBOT-IDsavedlinks")
local glinks = redis:scard("botBOT-IDgoodlinks")
local wlinks = redis:scard("botBOT-IDwaitelinks")
tdcli_function({
ID = "SearchContacts",
query_ = nil,
limit_ = 999999999
}, function (i, naji)
redis:set("botBOT-IDcontacts", naji.total_count_)
end, nil)
local contacts = redis:get("botBOT-IDcontacts")
local text = [[
<i>📈 وضعیت و آمار تبلیغ گر 📊</i>
<code>👤 گفت و گو های شخصی : </code>
<b>]] .. tostring(usrs) .. [[</b>
<code>👥 گروها : </code>
<b>]] .. tostring(gps) .. [[</b>
<code>🌐 سوپر گروه ها : </code>
<b>]] .. tostring(sgps) .. [[</b>
<code>📖 مخاطبین دخیره شده : </code>
<b>]] .. tostring(contacts)..[[</b>
<code>📂 لینک های ذخیره شده : </code>
<b>]] .. tostring(links)..[[</b>
]]
return send(msg.chat_id_, 0, text)
elseif (text:match("^(ارسال به) (.*)$") and msg.reply_to_message_id_ ~= 0) then
local matches = text:match("^ارسال به (.*)$")
local naji
if matches:match("^(همه)$") then
naji = "botBOT-IDall"
elseif matches:match("^(خصوصی)") then
naji = "botBOT-IDusers"
elseif matches:match("^(گروه)$") then
naji = "botBOT-IDgroups"
elseif matches:match("^(سوپرگروه)$") then
naji = "botBOT-IDsupergroups"
else
return true
end
local list = redis:smembers(naji)
local id = msg.reply_to_message_id_
for i, v in pairs(list) do
tdcli_function({
ID = "ForwardMessages",
chat_id_ = v,
from_chat_id_ = msg.chat_id_,
message_ids_ = {[0] = id},
disable_notification_ = 1,
from_background_ = 1
}, dl_cb, nil)
end
return send(msg.chat_id_, msg.id_, "<i>با موفقیت فرستاده شد</i>")
elseif text:match("^(ارسال به سوپرگروه) (.*)") then
local matches = text:match("^ارسال به سوپرگروه (.*)")
local dir = redis:smembers("botBOT-IDsupergroups")
for i, v in pairs(dir) do
tdcli_function ({
ID = "SendMessage",
chat_id_ = v,
reply_to_message_id_ = 0,
disable_notification_ = 0,
from_background_ = 1,
reply_markup_ = nil,
input_message_content_ = {
ID = "InputMessageText",
text_ = matches,
disable_web_page_preview_ = 1,
clear_draft_ = 0,
entities_ = {},
parse_mode_ = nil
},
}, dl_cb, nil)
end
return send(msg.chat_id_, msg.id_, "<i>با موفقیت فرستاده شد</i>")
elseif text:match("^(مسدودیت) (%d+)$") then
local matches = text:match("%d+")
rem(tonumber(matches))
redis:sadd("botBOT-IDblockedusers",matches)
tdcli_function ({
ID = "BlockUser",
user_id_ = tonumber(matches)
}, dl_cb, nil)
return send(msg.chat_id_, msg.id_, "<i>کاربر مورد نظر مسدود شد</i>")
elseif text:match("^(رفع مسدودیت) (%d+)$") then
local matches = text:match("%d+")
add(tonumber(matches))
redis:srem("botBOT-IDblockedusers",matches)
tdcli_function ({
ID = "UnblockUser",
user_id_ = tonumber(matches)
}, dl_cb, nil)
return send(msg.chat_id_, msg.id_, "<i>مسدودیت کاربر مورد نظر رفع شد.</i>")
elseif text:match('^(تنظیم نام) "(.*)" (.*)') then
local fname, lname = text:match('^تنظیم نام "(.*)" (.*)')
tdcli_function ({
ID = "ChangeName",
first_name_ = fname,
last_name_ = lname
}, dl_cb, nil)
return send(msg.chat_id_, msg.id_, "<i>نام جدید با موفقیت ثبت شد.</i>")
elseif text:match("^(تنظیم نام کاربری) (.*)") then
local matches = text:match("^تنظیم نام کاربری (.*)")
tdcli_function ({
ID = "ChangeUsername",
username_ = tostring(matches)
}, dl_cb, nil)
return send(msg.chat_id_, 0, '<i>تلاش برای تنظیم نام کاربری...</i>')
elseif text:match("^(حذف نام کاربری)$") then
tdcli_function ({
ID = "ChangeUsername",
username_ = ""
}, dl_cb, nil)
return send(msg.chat_id_, 0, '<i>نام کاربری با موفقیت حذف شد.</i>')
elseif text:match('^(ارسال کن) "(.*)" (.*)') then
local id, txt = text:match('^ارسال کن "(.*)" (.*)')
send(id, 0, txt)
return send(msg.chat_id_, msg.id_, "<i>ارسال شد</i>")
elseif text:match("^(بگو) (.*)") then
local matches = text:match("^بگو (.*)")
return send(msg.chat_id_, 0, matches)
elseif text:match("^(شناسه من)$") then
return send(msg.chat_id_, msg.id_, "<i>" .. msg.sender_user_id_ .."</i>")
elseif text:match("^(ترک کردن) (.*)$") then
local matches = text:match("^ترک کردن (.*)$")
send(msg.chat_id_, msg.id_, 'تبلیغگر از گروه مورد نظر خارج شد')
tdcli_function ({
ID = "ChangeChatMemberStatus",
chat_id_ = matches,
user_id_ = bot_id,
status_ = {ID = "ChatMemberStatusLeft"},
}, dl_cb, nil)
return rem(matches)
elseif text:match("^(افزودن به همه) (%d+)$") then
local matches = text:match("%d+")
local list = {redis:smembers("botBOT-IDgroups"),redis:smembers("botBOT-IDsupergroups")}
for a, b in pairs(list) do
for i, v in pairs(b) do
tdcli_function ({
ID = "AddChatMember",
chat_id_ = v,
user_id_ = matches,
forward_limit_ = 50
}, dl_cb, nil)
end
end
return send(msg.chat_id_, msg.id_, "<i>کاربر مورد نظر به تمام گروه های من دعوت شد</i>")
elseif (text:match("^(انلاین)$") and not msg.forward_info_)then
return tdcli_function({
ID = "ForwardMessages",
chat_id_ = msg.chat_id_,
from_chat_id_ = msg.chat_id_,
message_ids_ = {[0] = msg.id_},
disable_notification_ = 0,
from_background_ = 1
}, dl_cb, nil)
elseif text:match("^(راهنما)$") then
local txt = '📍راهنمای دستورات تبلیغ گر📍\n\nانلاین\n<i>اعلام وضعیت تبلیغ گر ✔️</i>\n<code>❤️ حتی اگر تبلیغگر شما دچار محدودیت ارسال پیام شده باشد بایستی به این پیام پاسخ دهد❤️</code>\n/reload\n<i>l🔄 بارگذاری مجدد ربات 🔄l</i>\n<code>I⛔️عدم استفاده بی جهت⛔️I</code>\nبروزرسانی ربات\n<i>بروزرسانی ربات به آخرین نسخه و بارگذاری مجدد 🆕</i>\n\nافزودن مدیر شناسه\n<i>افزودن مدیر جدید با شناسه عددی داده شده 🛂</i>\n\nافزودن مدیرکل شناسه\n<i>افزودن مدیرکل جدید با شناسه عددی داده شده 🛂</i>\n\n<code>(⚠️ تفاوت مدیر و مدیرکل دسترسی به اعطا و یا گرفتن مقام مدیریت است⚠️)</code>\n\nحذف مدیر شناسه\n<i>حذف مدیر یا مدیرکل با شناسه عددی داده شده ✖️</i>\n\nترک گروه\n<i>خارج شدن از گروه و حذف آن از اطلاعات گروه ها 🏃</i>\n\nافزودن همه مخاطبین\n<i>افزودن حداکثر مخاطبین و افراد در گفت و گوهای شخصی به گروه ➕</i>\n\nشناسه من\n<i>دریافت شناسه خود 🆔</i>\n\nبگو متن\n<i>دریافت متن 🗣</i>\n\nارسال کن "شناسه" متن\n<i>ارسال متن به شناسه گروه یا کاربر داده شده 📤</i>\n\nتنظیم نام "نام" فامیل\n<i>تنظیم نام ربات ✏️</i>\n\nتازه سازی ربات\n<i>تازهسازی اطلاعات فردی ربات🎈</i>\n<code>(مورد استفاده در مواردی همچون پس از تنظیم نام📍جهت بروزکردن نام مخاطب اشتراکی تبلیغگر📍)</code>\n\nتنظیم نام کاربری اسم\n<i>جایگزینی اسم با نام کاربری فعلی(محدود در بازه زمانی کوتاه) 🔄</i>\n\nحذف نام کاربری\n<i>حذف کردن نام کاربری ❎</i>\n\nافزودن با شماره روشن|خاموش\n<i>تغییر وضعیت اشتراک شماره تبلیغگر در جواب شماره به اشتراک گذاشته شده 🔖</i>\n\nافزودن با پیام روشن|خاموش\n<i>تغییر وضعیت ارسال پیام در جواب شماره به اشتراک گذاشته شده ℹ️</i>\n\nتنظیم پیام افزودن مخاطب متن\n<i>تنظیم متن داده شده به عنوان جواب شماره به اشتراک گذاشته شده 📨</i>\n\nلیست مخاطبین|خصوصی|گروه|سوپرگروه|پاسخ های خودکار|لینک|مدیر\n<i>دریافت لیستی از مورد خواسته شده در قالب پرونده متنی یا پیام 📄</i>\n\nمسدودیت شناسه\n<i>مسدودکردن(بلاک) کاربر با شناسه داده شده از گفت و گوی خصوصی 🚫</i>\n\nرفع مسدودیت شناسه\n<i>رفع مسدودیت کاربر با شناسه داده شده 💢</i>\n\nوضعیت مشاهده روشن|خاموش 👁\n<i>تغییر وضعیت مشاهده پیامها توسط تبلیغگر (فعال و غیرفعالکردن تیک دوم)</i>\n\nامار\n<i>دریافت آمار و وضعیت تبلیغ گر 📊</i>\n\nوضعیت\n<i>دریافت وضعیت اجرایی تبلیغگر⚙️</i>\n\nتازه سازی\n<i>تازهسازی آمار تبلیغگر🚀</i>\n<code>🎃مورد استفاده حداکثر یک بار در روز🎃</code>\n\nارسال به همه|خصوصی|گروه|سوپرگروه\n<i>ارسال پیام جواب داده شده به مورد خواسته شده 📩</i>\n<code>(😄توصیه ما عدم استفاده از همه و خصوصی😄)</code>\n\nارسال به سوپرگروه متن\n<i>ارسال متن داده شده به همه سوپرگروه ها ✉️</i>\n<code>(😜توصیه ما استفاده و ادغام دستورات بگو و ارسال به سوپرگروه😜)</code>\n\nتنظیم جواب "متن" جواب\n<i>تنظیم جوابی به عنوان پاسخ خودکار به پیام وارد شده مطابق با متن باشد 📝</i>\n\nحذف جواب متن\n<i>حذف جواب مربوط به متن ✖️</i>\n\nپاسخگوی خودکار روشن|خاموش\n<i>تغییر وضعیت پاسخگویی خودکار تبلیغ گر به متن های تنظیم شده 📯</i>\n\nافزودن به همه شناسه\n<i>افزودن کابر با شناسه وارد شده به همه گروه و سوپرگروه ها ➕➕</i>\n\nترک کردن شناسه\n<i>عملیات ترک کردن با استفاده از شناسه گروه 🏃</i>\n\nراهنما\n<i>دریافت همین پیام 🆘</i>\n〰〰〰ا〰〰〰\nهمگام سازی با تبچی\n<code>همگام سازی اطلاعات تبلیغ گر با اطلاعات تبچی از قبل نصب شده 🔃</code>'
return send(msg.chat_id_,msg.id_, txt)
elseif tostring(msg.chat_id_):match("^-") then
if text:match("^(ترک کردن)$") then
rem(msg.chat_id_)
return tdcli_function ({
ID = "ChangeChatMemberStatus",
chat_id_ = msg.chat_id_,
user_id_ = bot_id,
status_ = {ID = "ChatMemberStatusLeft"},
}, dl_cb, nil)
elseif text:match("^(افزودن همه مخاطبین)$") then
tdcli_function({
ID = "SearchContacts",
query_ = nil,
limit_ = 999999999
},function(i, naji)
local users, count = redis:smembers("botBOT-IDusers"), naji.total_count_
for n=0, tonumber(count) - 1 do
tdcli_function ({
ID = "AddChatMember",
chat_id_ = i.chat_id,
user_id_ = naji.users_[n].id_,
forward_limit_ = 50
}, dl_cb, nil)
end
for n=1, #users do
tdcli_function ({
ID = "AddChatMember",
chat_id_ = i.chat_id,
user_id_ = users[n],
forward_limit_ = 50
}, dl_cb, nil)
end
end, {chat_id=msg.chat_id_})
return send(msg.chat_id_, msg.id_, "<i>در حال افزودن مخاطبین به گروه ...</i>")
end
end
end
if redis:sismember("botBOT-IDanswerslist", text) then
if redis:get("botBOT-IDautoanswer") then
if msg.sender_user_id_ ~= bot_id then
local answer = redis:hget("botBOT-IDanswers", text)
send(msg.chat_id_, 0, answer)
end
end
end
elseif msg.content_.ID == "MessageContact" then
local id = msg.content_.contact_.user_id_
if not redis:sismember("botBOT-IDaddedcontacts",id) then
redis:sadd("botBOT-IDaddedcontacts",id)
local first = msg.content_.contact_.first_name_ or "-"
local last = msg.content_.contact_.last_name_ or "-"
local phone = msg.content_.contact_.phone_number_
local id = msg.content_.contact_.user_id_
tdcli_function ({
ID = "ImportContacts",
contacts_ = {[0] = {
phone_number_ = tostring(phone),
first_name_ = tostring(first),
last_name_ = tostring(last),
user_id_ = id
},
},
}, dl_cb, nil)
if redis:get("botBOT-IDaddcontact") and msg.sender_user_id_ ~= bot_id then
local fname = redis:get("botBOT-IDfname")
local lnasme = redis:get("botBOT-IDlname") or ""
local num = redis:get("botBOT-IDnum")
tdcli_function ({
ID = "SendMessage",
chat_id_ = msg.chat_id_,
reply_to_message_id_ = msg.id_,
disable_notification_ = 1,
from_background_ = 1,
reply_markup_ = nil,
input_message_content_ = {
ID = "InputMessageContact",
contact_ = {
ID = "Contact",
phone_number_ = num,
first_name_ = fname,
last_name_ = lname,
user_id_ = bot_id
},
},
}, dl_cb, nil)
end
end
if redis:get("botBOT-IDaddmsg") then
local answer = redis:get("botBOT-IDaddmsgtext") or "اددی گلم خصوصی پیام بده"
send(msg.chat_id_, msg.id_, answer)
end
elseif msg.content_.ID == "MessageChatDeleteMember" and msg.content_.id_ == bot_id then
return rem(msg.chat_id_)
elseif msg.content_.ID == "MessageChatJoinByLink" and msg.sender_user_id_ == bot_id then
return add(msg.chat_id_)
elseif msg.content_.ID == "MessageChatAddMembers" then
for i = 0, #msg.content_.members_ do
if msg.content_.members_[i].id_ == bot_id then
add(msg.chat_id_)
end
end
elseif msg.content_.caption_ then
return find_link(msg.content_.caption_)
end
if redis:get("botBOT-IDmarkread") then
tdcli_function ({
ID = "ViewMessages",
chat_id_ = msg.chat_id_,
message_ids_ = {[0] = msg.id_}
}, dl_cb, nil)
end
elseif data.ID == "UpdateOption" and data.name_ == "my_id" then
tdcli_function ({
ID = "GetChats",
offset_order_ = 9223372036854775807,
offset_chat_id_ = 0,
limit_ = 20
}, dl_cb, nil)
end
end
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Windurst_Waters/npcs/Ensasa.lua | 30 | 1873 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Ensasa
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/shop");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
onHalloweenTrade(player,trade,npc);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ENSASA_SHOP_DIALOG);
stock = {
0x0068, 3881,1, --Tarutaru Folding Screen
0x43B8, 5,2, --Crossbow Bolt
0x43A6, 3,2, --Wooden Arrow
0x0070, 456,2, --Yellow Jar
0x43A7, 4,3, --Bone Arrow
0x00DA, 920,3, --Earthen Flowerpot
0x43F4, 3,3, --Little Worm
0x43F3, 9,3, --Lugworm
0x0762, 576,3, --River Foliage
0x13C9, 283,3, --Earth Threnody
0x13C6, 644,3, --Fire Threnody
0x0763, 576,3, --Sea Foliage
0x005C, 905,3, --Tarutaru Stool
0x006E, 4744,3 --White Jar
}
showNationShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Quenty/NevermoreEngine | src/settings-inputkeymap/src/Server/InputKeyMapSetting.lua | 1 | 1673 | --[=[
Registers the settings automatically so we can validate on the server.
@class InputKeyMapSetting
]=]
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local InputKeyMapSettingUtils = require("InputKeyMapSettingUtils")
local SettingsService = require("SettingsService")
local InputKeyMapSettingConstants = require("InputKeyMapSettingConstants")
local SettingDefinition = require("SettingDefinition")
local SettingRegistryServiceShared = require("SettingRegistryServiceShared")
local InputKeyMapSetting = setmetatable({}, BaseObject)
InputKeyMapSetting.ClassName = "InputKeyMapSetting"
InputKeyMapSetting.__index = InputKeyMapSetting
function InputKeyMapSetting.new(serviceBag, inputKeyMapList)
local self = setmetatable(BaseObject.new(), InputKeyMapSetting)
self._serviceBag = assert(serviceBag, "No serviceBag")
self._settingService = self._serviceBag:GetService(SettingsService)
self._settingRegistryServiceShared = self._serviceBag:GetService(SettingRegistryServiceShared)
self._inputKeyMapList = assert(inputKeyMapList, "No inputKeyMapList")
self._maid:GiveTask(self._inputKeyMapList:ObservePairsBrio():Subscribe(function(brio)
if brio:IsDead() then
return
end
-- Register settings
local maid = brio:ToMaid()
local inputModeType, _ = brio:GetValue()
local settingName = InputKeyMapSettingUtils.getSettingName(inputKeyMapList, inputModeType)
local definition = SettingDefinition.new(settingName, InputKeyMapSettingConstants.DEFAULT_VALUE)
maid:GiveTask(self._settingRegistryServiceShared:RegisterSettingDefinition(definition))
end))
return self
end
return InputKeyMapSetting | mit |
noooway/love2d_arkanoid_tutorial | 3-13_Score/menu.lua | 8 | 2800 | local vector = require "vector"
local buttons = require "buttons"
local menu = {}
local menu_buttons_image = love.graphics.newImage( "img/800x600/buttons.png" )
local button_tile_width = 128
local button_tile_height = 64
local play_button_tile_x_pos = 0
local play_button_tile_y_pos = 0
local quit_button_tile_x_pos = 0
local quit_button_tile_y_pos = 64
local selected_x_shift = 128
local tileset_width = 256
local tileset_height = 128
local play_button_quad = love.graphics.newQuad(
play_button_tile_x_pos,
play_button_tile_y_pos,
button_tile_width,
button_tile_height,
tileset_width,
tileset_height )
local play_button_selected_quad = love.graphics.newQuad(
play_button_tile_x_pos + selected_x_shift,
play_button_tile_y_pos,
button_tile_width,
button_tile_height,
tileset_width,
tileset_height )
local quit_button_quad = love.graphics.newQuad(
quit_button_tile_x_pos,
quit_button_tile_y_pos,
button_tile_width,
button_tile_height,
tileset_width,
tileset_height )
local quit_button_selected_quad = love.graphics.newQuad(
quit_button_tile_x_pos + selected_x_shift,
quit_button_tile_y_pos,
button_tile_width,
button_tile_height,
tileset_width,
tileset_height )
local start_button = {}
local quit_button = {}
function menu.load( prev_state, ... )
start_button = buttons.new_button{
text = "New game",
position = vector( (800 - button_tile_width) / 2, 200),
width = button_tile_width,
height = button_tile_height,
image = menu_buttons_image,
quad = play_button_quad,
quad_when_selected = play_button_selected_quad
}
quit_button = buttons.new_button{
text = "Quit",
position = vector( (800 - button_tile_width) / 2, 310),
width = button_tile_width,
height = button_tile_height,
image = menu_buttons_image,
quad = quit_button_quad,
quad_when_selected = quit_button_selected_quad
}
music:play()
end
function menu.update( dt )
buttons.update_button( start_button, dt )
buttons.update_button( quit_button, dt )
end
function menu.draw()
buttons.draw_button( start_button )
buttons.draw_button( quit_button )
end
function menu.keyreleased( key, code )
if key == "return" then
gamestates.set_state( "game", { current_level = 1 } )
elseif key == 'escape' then
love.event.quit()
end
end
function menu.mousereleased( x, y, button, istouch )
if button == 'l' or button == 1 then
if buttons.mousereleased( start_button, x, y, button ) then
gamestates.set_state( "game", { current_level = 1 } )
elseif buttons.mousereleased( quit_button, x, y, button ) then
love.event.quit()
end
elseif button == 'r' or button == 2 then
love.event.quit()
end
end
return menu
| mit |
shahabsaf1/merbot.cl | plugins/moderation.lua | 29 | 12162 | do
local function check_member(extra, success, result)
local data = extra.data
for k,v in pairs(result.members) do
if v.id ~= our_id then
data[tostring(extra.msg.to.id)] = {
moderators = {[tostring(v.id)] = '@'..v.username},
settings = {
set_name = string.gsub(extra.msg.to.print_name, '_', ' '),
lock_bots = 'no',
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
anti_flood = 'ban',
welcome = 'group',
sticker = 'ok',
}
}
save_data(_config.moderation.data, data)
return send_large_msg(get_receiver(extra.msg), 'You have been promoted as moderator for this group.')
end
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted as moderator for this group.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted from moderator of this group.')
end
local function admin_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted as admin.')
end
local function admin_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(extra, success, result)
for k,v in pairs(result.members) do
if v.username == extra.username then
if extra.mod_cmd == 'promote' then
return promote(extra.receiver, '@'..extra.username, v.id)
elseif extra.mod_cmd == 'demote' then
return demote(extra.receiver, '@'..extra.username, v.id)
elseif extra.mod_cmd == 'adminprom' then
return admin_promote(extra.receiver, '@'..extra.username, v.id)
elseif extra.mod_cmd == 'admindem' then
return admin_demote(extra.receiver, '@'..extra.username, v.id)
end
end
end
send_large_msg(extra.receiver, 'No user '..extra.username..' in this group.')
end
local function action_by_id(extra, success, result)
if success == 1 then
for k,v in pairs(result.members) do
if extra.matches[2] == tostring(v.id) then
if extra.matches[1] == 'promote' then
return promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
elseif extra.matches[1] == 'demote' then
return demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
elseif extra.matches[1] == 'adminprom' then
return admin_promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
elseif extra.matches[1] == 'admindem' then
return admin_demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
end
end
end
send_large_msg('chat#id'..result.id, 'No user user#id'..extra.matches[2]..' in this group.')
end
end
local function action_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' and not is_sudo(member_id) then
if extra.msg.text == '!promote' then
return promote(get_receiver(msg), member_username, member_id)
elseif extra.msg.text == '!demote' then
return demote(get_receiver(msg), member_username, member_id)
elseif extra.msg.text == '!adminprom' then
return admin_promote(get_receiver(msg), member_username, member_id)
elseif extra.msg.text == '!admindem' then
return admin_demote(get_receiver(msg), member_username, member_id)
end
else
return 'Use This in Your Groups.'
end
end
function run(msg, matches)
local receiver = get_receiver(msg)
if is_chat_msg(msg) then
if is_mod(msg.from.id, msg.to.id) then
if matches[1] == 'promote' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
elseif matches[1] == 'demote' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
demote(receiver, 'user_'..matches[2], matches[2])
elseif string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
if username == msg.from.username then
return 'You can\'t demote yourself.'
else
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
end
elseif matches[1] == 'modlist' then
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message .. '- '..v..' [' ..k.. '] \n'
end
return message
end
end
if is_admin(msg.from.id, msg.to.id) then
if matches[1] == 'adminprom' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif matches[2] and string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
elseif matches[1] == 'admindem' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
admin_demote(receiver, 'user_'..matches[2], matches[2])
elseif string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
elseif matches[1] == 'adminlist' then
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if next(data['admins']) == nil then --fix way
return 'No admin available.'
end
for k,v in pairs(data['admins']) do
message = 'List for Bot admins:\n'..'- '..v..' ['..k..'] \n'
end
return message
end
end
else
return 'Only works on group'
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
chat_info(get_receiver(msg), check_member,{data=data, msg=msg})
else
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
local username = msg.from.username or msg.from.print_name
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={[tostring(msg.from.id)] = '@'..username},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_bots = 'no',
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
anti_flood = 'ban',
welcome = 'group',
sticker = 'ok',
}
}
save_data(_config.moderation.data, data)
return 'Group has been added, and @'..username..' has been promoted as moderator for this group.'
end
end
end
return {
description = 'Moderation plugin',
usage = {
moderator = {
'!promote : If typed when replying, promote replied user as moderator',
'!promote <user_id> : Promote user_id as moderator',
'!promote @<username> : Promote username as moderator',
'!demote : If typed when replying, demote replied user from moderator',
'!demote <user_id> : Demote user_id from moderator',
'!demote @<username> : Demote username from moderator',
'!modlist : List of moderators'
},
sudo = {
'!adminprom : If typed when replying, promote replied user as admin.',
'!adminprom <user_id> : Promote user_id as admin.',
'!adminprom @<username> : Promote username as admin.',
'!admindem : If typed when replying, demote replied user from admin.',
'!admindem <user_id> : Demote user_id from admin.',
'!admindem @<username> : Demote username from admin.'
},
},
patterns = {
'^!(admindem) (%d+)$',
'^!(admindem) (.*)$',
'^!(admindem)$',
'^!(adminlist)$',
'^!(adminprom) (%d+)$',
'^!(adminprom) (.*)$',
'^!(adminprom)$',
'^!(demote) (.*)$',
'^!(demote)$',
'^!(modlist)$',
'^!(promote) (.*)$',
'^!(promote)$',
'^!(promote) (%d+)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_created)$'
},
run = run
}
end
| gpl-2.0 |
Lord-Mohammad/uzzy | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
ffxiphoenix/darkstar | scripts/globals/weaponskills/trueflight.lua | 18 | 4616 | -----------------------------------
-- Skill Level: N/A
-- Description: Deals light elemental damage. Damage varies with TP. Gastraphetes: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Ranger) quest.
-- Does not work with Flashy Shot.
-- Does not work with Stealth Shot.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Properties
-- Element: Light
-- Skillchain Properties: Fragmentation/Scission
-- Modifiers: AGI:30%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 4.0 4.25 4.75
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 4; params.ftp200 = 4.25; params.ftp300 = 4.75;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0;
params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
params.ele = ELE_LIGHT;
params.skill = SKILL_MRK;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 3.8906; params.ftp200 = 6.3906; params.ftp300 = 9.3906;
params.agi_wsc = 1.0;
end
local damage, tpHits, extraHits = doMagicWeaponskill(player, target, params);
if ((player:getEquipID(SLOT_RANGED) == 19001) and (player:getMainJob() == JOB_RNG)) then
if (damage > 0) then
-- AFTERMATH LV1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 3);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 3);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 3);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 3);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 3);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 3);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 3);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 3);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 3);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 3);
-- AFTERMATH LV2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 4);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 4);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 4);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 4);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 4);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 4);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 4);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 4);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 4);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 4);
-- AFTERMATH LV3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 2);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Gustav_Tunnel/mobs/Goblin_Mercenary.lua | 23 | 1026 | ----------------------------------
-- Area: Gustav Tunnel
-- MOB: Goblin Mercenary
-- Note: Place holder Wyvernpoacher Drachlox
-----------------------------------
require("scripts/zones/Gustav_Tunnel/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
checkGoVregime(killer,mob,764,3);
checkGoVregime(killer,mob,765,3);
local mob = mob:getID();
if (Wyvernpoacher_Drachlox_PH[mob] ~= nil) then
local ToD = GetServerVariable("[POP]Wyvernpoacher_Drachlox");
if (ToD <= os.time(t) and GetMobAction(Wyvernpoacher_Drachlox) == 0) then
if (math.random((1),(20)) == 5) then
UpdateNMSpawnPoint(Wyvernpoacher_Drachlox);
GetMobByID(Wyvernpoacher_Drachlox):setRespawnTime(GetMobRespawnTime(mob));
SetServerVariable("[PH]Wyvernpoacher_Drachlox", mob);
DeterMob(mob, true);
end
end
end
end;
| gpl-3.0 |
vilarion/Illarion-Content | scheduled/factionLeader.lua | 3 | 1906 | --[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
--Checks if the playable faction leaders is logged in and thus the NPC needs to be out of player sight
local common = require("base.common")
local M = {}
M.informationTable = {
{npcName="Rosaline Edwards", usualPosition=position(122, 521, 0), newPosition=position(237, 104, 0)},
{npcName="Valerio Guilianni", usualPosition=position(337, 215, 0), newPosition=position(238, 104, 0)},
{npcName="Elvaine Morgan", usualPosition=position(898, 775, 2), newPosition=position(239, 104, 0)}}
function M.checkFactionLeader()
for i=1, #(M.informationTable) do
local charObject = common.CheckIfOnline(M.informationTable[i].npcName)
if charObject ~= nil then
M.updatePosition(M.informationTable[i].usualPosition, M.informationTable[i].newPosition)
else
M.updatePosition(M.informationTable[i].newPosition, M.informationTable[i].usualPosition)
end
end
end
function M.updatePosition(usualPosition, newPosition)
if world:isCharacterOnField(usualPosition) == true then
local npcCharObject = world:getCharacterOnField(usualPosition);
if npcCharObject:getType() == Character.npc then
npcCharObject:forceWarp(newPosition);
end
end
end
return M
| agpl-3.0 |
moonlight/blues-brothers-rpg | data/scripts/AI.lua | 2 | 3206 | --
-- Our 'magnificent' AI implementation
--
-- Common states for an AI monster
AI_WAITING = 1
AI_WALKING = 2
AI_ATTACK = 3
AI_DEAD = 4
AI_HIT = 5
AI_READY = 6
CommonAI = {}
function CommonAI:event_init()
self.state = AI_READY
self.tick_time = 1
self.charge = 0
self.charge_time = 200
self.attack_time = 50
self.attack_range = 3
self.attack_min_dam = 1
self.attack_max_dam = 3
self.health = 25
self.maxHealth = self.health
end
function CommonAI:tick()
if (self.charge > 0) then self.charge = self.charge - 1 end
-- Switch to ready from walking
if (self.state == AI_WALKING and self.walking == 0) then
self:setState(AI_READY)
end
-- When an AI is ready, it's waiting for something to happen to take action
if (self.state == AI_READY) then
-- Check if player is drawing near
playerDist = playerDistance(self)
local player = m_get_player()
if (playerDist < 5 and player.state ~= CHR_DEAD) then
-- Chase or attack?
if (playerDist <= self.attack_range) then
-- Attack on charged
if (self.charge == 0 and self.walking == 0) then
self:attack(playerDirection(self))
end
else
self:walk(playerDirection(self))
end
end
end
end
function CommonAI:attack(dir)
--m_message("AI attacking!");
self.dir = dir
self:setState(AI_ATTACK)
local player = m_get_player()
-- Handle attack (deal damage to player)
player:takeDamage(self.attack_min_dam + math.random(self.attack_max_dam - self.attack_min_dam))
-- Spawn the hitting effect (ie. sparks)
if (self.attack_object) then self:attack_object(player) end
ActionController:addSequence{
ActionWait(self.attack_time),
ActionSetState(self, AI_READY),
ActionSetVariable(self, "charge", self.charge_time),
}
end
function CommonAI:walk(dir)
m_walk_obj(self, dir)
self:setState(AI_WALKING)
end
function CommonAI:setState(state)
self.state = state
if (self.state == AI_ATTACK) then self.attacking = 1 else self.attacking = 0 end
self:update_bitmap()
if (self.state == AI_DEAD) then
if (self.do_death) then self:do_death()
else
self.animation = nil
ActionController:addSequence({
ActionWait(100),
ActionSetVariable(self, "draw_mode", DM_TRANS),
ActionTweenVariable(self, "alpha", 200, 0),
ActionDestroyObject(self),
})
end
self.tick_time = 0
end
end
function CommonAI:take_damage(amount)
if (self.state ~= AI_DEAD) then
-- Should probably suspend a little when being hit
--self:setState(AI_HIT)
self.health = self.health - amount
-- Spawn the getting hit effect (ie. blood)
if (self.do_hit) then self:do_hit()
else
local obj = m_add_object(self.x, self.y, "BloodSplat")
obj.offset_z = obj.offset_z + 12
end
if (self.health <= 0) then
self:setState(AI_DEAD)
local player = m_get_player()
player.experience = player.experience + self.experience
if (player.experience >= player.nextLevelExperience) then
player.endurance = player.endurance + 5
player.nextLevelExperience = 2.5 * player.nextLevelExperience
player:derive_attributes()
end
end
end
end
| gpl-2.0 |
suvjunmd/OpenRA | mods/cnc/maps/gdi05a/gdi05a.lua | 19 | 6681 | RepairThreshold = { Easy = 0.3, Normal = 0.6, Hard = 0.9 }
ActorRemovals =
{
Easy = { Actor167, Actor168, Actor190, Actor191, Actor193, Actor194, Actor196, Actor198, Actor200 },
Normal = { Actor167, Actor194, Actor196, Actor197 },
Hard = { },
}
GdiTanks = { "mtnk", "mtnk" }
GdiApc = { "apc" }
GdiInfantry = { "e1", "e1", "e1", "e1", "e1", "e2", "e2", "e2", "e2", "e2" }
GdiBase = { GdiNuke1, GdiNuke2, GdiProc, GdiSilo1, GdiSilo2, GdiPyle, GdiWeap, GdiHarv }
NodSams = { Sam1, Sam2, Sam3, Sam4 }
CoreNodBase = { NodConYard, NodRefinery, HandOfNod, Airfield }
Grd1UnitTypes = { "bggy" }
Grd1Path = { waypoint4.Location, waypoint5.Location, waypoint10.Location }
Grd1Delay = { Easy = DateTime.Minutes(2), Normal = DateTime.Minutes(1), Hard = DateTime.Seconds(30) }
Grd2UnitTypes = { "bggy" }
Grd2Path = { waypoint0.Location, waypoint1.Location, waypoint2.Location }
Grd3Units = { GuardTank1, GuardTank2 }
Grd3Path = { waypoint4.Location, waypoint5.Location, waypoint9.Location }
AttackDelayMin = { Easy = DateTime.Minutes(1), Normal = DateTime.Seconds(45), Hard = DateTime.Seconds(30) }
AttackDelayMax = { Easy = DateTime.Minutes(2), Normal = DateTime.Seconds(90), Hard = DateTime.Minutes(1) }
AttackUnitTypes =
{
Easy =
{
{ HandOfNod, { "e1", "e1" } },
{ HandOfNod, { "e1", "e3" } },
{ HandOfNod, { "e1", "e1", "e3" } },
{ HandOfNod, { "e1", "e3", "e3" } },
},
Normal =
{
{ HandOfNod, { "e1", "e1", "e3" } },
{ HandOfNod, { "e1", "e3", "e3" } },
{ HandOfNod, { "e1", "e1", "e3", "e3" } },
{ Airfield, { "bggy" } },
},
Hard =
{
{ HandOfNod, { "e1", "e1", "e3", "e3" } },
{ HandOfNod, { "e1", "e1", "e1", "e3", "e3" } },
{ HandOfNod, { "e1", "e1", "e3", "e3", "e3" } },
{ Airfield, { "bggy" } },
{ Airfield, { "ltnk" } },
}
}
AttackPaths =
{
{ waypoint0.Location, waypoint1.Location, waypoint2.Location, waypoint3.Location },
{ waypoint4.Location, waypoint9.Location, waypoint7.Location, waypoint8.Location },
}
Build = function(factory, units, action)
if factory.IsDead or factory.Owner ~= nod then
return
end
if not factory.Build(units, action) then
Trigger.AfterDelay(DateTime.Seconds(5), function()
Build(factory, units, action)
end)
end
end
Attack = function()
local types = Utils.Random(AttackUnitTypes[Map.Difficulty])
local path = Utils.Random(AttackPaths)
Build(types[1], types[2], function(units)
Utils.Do(units, function(unit)
if unit.Owner ~= nod then return end
unit.Patrol(path, false)
Trigger.OnIdle(unit, unit.Hunt)
end)
end)
Trigger.AfterDelay(Utils.RandomInteger(AttackDelayMin[Map.Difficulty], AttackDelayMax[Map.Difficulty]), Attack)
end
Grd1Action = function()
Build(Airfield, Grd1UnitTypes, function(units)
Utils.Do(units, function(unit)
if unit.Owner ~= nod then return end
Trigger.OnKilled(unit, function()
Trigger.AfterDelay(Grd1Delay[Map.Difficulty], Grd1Action)
end)
unit.Patrol(Grd1Path, true, DateTime.Seconds(7))
end)
end)
end
Grd2Action = function()
Build(Airfield, Grd2UnitTypes, function(units)
Utils.Do(units, function(unit)
if unit.Owner ~= nod then return end
unit.Patrol(Grd2Path, true, DateTime.Seconds(5))
end)
end)
end
Grd3Action = function()
local unit
for i, u in ipairs(Grd3Units) do
if not u.IsDead then
unit = u
break
end
end
if unit ~= nil then
Trigger.OnKilled(unit, function()
Grd3Action()
end)
unit.Patrol(Grd3Path, true, DateTime.Seconds(11))
end
end
DiscoverGdiBase = function(actor, discoverer)
if baseDiscovered or not discoverer == gdi then
return
end
Utils.Do(GdiBase, function(actor)
actor.Owner = gdi
end)
GdiHarv.FindResources()
baseDiscovered = true
gdiObjective3 = gdi.AddPrimaryObjective("Eliminate all Nod forces in the area.")
gdi.MarkCompletedObjective(gdiObjective1)
Attack()
end
SetupWorld = function()
Utils.Do(ActorRemovals[Map.Difficulty], function(unit)
unit.Destroy()
end)
Media.PlaySpeechNotification(gdi, "Reinforce")
Reinforcements.Reinforce(gdi, GdiTanks, { GdiTankEntry.Location, GdiTankRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end)
Reinforcements.Reinforce(gdi, GdiApc, { GdiApcEntry.Location, GdiApcRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end)
Reinforcements.Reinforce(gdi, GdiInfantry, { GdiInfantryEntry.Location, GdiInfantryRallyPoint.Location }, 15, function(actor) actor.Stance = "Defend" end)
Trigger.OnPlayerDiscovered(gdiBase, DiscoverGdiBase)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == nod and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == nod and building.Health < RepairThreshold[Map.Difficulty] * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Trigger.OnAllKilled(NodSams, function()
gdi.MarkCompletedObjective(gdiObjective2)
Actor.Create("airstrike.proxy", true, { Owner = gdi })
end)
GdiHarv.Stop()
NodHarv.FindResources()
if Map.Difficulty ~= "Easy" then
Trigger.OnDamaged(NodHarv, function()
Utils.Do(nod.GetGroundAttackers(), function(unit)
unit.AttackMove(NodHarv.Location)
if Map.Difficulty == "Hard" then
unit.Hunt()
end
end)
end)
end
Trigger.AfterDelay(DateTime.Seconds(45), Grd1Action)
Trigger.AfterDelay(DateTime.Minutes(3), Grd2Action)
Grd3Action()
end
WorldLoaded = function()
gdiBase = Player.GetPlayer("AbandonedBase")
gdi = Player.GetPlayer("GDI")
nod = Player.GetPlayer("Nod")
Trigger.OnObjectiveAdded(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(gdi, function()
Media.PlaySpeechNotification(player, "Lose")
end)
Trigger.OnPlayerWon(gdi, function()
Media.PlaySpeechNotification(player, "Win")
end)
nodObjective = nod.AddPrimaryObjective("Destroy all GDI troops.")
gdiObjective1 = gdi.AddPrimaryObjective("Find the GDI base.")
gdiObjective2 = gdi.AddSecondaryObjective("Destroy all SAM sites to receive air support.")
SetupWorld()
Camera.Position = GdiTankRallyPoint.CenterPosition
end
Tick = function()
if gdi.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
nod.MarkCompletedObjective(nodObjective)
end
end
if baseDiscovered and nod.HasNoRequiredUnits() then
gdi.MarkCompletedObjective(gdiObjective3)
end
end | gpl-3.0 |
elixboyBW/elixboySPM | plugins/btc.lua | 289 | 1375 | -- See https://bitcoinaverage.com/api
local function getBTCX(amount,currency)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
-- Do request on bitcoinaverage, the final / is critical!
local res,code = https.request(base_url..currency.."/")
if code ~= 200 then return nil end
local data = json:decode(res)
-- Easy, it's right there
text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid
-- If we have a number as second parameter, calculate the bitcoin amount
if amount~=nil then
btc = tonumber(amount) / tonumber(data.ask)
text = text.."\n "..currency .." "..amount.." = BTC "..btc
end
return text
end
local function run(msg, matches)
local cur = 'EUR'
local amt = nil
-- Get the global match out of the way
if matches[1] == "!btc" then
return getBTCX(amt,cur)
end
if matches[2] ~= nil then
-- There is a second match
amt = matches[2]
cur = string.upper(matches[1])
else
-- Just a EUR or USD param
cur = string.upper(matches[1])
end
return getBTCX(amt,cur)
end
return {
description = "Bitcoin global average market value (in EUR or USD)",
usage = "!btc [EUR|USD] [amount]",
patterns = {
"^!btc$",
"^!btc ([Ee][Uu][Rr])$",
"^!btc ([Uu][Ss][Dd])$",
"^!btc (EUR) (%d+[%d%.]*)$",
"^!btc (USD) (%d+[%d%.]*)$"
},
run = run
}
| gpl-2.0 |
keshwans/vlc | share/lua/playlist/pinkbike.lua | 97 | 2080 | --[[
$Id$
Copyright © 2009 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "pinkbike.com/video/%d+" )
end
-- Parse function.
function parse()
p = {}
if string.match ( vlc.path, "pinkbike.com/video/%d+" ) then
while true do
line = vlc.readline()
if not line then break end
-- Try to find video id
if string.match( line, "video_src.+swf.id=(.*)\"") then
_,_,videoid = string.find( line, "video_src.+swf.id=(.*)\"")
catalog = math.floor( tonumber( videoid ) / 10000 )
end
-- Try to find the video's title
if string.match( line, "<title>(.*)</title>" ) then
_,_,name = string.find (line, "<title>(.*)</title>")
end
-- Try to find server which has our video
if string.match( line, "<link rel=\"videothumbnail\" href=\"http://(.*)/vt/svt-") then
_,_,server = string.find (line, '<link rel="videothumbnail" href="http://(.*)/vt/svt-' )
end
if string.match( line, "<link rel=\"videothumbnail\" href=\"(.*)\" type=\"image/jpeg\"") then
_,_,arturl = string.find (line, '<link rel="videothumbnail" href="(.*)" type="image/jpeg"')
end
end
end
table.insert( p, { path = "http://" .. server .. "/vf/" .. catalog .. "/pbvid-" .. videoid .. ".flv"; name = name; arturl = arturl } )
return p
end
| gpl-2.0 |
0x0mar/ettercap | src/lua/share/third-party/stdlib/src/xml.lua | 17 | 2787 | -- XML extensions to string module.
-- @class module
-- @name xml
require "base"
require "string_ext"
--- Write a table as XML.
-- The input format is assumed to be that output by luaexpat.
-- @param t table to print.
-- In each element, tag is its name, attr is the table of attributes,
-- and the sub-elements are held in the integer keys
-- @param indent indent between levels (default: <code>"\t"</code>)
-- @param spacing space before every line
-- @returns XML string
function string.writeXML (t, indent, spacing)
indent = indent or "\t"
spacing = spacing or ""
return render (t,
function (x)
spacing = spacing .. indent
if x.tag then
local s = "<" .. x.tag
if type (x.attr) == "table" then
for i, v in pairs (x.attr) do
if type (i) ~= "number" then
-- luaexpat gives names of attributes in list elements
s = s .. " " .. tostring (i) .. "=" .. string.format ("%q", tostring (v))
end
end
end
if #x == 0 then
s = s .. " /"
end
s = s .. ">"
return s
end
return ""
end,
function (x)
spacing = string.gsub (spacing, indent .. "$", "")
if x.tag and #x > 0 then
return spacing .. "</" .. x.tag .. ">"
end
return ""
end,
function (s)
s = tostring (s)
s = string.gsub (s, "&([%S]+)",
function (s)
if not string.match (s, "^#?%w+;") then
return "&" .. s
else
return "&" .. s
end
end)
s = string.gsub (s, "<", "<")
s = string.gsub (s, ">", ">")
return s
end,
function (x, i, v, is, vs)
local s = ""
if type (i) == "number" then
s = spacing .. vs
end
return s
end,
function (_, i, _, j)
if type (i) == "number" or type (j) == "number" then
return "\n"
end
return ""
end)
end
| gpl-2.0 |
azekillDIABLO/Voxellar | mods/PLAYER/hud_hunger/hud/itemwheel.lua | 4 | 4796 | local hb = {}
local scale = tonumber(core.setting_get("hud_scaling")) or 1
local function update_wheel(player)
local name = player:get_player_name()
if not player or not name then
return
end
local i = player:get_wield_index()
local i1 = i - 1
local i3 = i + 1
-- it's a wheel
if i1 < 1 then
i1 = HUD_IW_MAX
end
if i3 > HUD_IW_MAX then
i3 = 1
end
-- get the displayed items
local inv = player:get_inventory()
local item = hb[name].item
local index = hb[name].index
local item2 = player:get_wielded_item():get_name()
-- update all items when wielded has changed
if item and item2 and item ~= item2 or item == "wheel_init" or (index and index ~= i) then
local items = {}
items[1] = inv:get_stack("main", i1):get_name() or nil
items[2] = item2
items[3] = inv:get_stack("main", i3):get_name() or nil
local num = player:get_wielded_item():get_count()
local wear = player:get_wielded_item():get_wear()
if num < 2 then
num = ""
else
num = tostring(num)
end
if wear > 0 then
num = tostring(100 - math.floor((wear/65535)*100)) .. "%"
end
for n, m in pairs(items) do
-- some default values
local image = "hud_wielded.png"
local need_scale = false
local s1 = {x = 1*scale, y = 1*scale}
local s2 = {x = 3*scale, y = 3*scale}
if n ~= 2 then
s1 = {x = 0.6*scale, y = 0.6*scale}
s2 = {x = 2*scale, y = 2*scale}
end
-- get the images
local def = minetest.registered_items[m]
if def then
if def.tiles and (def.tiles[1] and not def.tiles[1].name) then
image = minetest.inventorycube(def.tiles[1], def.tiles[6] or def.tiles[3] or def.tiles[1], def.tiles[3] or def.tiles[1])
need_scale = true
end
if def.inventory_image and def.inventory_image ~= "" then
image = def.inventory_image
need_scale = false
end
if def.wielded_image and def.wielded_image ~= "" then
image = def.wielded_image
need_scale = false
end
-- needed for nodes with inventory cube inv imges, e.g. glass
if string.find(image, 'inventorycube') then
need_scale = true
end
end
-- get the id and update hud elements
local id = hb[name].id[n]
if id and image then
if need_scale then
player:hud_change(id, "scale", s1)
else
player:hud_change(id, "scale", s2)
end
-- make previous and next item darker
--if n ~= 2 then
--image = image .. "^[colorize:#0005"
--end
player:hud_change(id, "text", image)
end
end
if hb[name].id[4] then
player:hud_change(hb[name].id[4], "text", num)
end
end
-- update wielded buffer
if hb[name].id[2] ~= nil then
hb[name].item = item2
hb[name].index = i
end
end
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
hb[name]= {}
hb[name].id = {}
hb[name].item = "wheel_init"
hb[name].index = 1
minetest.after(0.1, function()
-- hide builtin hotbar
local hud_flags = player:hud_get_flags()
hud_flags.hotbar = false
player:hud_set_flags(hud_flags)
player:hud_add({
hud_elem_type = "image",
text = "hud_new.png",
position = {x = 0.5, y = 1},
scale = {x = 1*scale, y = 1*scale},
alignment = {x = 0, y = -1},
offset = {x = 0, y = 0}
})
hb[name].id[1] = player:hud_add({
hud_elem_type = "image",
text = "hud_wielded.png",
position = {x = 0.5, y = 1},
scale = {x = 1*scale, y = 1*scale},
alignment = {x = 0, y = -1},
offset = {x = -75*scale, y = -8*scale}
})
hb[name].id[2] = player:hud_add({
hud_elem_type = "image",
text = "hud_wielded.png",
position = {x = 0.5, y = 1},
scale = {x = 3*scale, y = 3*scale},
alignment = {x = 0, y = -1},
offset = {x = 0, y = -12*scale}
})
hb[name].id[3] = player:hud_add({
hud_elem_type = "image",
text = "hud_wielded.png",
position = {x = 0.5, y = 1},
scale = {x = 1*scale, y = 1*scale},
alignment = {x = 0, y = -1},
offset = {x = 75*scale, y = -8*scale}
})
hb[name].id[4] = player:hud_add({
hud_elem_type = "text",
position = {x = 0.5, y = 1},
offset = {x = 35*scale, y = -55*scale},
alignment = {x = 0, y = -1},
number = 0xffffff,
text = "",
})
-- init item wheel
minetest.after(0, function()
hb[name].item = "wheel_init"
update_wheel(player)
end)
end)
end)
local function update_wrapper(a, b, player)
local name = player:get_player_name()
if not name then
return
end
minetest.after(0, function()
hb[name].item = "wheel_init"
update_wheel(player)
end)
end
minetest.register_on_placenode(update_wrapper)
minetest.register_on_dignode(update_wrapper)
local timer = 0
minetest.register_globalstep(function(dtime)
timer = timer + dtime
if timer >= HUD_IW_TICK then
timer = 0
for _, player in ipairs(minetest.get_connected_players()) do
update_wheel(player)
end
end--timer
end) | lgpl-2.1 |
ffxiphoenix/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua | 57 | 2181 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: qm7 (??? - Ancient Papyrus Shreds)
-- Involved in Quest: In Defiant Challenge
-- @pos 105.275 -32 92.551 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(ANCIENT_PAPYRUS_SHRED1);
player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1);
end
if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1088, 1);
player:messageSpecial(ITEM_OBTAINED, 1088);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088);
end
end
if (player:hasItem(1088)) then
player:delKeyItem(ANCIENT_PAPYRUS_SHRED1);
player:delKeyItem(ANCIENT_PAPYRUS_SHRED2);
player:delKeyItem(ANCIENT_PAPYRUS_SHRED3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Konschtat_Highlands/npcs/qm1.lua | 34 | 1376 | -----------------------------------
-- Area: Konschtat Highlands
-- NPC: qm1 (???)
-- Continues Quests: Past Perfect
-- @pos -201 16 80 108
-----------------------------------
package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Konschtat_Highlands/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT);
if (PastPerfect == QUEST_ACCEPTED) then
player:addKeyItem(0x6d);
player:messageSpecial(KEYITEM_OBTAINED,0x6d); -- Tattered Mission Orders
else
player:messageSpecial(FIND_NOTHING);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Sacrarium/npcs/qm3.lua | 17 | 1738 | -----------------------------------
-- Area: Sacrarium
-- NPC: qm3 (???)
-- Notes: Used to spawn Old Prof. Mariselle
-- @pos 62.668 -3.111 127.288 28
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OldProfessor = 16891970;
if (GetServerVariable("Old_Prof_Spawn_Location") == 3) then
if (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0) then
player:messageSpecial(EVIL_PRESENCE);
SpawnMob(OldProfessor,300):updateClaim(player);
GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC
else
player:messageSpecial(DRAWER_SHUT);
end
elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false) then
player:addKeyItem(RELIQUIARIUM_KEY);
player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY);
else
player:messageSpecial(DRAWER_OPEN);
player:messageSpecial(DRAWER_EMPTY);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
AIUbi/Easy-access | easylua_access.lua | 1 | 3585 | if CLIENT then return end
easylua_manager = {}
easylua_manager.access_manager = {}
easylua_manager.access_manager.access_list = {}
easylua_manager.access_manager.add = function(userinfo, caller)
if not userinfo._steam64 then return "[EASYLUA ERROR]: Need SteamID64" end
if #userinfo._steam64 ~= 17 then return "[EASYLUA ERROR]: Length of SteamID64 must have 17 symbols" end
if easylua_manager.access_manager.access_list["STEAM:"..userinfo._steam64] then return "[EASYLUA ERROR]: User alredy exists" end
if not userinfo._name then
for _, o in pairs(player.GetAll()) do
if o:SteamID64() == userinfo._steam64 then
userinfo._name = o:Nick()
userinfo._ip = o:IPAddress()
end
end
if not userinfo._name then
userinfo._name = "Unknown"
userinfo._ip = "Unknown"
end
end
easylua_manager.access_manager.access_list["STEAM:"..userinfo._steam64] =
{
_steam64 = "STEAM:"..userinfo._steam64,
_name = userinfo._name,
_ip = userinfo._ip,
_caller = IsValid(caller) and
{
_steam64 = "STEAM:"..caller:SteamID64(),
_name = caller:Nick(),
_ip = caller:IPAddress()
} or {}
}
if _name == "Unknown" then return "[EASYLUA WARNING]: Player not found, name set to Unknown, access granted for "..userinfo._steam64 end
return "[EASYLUA]: Access granted for "..userinfo._name
end
easylua_manager.access_manager.del = function(steamid64)
if not steamid64 then return "[EASYLUA ERROR]: Need SteamID64" end
if #steamid64 ~= 17 then return "[EASYLUA ERROR]: Length of SteamID64 must have 17 symbols" end
if not easylua_manager.access_manager.access_list["STEAM:"..steamid64] then return "[EASYLUA ERROR]: User not exists" end
easylua_manager.access_manager.access_list["STEAM:"..steamid64] = nil
return "[EASYLUA]: Remove "..steamid64
end
easylua_manager.access_manager.file_update = function(isload)
if isload then
if file.Exists("whitelist_gcompute.txt","DATA") then
local l = util.JSONToTable(file.Read("whitelist_gcompute.txt","DATA"))
easylua_manager.access_manager.access_list = l or {}
else
file.Write("whitelist_gcompute.txt",util.TableToJSON({}))
easylua_manager.access_manager.file_update(isload)
end
else
file.Write("whitelist_gcompute.txt",util.TableToJSON(easylua_manager.access_manager.access_list))
end
end
easylua_manager.access_manager.update_access = function()
easylua_manager.access_manager.file_update(true)
for _, o in pairs(player.GetAll()) do
if easylua_manager.access_manager.access_list["STEAM:"..o:SteamID64()] then
o:SetNWBool("glua_access", true)
else
o:SetNWBool("glua_access", false)
end
end
end
concommand.Add("lua_access", function(ply, cmd, args)
if not IsValid(ply) or not ply:IsAdmin() then return end
local act = args[1]
if act == "add" then
print(easylua_manager.access_manager.add({_steam64 = args[2]}, ply))
elseif act == "del" then
print(easylua_manager.access_manager.del(args[2]))
elseif act == "show" then
for _, o in pairs(easylua_manager.access_manager.access_list) do
print("[EASYLUA] Have access:",o._name, _, o._ip)
end
end
easylua_manager.access_manager.file_update(false)
easylua_manager.access_manager.update_access()
end,nil,nil,FCVAR_USERINFO)
easylua_manager.access_manager.update_access()
hook.Add("OnEntityCreated","easylua_access_updater",function(ent)
if(ent:GetClass() == "player") then
easylua_manager.access_manager.update_access()
end
end) | gpl-2.0 |
ffxiphoenix/darkstar | scripts/zones/Metalworks/npcs/Abbudin.lua | 34 | 1045 | -----------------------------------
-- Area: Metalworks
-- NPC: Abbudin
-- Type: Standard Info NPC
-- @pos -56.338 2.777 -31.446 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x022E);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/items/warm_egg.lua | 35 | 1186 | -----------------------------------------
-- ID: 4602
-- Item: warm_egg
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 18
-- Magic 18
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4602);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 18);
target:addMod(MOD_MP, 18);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 18);
target:delMod(MOD_MP, 18);
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Cloister_of_Storms/bcnms/carbuncle_debacle.lua | 19 | 1480 | -----------------------------------
-- Area: Cloister of Storms
-- BCNM: Carbuncle Debacle
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Cloister_of_Storms/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0,0);
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:setVar("CarbuncleDebacleProgress",4);
end;
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Davoi/npcs/_45j.lua | 19 | 2049 | -----------------------------------
-- Area: Davoi
-- NPC: Screaming Pond
-- Used In Quest: Whence Blows the Wind
-- @pos -219 0.1 -101 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0035);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0035 and player:getVar("miniQuestForORB_CS") == 1) then
local c = player:getVar("countRedPoolForORB");
if (c == 0) then
player:setVar("countRedPoolForORB", c + 4);
player:delKeyItem(WHITE_ORB);
player:addKeyItem(PINK_ORB);
player:messageSpecial(KEYITEM_OBTAINED, PINK_ORB);
elseif (c == 1 or c == 2 or c == 8) then
player:setVar("countRedPoolForORB", c + 4);
player:delKeyItem(PINK_ORB);
player:addKeyItem(RED_ORB);
player:messageSpecial(KEYITEM_OBTAINED, RED_ORB);
elseif (c == 3 or c == 9 or c == 10) then
player:setVar("countRedPoolForORB", c + 4);
player:delKeyItem(RED_ORB);
player:addKeyItem(BLOOD_ORB);
player:messageSpecial(KEYITEM_OBTAINED, BLOOD_ORB);
elseif (c == 11) then
player:setVar("countRedPoolForORB", c + 4);
player:delKeyItem(BLOOD_ORB);
player:addKeyItem(CURSED_ORB);
player:messageSpecial(KEYITEM_OBTAINED, CURSED_ORB);
player:addStatusEffect(EFFECT_PLAGUE,0,0,900);
end
end
end; | gpl-3.0 |
Amnesy/petbuffs | PetBuffs/lib/AceAddon-3.0/AceAddon-3.0.lua | 17 | 26462 | --- **AceAddon-3.0** provides a template for creating addon objects.
-- It'll provide you with a set of callback functions that allow you to simplify the loading
-- process of your addon.\\
-- Callbacks provided are:\\
-- * **OnInitialize**, which is called directly after the addon is fully loaded.
-- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present.
-- * **OnDisable**, which is only called when your addon is manually being disabled.
-- @usage
-- -- A small (but complete) addon, that doesn't do anything,
-- -- but shows usage of the callbacks.
-- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
--
-- function MyAddon:OnInitialize()
-- -- do init tasks here, like loading the Saved Variables,
-- -- or setting up slash commands.
-- end
--
-- function MyAddon:OnEnable()
-- -- Do more initialization here, that really enables the use of your addon.
-- -- Register Events, Hook functions, Create Frames, Get information from
-- -- the game that wasn't available in OnInitialize
-- end
--
-- function MyAddon:OnDisable()
-- -- Unhook, Unregister Events, Hide frames that you created.
-- -- You would probably only use an OnDisable if you want to
-- -- build a "standby" mode, or be able to toggle modules on/off.
-- end
-- @class file
-- @name AceAddon-3.0.lua
-- @release $Id: AceAddon-3.0.lua 1084 2013-04-27 20:14:11Z nevcairiel $
local MAJOR, MINOR = "AceAddon-3.0", 12
local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceAddon then return end -- No Upgrade needed.
AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame
AceAddon.addons = AceAddon.addons or {} -- addons in general
AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon.
AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized
AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled
AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon
-- Lua APIs
local tinsert, tconcat, tremove = table.insert, table.concat, table.remove
local fmt, tostring = string.format, tostring
local select, pairs, next, type, unpack = select, pairs, next, type, unpack
local loadstring, assert, error = loadstring, assert, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub, IsLoggedIn, geterrorhandler
--[[
xpcall safecall implementation
]]
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err)
end
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ...
local method, ARGS
local function call() return method(ARGS) end
local function dispatch(func, ...)
method = func
if not method then return end
ARGS = ...
return xpcall(call, eh)
end
return dispatch
]]
local ARGS = {}
for i = 1, argCount do ARGS[i] = "arg"..i end
code = code:gsub("ARGS", tconcat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
Dispatchers[0] = function(func)
return xpcall(func, errorhandler)
end
local function safecall(func, ...)
-- we check to see if the func is passed is actually a function here and don't error when it isn't
-- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not
-- present execution should continue without hinderance
if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...)
end
end
-- local functions that will be implemented further down
local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype
-- used in the addon metatable
local function addontostring( self ) return self.name end
-- Check if the addon is queued for initialization
local function queuedForInitialization(addon)
for i = 1, #AceAddon.initializequeue do
if AceAddon.initializequeue[i] == addon then
return true
end
end
return false
end
--- Create a new AceAddon-3.0 addon.
-- Any libraries you specified will be embeded, and the addon will be scheduled for
-- its OnInitialize and OnEnable callbacks.
-- The final addon object, with all libraries embeded, will be returned.
-- @paramsig [object ,]name[, lib, ...]
-- @param object Table to use as a base for the addon (optional)
-- @param name Name of the addon object to create
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a simple addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0")
--
-- -- Create a Addon object based on the table of a frame
-- local MyFrame = CreateFrame("Frame")
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0")
function AceAddon:NewAddon(objectorname, ...)
local object,name
local i=1
if type(objectorname)=="table" then
object=objectorname
name=...
i=2
else
name=objectorname
end
if type(name)~="string" then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2)
end
if self.addons[name] then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2)
end
object = object or {}
object.name = name
local addonmeta = {}
local oldmeta = getmetatable(object)
if oldmeta then
for k, v in pairs(oldmeta) do addonmeta[k] = v end
end
addonmeta.__tostring = addontostring
setmetatable( object, addonmeta )
self.addons[name] = object
object.modules = {}
object.orderedModules = {}
object.defaultModuleLibraries = {}
Embed( object ) -- embed NewModule, GetModule methods
self:EmbedLibraries(object, select(i,...))
-- add to queue of addons to be initialized upon ADDON_LOADED
tinsert(self.initializequeue, object)
return object
end
--- Get the addon object by its name from the internal AceAddon registry.
-- Throws an error if the addon object cannot be found (except if silent is set).
-- @param name unique name of the addon object
-- @param silent if true, the addon is optional, silently return nil if its not found
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
function AceAddon:GetAddon(name, silent)
if not silent and not self.addons[name] then
error(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(tostring(name)), 2)
end
return self.addons[name]
end
-- - Embed a list of libraries into the specified addon.
-- This function will try to embed all of the listed libraries into the addon
-- and error if a single one fails.
--
-- **Note:** This function is for internal use by :NewAddon/:NewModule
-- @paramsig addon, [lib, ...]
-- @param addon addon object to embed the libs in
-- @param lib List of libraries to embed into the addon
function AceAddon:EmbedLibraries(addon, ...)
for i=1,select("#", ... ) do
local libname = select(i, ...)
self:EmbedLibrary(addon, libname, false, 4)
end
end
-- - Embed a library into the addon object.
-- This function will check if the specified library is registered with LibStub
-- and if it has a :Embed function to call. It'll error if any of those conditions
-- fails.
--
-- **Note:** This function is for internal use by :EmbedLibraries
-- @paramsig addon, libname[, silent[, offset]]
-- @param addon addon object to embed the library in
-- @param libname name of the library to embed
-- @param silent marks an embed to fail silently if the library doesn't exist (optional)
-- @param offset will push the error messages back to said offset, defaults to 2 (optional)
function AceAddon:EmbedLibrary(addon, libname, silent, offset)
local lib = LibStub:GetLibrary(libname, true)
if not lib and not silent then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(tostring(libname)), offset or 2)
elseif lib and type(lib.Embed) == "function" then
lib:Embed(addon)
tinsert(self.embeds[addon], libname)
return true
elseif lib then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(libname), offset or 2)
end
end
--- Return the specified module from an addon object.
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @name //addon//:GetModule
-- @paramsig name[, silent]
-- @param name unique name of the module
-- @param silent if true, the module is optional, silently return nil if its not found (optional)
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- -- Get the Module
-- MyModule = MyAddon:GetModule("MyModule")
function GetModule(self, name, silent)
if not self.modules[name] and not silent then
error(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(tostring(name)), 2)
end
return self.modules[name]
end
local function IsModuleTrue(self) return true end
--- Create a new module for the addon.
-- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\
-- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as
-- an addon object.
-- @name //addon//:NewModule
-- @paramsig name[, prototype|lib[, lib, ...]]
-- @param name unique name of the module
-- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a module with some embeded libraries
-- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0")
--
-- -- Create a module with a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0")
function NewModule(self, name, prototype, ...)
if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end
if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end
if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(name), 2) end
-- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well.
-- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is.
local module = AceAddon:NewAddon(fmt("%s_%s", self.name or tostring(self), name))
module.IsModule = IsModuleTrue
module:SetEnabledState(self.defaultModuleState)
module.moduleName = name
if type(prototype) == "string" then
AceAddon:EmbedLibraries(module, prototype, ...)
else
AceAddon:EmbedLibraries(module, ...)
end
AceAddon:EmbedLibraries(module, unpack(self.defaultModuleLibraries))
if not prototype or type(prototype) == "string" then
prototype = self.defaultModulePrototype or nil
end
if type(prototype) == "table" then
local mt = getmetatable(module)
mt.__index = prototype
setmetatable(module, mt) -- More of a Base class type feel.
end
safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy.
self.modules[name] = module
tinsert(self.orderedModules, module)
return module
end
--- Returns the real name of the addon or module, without any prefix.
-- @name //addon//:GetName
-- @paramsig
-- @usage
-- print(MyAddon:GetName())
-- -- prints "MyAddon"
function GetName(self)
return self.moduleName or self.name
end
--- Enables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback
-- and enabling all modules of the addon (unless explicitly disabled).\\
-- :Enable() also sets the internal `enableState` variable to true
-- @name //addon//:Enable
-- @paramsig
-- @usage
-- -- Enable MyModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
function Enable(self)
self:SetEnabledState(true)
-- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still
-- it'll be enabled after the init process
if not queuedForInitialization(self) then
return AceAddon:EnableAddon(self)
end
end
--- Disables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback
-- and disabling all modules of the addon.\\
-- :Disable() also sets the internal `enableState` variable to false
-- @name //addon//:Disable
-- @paramsig
-- @usage
-- -- Disable MyAddon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:Disable()
function Disable(self)
self:SetEnabledState(false)
return AceAddon:DisableAddon(self)
end
--- Enables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object.
-- @name //addon//:EnableModule
-- @paramsig name
-- @usage
-- -- Enable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
--
-- -- Enable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:EnableModule("MyModule")
function EnableModule(self, name)
local module = self:GetModule( name )
return module:Enable()
end
--- Disables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object.
-- @name //addon//:DisableModule
-- @paramsig name
-- @usage
-- -- Disable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Disable()
--
-- -- Disable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:DisableModule("MyModule")
function DisableModule(self, name)
local module = self:GetModule( name )
return module:Disable()
end
--- Set the default libraries to be mixed into all modules created by this object.
-- Note that you can only change the default module libraries before any module is created.
-- @name //addon//:SetDefaultModuleLibraries
-- @paramsig lib[, lib, ...]
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Configure default libraries for modules (all modules need AceEvent-3.0)
-- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0")
-- -- Create a module
-- MyModule = MyAddon:NewModule("MyModule")
function SetDefaultModuleLibraries(self, ...)
if next(self.modules) then
error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleLibraries = {...}
end
--- Set the default state in which new modules are being created.
-- Note that you can only change the default state before any module is created.
-- @name //addon//:SetDefaultModuleState
-- @paramsig state
-- @param state Default state for new modules, true for enabled, false for disabled
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Set the default state to "disabled"
-- MyAddon:SetDefaultModuleState(false)
-- -- Create a module and explicilty enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
function SetDefaultModuleState(self, state)
if next(self.modules) then
error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleState = state
end
--- Set the default prototype to use for new modules on creation.
-- Note that you can only change the default prototype before any module is created.
-- @name //addon//:SetDefaultModulePrototype
-- @paramsig prototype
-- @param prototype Default prototype for the new modules (table)
-- @usage
-- -- Define a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- -- Set the default prototype
-- MyAddon:SetDefaultModulePrototype(prototype)
-- -- Create a module and explicitly Enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
-- -- should print "OnEnable called!" now
-- @see NewModule
function SetDefaultModulePrototype(self, prototype)
if next(self.modules) then
error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2)
end
if type(prototype) ~= "table" then
error(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(type(prototype)), 2)
end
self.defaultModulePrototype = prototype
end
--- Set the state of an addon or module
-- This should only be called before any enabling actually happend, e.g. in/before OnInitialize.
-- @name //addon//:SetEnabledState
-- @paramsig state
-- @param state the state of an addon or module (enabled=true, disabled=false)
function SetEnabledState(self, state)
self.enabledState = state
end
--- Return an iterator of all modules associated to the addon.
-- @name //addon//:IterateModules
-- @paramsig
-- @usage
-- -- Enable all modules
-- for name, module in MyAddon:IterateModules() do
-- module:Enable()
-- end
local function IterateModules(self) return pairs(self.modules) end
-- Returns an iterator of all embeds in the addon
-- @name //addon//:IterateEmbeds
-- @paramsig
local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end
--- Query the enabledState of an addon.
-- @name //addon//:IsEnabled
-- @paramsig
-- @usage
-- if MyAddon:IsEnabled() then
-- MyAddon:Disable()
-- end
local function IsEnabled(self) return self.enabledState end
local mixins = {
NewModule = NewModule,
GetModule = GetModule,
Enable = Enable,
Disable = Disable,
EnableModule = EnableModule,
DisableModule = DisableModule,
IsEnabled = IsEnabled,
SetDefaultModuleLibraries = SetDefaultModuleLibraries,
SetDefaultModuleState = SetDefaultModuleState,
SetDefaultModulePrototype = SetDefaultModulePrototype,
SetEnabledState = SetEnabledState,
IterateModules = IterateModules,
IterateEmbeds = IterateEmbeds,
GetName = GetName,
}
local function IsModule(self) return false end
local pmixins = {
defaultModuleState = true,
enabledState = true,
IsModule = IsModule,
}
-- Embed( target )
-- target (object) - target object to embed aceaddon in
--
-- this is a local function specifically since it's meant to be only called internally
function Embed(target, skipPMixins)
for k, v in pairs(mixins) do
target[k] = v
end
if not skipPMixins then
for k, v in pairs(pmixins) do
target[k] = target[k] or v
end
end
end
-- - Initialize the addon after creation.
-- This function is only used internally during the ADDON_LOADED event
-- It will call the **OnInitialize** function on the addon object (if present),
-- and the **OnEmbedInitialize** function on all embeded libraries.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- @param addon addon object to intialize
function AceAddon:InitializeAddon(addon)
safecall(addon.OnInitialize, addon)
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedInitialize, lib, addon) end
end
-- we don't call InitializeAddon on modules specifically, this is handled
-- from the event handler and only done _once_
end
-- - Enable the addon after creation.
-- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED,
-- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons.
-- It will call the **OnEnable** function on the addon object (if present),
-- and the **OnEmbedEnable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Enable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:EnableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if self.statuses[addon.name] or not addon.enabledState then return false end
-- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable.
self.statuses[addon.name] = true
safecall(addon.OnEnable, addon)
-- make sure we're still enabled before continueing
if self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedEnable, lib, addon) end
end
-- enable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:EnableAddon(modules[i])
end
end
return self.statuses[addon.name] -- return true if we're disabled
end
-- - Disable the addon
-- Note: This function is only used internally.
-- It will call the **OnDisable** function on the addon object (if present),
-- and the **OnEmbedDisable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Disable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:DisableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if not self.statuses[addon.name] then return false end
-- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable.
self.statuses[addon.name] = false
safecall( addon.OnDisable, addon )
-- make sure we're still disabling...
if not self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedDisable, lib, addon) end
end
-- disable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:DisableAddon(modules[i])
end
end
return not self.statuses[addon.name] -- return true if we're disabled
end
--- Get an iterator over all registered addons.
-- @usage
-- -- Print a list of all installed AceAddon's
-- for name, addon in AceAddon:IterateAddons() do
-- print("Addon: " .. name)
-- end
function AceAddon:IterateAddons() return pairs(self.addons) end
--- Get an iterator over the internal status registry.
-- @usage
-- -- Print a list of all enabled addons
-- for name, status in AceAddon:IterateAddonStatus() do
-- if status then
-- print("EnabledAddon: " .. name)
-- end
-- end
function AceAddon:IterateAddonStatus() return pairs(self.statuses) end
-- Following Iterators are deprecated, and their addon specific versions should be used
-- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon)
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end
-- Event Handling
local function onEvent(this, event, arg1)
-- 2011-08-17 nevcairiel - ignore the load event of Blizzard_DebugTools, so a potential startup error isn't swallowed up
if (event == "ADDON_LOADED" and arg1 ~= "Blizzard_DebugTools") or event == "PLAYER_LOGIN" then
-- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration
while(#AceAddon.initializequeue > 0) do
local addon = tremove(AceAddon.initializequeue, 1)
-- this might be an issue with recursion - TODO: validate
if event == "ADDON_LOADED" then addon.baseName = arg1 end
AceAddon:InitializeAddon(addon)
tinsert(AceAddon.enablequeue, addon)
end
if IsLoggedIn() then
while(#AceAddon.enablequeue > 0) do
local addon = tremove(AceAddon.enablequeue, 1)
AceAddon:EnableAddon(addon)
end
end
end
end
AceAddon.frame:RegisterEvent("ADDON_LOADED")
AceAddon.frame:RegisterEvent("PLAYER_LOGIN")
AceAddon.frame:SetScript("OnEvent", onEvent)
-- upgrade embeded
for name, addon in pairs(AceAddon.addons) do
Embed(addon, true)
end
-- 2010-10-27 nevcairiel - add new "orderedModules" table
if oldminor and oldminor < 10 then
for name, addon in pairs(AceAddon.addons) do
addon.orderedModules = {}
for module_name, module in pairs(addon.modules) do
tinsert(addon.orderedModules, module)
end
end
end
| mit |
ffxiphoenix/darkstar | scripts/zones/Dynamis-Beaucedine/mobs/Adamantking_Effigy.lua | 12 | 3434 | -----------------------------------
-- Area: Dynamis Beaucedine
-- NPC: Adamantking Effigy
-- Map Position: http://images1.wikia.nocookie.net/__cb20090312005233/ffxi/images/thumb/b/b6/Bea.jpg/375px-Bea.jpg
-----------------------------------
package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Beaucedine/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = beaucedineQuadavList;
if (mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if (mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if ((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if (mobNBR <= 20) then
if (mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY)
local DynaMob = getDynaMob(target,mobNBR,3);
if (DynaMob ~= nil) then
-- Spawn Mob
SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob):setPos(X,Y,Z);
GetMobByID(DynaMob):setSpawn(X,Y,Z);
-- Spawn Pet for BST, DRG, and SMN
if (mobNBR == 9 or mobNBR == 14 or mobNBR == 15) then
SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob + 1):setPos(X,Y,Z);
GetMobByID(DynaMob + 1):setSpawn(X,Y,Z);
end
end
elseif (mobNBR > 20) then
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
local MJob = GetMobByID(mobNBR):getMainJob();
if (MJob == 9 or MJob == 14 or MJob == 15) then
-- Spawn Pet for BST, DRG, and SMN
SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR + 1):setPos(X,Y,Z);
GetMobByID(mobNBR + 1):setSpawn(X,Y,Z);
end
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
-- Time Bonus: 063 066
if (mobID == 17326892 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
elseif (mobID == 17326895 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
-- HP Bonus: 056 059 065 070 074 103
elseif (mobID == 17326885 or mobID == 17326888 or mobID == 17326894 or mobID == 17326899 or mobID == 17326903 or mobID == 17326932) then
killer:restoreHP(2000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- MP Bonus: 057 061 067 072 076
elseif (mobID == 17326886 or mobID == 17326890 or mobID == 17326896 or mobID == 17326901 or mobID == 17326905) then
killer:restoreMP(2000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/items/greedie.lua | 18 | 1317 | -----------------------------------------
-- ID: 4500
-- Item: greedie
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 1
-- Mind -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4500);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_MND, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_MND, -3);
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Tavnazian_Safehold/Zone.lua | 19 | 3150 | -----------------------------------
--
-- Zone: Tavnazian_Safehold (26)
--
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -5, -24, 18, 5, -20, 27);
zone:registerRegion(2, 104, -42, -88, 113, -38, -77);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(27.971,-14.068,43.735,66);
end
if (player:getCurrentMission(COP) == AN_INVITATION_WEST) then
if (player:getVar("PromathiaStatus") == 1) then
cs = 0x0065;
end
elseif (player:getCurrentMission(COP) == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 0) then
cs = 0x006B;
elseif (player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus") == 1) then
cs = 0x0072;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x)
if (player:getCurrentMission(COP) == AN_ETERNAL_MELODY and player:getVar("PromathiaStatus") == 2) then
player:startEvent(0x0069);
end
end,
[2] = function (x)
if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 0) then
player:startEvent(0x0070);
end
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0065) then
player:completeMission(COP,AN_INVITATION_WEST);
player:addMission(COP,THE_LOST_CITY);
player:setVar("PromathiaStatus",0);
elseif (csid == 0x0069) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,AN_ETERNAL_MELODY);
player:addMission(COP,ANCIENT_VOWS);
elseif (csid == 0x006B) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x0070) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x0072) then
player:setVar("PromathiaStatus",2);
end
end; | gpl-3.0 |
usstwxy/luarocks | src/luarocks/pack.lua | 20 | 7450 |
--- Module implementing the LuaRocks "pack" command.
-- Creates a rock, packing sources or binaries.
--module("luarocks.pack", package.seeall)
local pack = {}
package.loaded["luarocks.pack"] = pack
local unpack = unpack or table.unpack
local path = require("luarocks.path")
local repos = require("luarocks.repos")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local search = require("luarocks.search")
pack.help_summary = "Create a rock, packing sources or binaries."
pack.help_arguments = "{<rockspec>|<name> [<version>]}"
pack.help = [[
Argument may be a rockspec file, for creating a source rock,
or the name of an installed package, for creating a binary rock.
In the latter case, the app version may be given as a second
argument.
]]
--- Create a source rock.
-- Packages a rockspec and its required source files in a rock
-- file with the .src.rock extension, which can later be built and
-- installed with the "build" command.
-- @param rockspec_file string: An URL or pathname for a rockspec file.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
function pack.pack_source_rock(rockspec_file)
assert(type(rockspec_file) == "string")
local rockspec, err = fetch.load_rockspec(rockspec_file)
if err then
return nil, "Error loading rockspec: "..err
end
rockspec_file = rockspec.local_filename
local name_version = rockspec.name .. "-" .. rockspec.version
local rock_file = fs.absolute_name(name_version .. ".src.rock")
local source_file, source_dir = fetch.fetch_sources(rockspec, false)
if not source_file then
return nil, source_dir
end
local ok, err = fs.change_dir(source_dir)
if not ok then return nil, err end
fs.delete(rock_file)
fs.copy(rockspec_file, source_dir)
if not fs.zip(rock_file, dir.base_name(rockspec_file), dir.base_name(source_file)) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
return rock_file
end
local function copy_back_files(name, version, file_tree, deploy_dir, pack_dir)
local ok, err = fs.make_dir(pack_dir)
if not ok then return nil, err end
for file, sub in pairs(file_tree) do
local source = dir.path(deploy_dir, file)
local target = dir.path(pack_dir, file)
if type(sub) == "table" then
local ok, err = copy_back_files(name, version, sub, source, target)
if not ok then return nil, err end
else
local versioned = path.versioned_name(source, deploy_dir, name, version)
if fs.exists(versioned) then
fs.copy(versioned, target)
else
fs.copy(source, target)
end
end
end
return true
end
-- @param name string: Name of package to pack.
-- @param version string or nil: A version number may also be passed.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
local function do_pack_binary_rock(name, version)
assert(type(name) == "string")
assert(type(version) == "string" or not version)
local query = search.make_query(name, version)
query.exact_name = true
local results = {}
search.manifest_search(results, cfg.rocks_dir, query)
if not next(results) then
return nil, "'"..name.."' does not seem to be an installed rock."
end
local versions = results[name]
if not version then
local first = next(versions)
if next(versions, first) then
return nil, "Please specify which version of '"..name.."' to pack."
end
version = first
end
if not version:match("[^-]+%-%d+") then
return nil, "Expected version "..version.." in version-revision format."
end
local info = versions[version][1]
local root = path.root_dir(info.repo)
local prefix = path.install_dir(name, version, root)
if not fs.exists(prefix) then
return nil, "'"..name.." "..version.."' does not seem to be an installed rock."
end
local rock_manifest = manif.load_rock_manifest(name, version, root)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
local name_version = name .. "-" .. version
local rock_file = fs.absolute_name(name_version .. "."..cfg.arch..".rock")
local temp_dir = fs.make_temp_dir("pack")
fs.copy_contents(prefix, temp_dir)
local is_binary = false
if rock_manifest.lib then
local ok, err = copy_back_files(name, version, rock_manifest.lib, path.deploy_lib_dir(root), dir.path(temp_dir, "lib"))
if not ok then return nil, "Failed copying back files: " .. err end
is_binary = true
end
if rock_manifest.lua then
local ok, err = copy_back_files(name, version, rock_manifest.lua, path.deploy_lua_dir(root), dir.path(temp_dir, "lua"))
if not ok then return nil, "Failed copying back files: " .. err end
end
local ok, err = fs.change_dir(temp_dir)
if not ok then return nil, err end
if not is_binary and not repos.has_binaries(name, version) then
rock_file = rock_file:gsub("%."..cfg.arch:gsub("%-","%%-").."%.", ".all.")
end
fs.delete(rock_file)
if not fs.zip(rock_file, unpack(fs.list_dir())) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
fs.delete(temp_dir)
return rock_file
end
function pack.pack_binary_rock(name, version, cmd, ...)
-- The --pack-binary-rock option for "luarocks build" basically performs
-- "luarocks build" on a temporary tree and then "luarocks pack". The
-- alternative would require refactoring parts of luarocks.build and
-- luarocks.pack, which would save a few file operations: the idea would be
-- to shave off the final deploy steps from the build phase and the initial
-- collect steps from the pack phase.
local temp_dir, err = fs.make_temp_dir("luarocks-build-pack-"..dir.base_name(name))
if not temp_dir then
return nil, "Failed creating temporary directory: "..err
end
util.schedule_function(fs.delete, temp_dir)
path.use_tree(temp_dir)
local ok, err = cmd(...)
if not ok then
return nil, err
end
local rname, rversion = path.parse_name(name)
if not rname then
rname, rversion = name, version
end
return do_pack_binary_rock(rname, rversion)
end
--- Driver function for the "pack" command.
-- @param arg string: may be a rockspec file, for creating a source rock,
-- or the name of an installed package, for creating a binary rock.
-- @param version string or nil: if the name of a package is given, a
-- version may also be passed.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
function pack.run(...)
local flags, arg, version = util.parse_flags(...)
assert(type(version) == "string" or not version)
if type(arg) ~= "string" then
return nil, "Argument missing. "..util.see_help("pack")
end
local file, err
if arg:match(".*%.rockspec") then
file, err = pack.pack_source_rock(arg)
else
file, err = do_pack_binary_rock(arg, version)
end
if err then
return nil, err
else
util.printout("Packed: "..file)
return true
end
end
return pack
| mit |
ffxiphoenix/darkstar | scripts/globals/spells/bluemagic/wild_oats.lua | 18 | 1960 | -----------------------------------------
-- Spell: Wild Oats
-- Additional effect: Vitality Down. Duration of effect varies on TP
-- Spell cost: 9 MP
-- Monster Type: Plantoids
-- Spell Type: Physical (Piercing)
-- Blue Magic Points: 3
-- Stat Bonus: CHR+1, HP+10
-- Level: 4
-- Casting Time: 0.5 seconds
-- Recast Time: 7.25 seconds
-- Skillchain Element(s): Light (can open Compression, Reverberation, or Distortion; can close Transfixion)
-- Combos: Beast Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_DURATION;
params.dmgtype = DMGTYPE_PIERCE;
params.scattr = SC_TRANSFIXION;
params.numhits = 1;
params.multiplier = 1.84;
params.tp150 = 1.84;
params.tp300 = 1.84;
params.azuretp = 1.84;
params.duppercap = 11;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.3;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
if (target:hasStatusEffect(EFFECT_VIT_DOWN)) then
spell:setMsg(75); -- no effect
else
target:addStatusEffect(EFFECT_VIT_DOWN,15,0,20);
end
return damage;
end; | gpl-3.0 |
elixboyBW/elixboySPM | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
RodneyMcKay/x_hero_siege | game/scripts/vscripts/libraries/playertables.lua | 1 | 13945 | PLAYERTABLES_VERSION = "0.90"
--[[
PlayerTables: Player-specific shared state/nettable Library by BMD
PlayerTables sets up a table that is shared between server (lua) and client (javascript) between specific (but changeable) clients.
It is very similar in concept to nettables, but is built on being player-specific state (not sent to all players).
Like nettables, PlayerTable state adjustments are mirrored to clients (that are currently subscribed).
If players disconnect and then reconnect, PlayerTables automatically transmits their subscribed table states to them when they connect.
PlayerTables only support sending numbers, strings, and tables of numbers/strings/tables to clients.
Installation
-"require" this file inside your code in order to gain access to the PlayerTables global table.
-Ensure that you have the playertables/playertables_base.js in your panorama content scripts folder.
-Ensure that playertables/playertables_base.js script is included in your custom_ui_manifest.xml with
<scripts>
<include src="file://{resources}/scripts/playertables/playertables_base.js" />
</scripts>
Library Usage
-Lua
-void PlayerTables:CreateTable(tableName, tableContents, pids)
Creates a new PlayerTable with the given name, default table contents, and automatically sets up a subscription
for all playerIDs in the "pids" object.
-void PlayerTables:DeleteTable(tableName)
Deletes a table by the given name, alerting any subscribed clients.
-bool PlayerTables:TableExists(tableName)
Returns whether a table currently exists with the given name
-void PlayerTables:SetPlayerSubscriptions(tableName, pids)
Clear and reset all player subscriptions based on the "pids" object.
-void PlayerTables:AddPlayerSubscription(tableName, pid)
Adds a subscription for the given player ID.
-void PlayerTables:RemovePlayerSubscription(tableName, pid)
Removes a subscription for the given player ID.
-<> PlayerTables:GetTableValue(tableName, key)
Returns the current value for this PlayerTable for the given "key", or nil if the key doesn't exist.
-<> PlayerTables:GetAllTableValues(tableName)
Returns the current keys and values for the given table.
-void PlayerTables:DeleteTableValue(tableName, key)
Delete a key from a playertable.
-void PlayerTables:DeleteTableValues(tableName, keys)
Delete the keys from a playertable given in the keys object.
-void PlayerTables:SetTableValue(tableName, key, value)
Set a value for the given key.
-void PlayerTables:SetTableValues(tableName, changes)
Set a all of the given key-value pairs in the changes object.
-Javascript: include the javascript API with "var PlayerTables = GameUI.CustomUIConfig().PlayerTables" at the top of your file.
-void PlayerTables.GetAllTableValues(tableName)
Returns the current keys and values of all keys within the table "tableName".
Returns null if no table exists with that name.
-void PlayerTables.GetTableValue(tableName, keyName)
Returns the current value for the key given by "keyName" if it exists on the table given by "tableName".
Returns null if no table exists, or undefined if the key does not exist.
-int PlayerTables.SubscribeNetTableListener(tableName, callback)
Sets up a callback for when this playertable is changed. The callback is of the form:
function(tableName, changesObject, deletionsObject).
changesObject contains the key-value pairs that were changed
deletionsObject contains the keys that were deleted.
If changesObject and deletionsObject are both null, then the entire table was deleted.
Returns an integer value representing this subscription.
-void PlayerTables.UnsubscribeNetTableListener(callbackID)
Remvoes the existing subscription as given by the callbackID (the integer returned from SubscribeNetTableListener)
Examples:
--Create a Table and set a few values.
PlayerTables:CreateTable("new_table", {initial="initial value"}, {0})
PlayerTables:SetTableValue("new_table", "count", 0)
PlayerTables:SetTableValues("new_table", {val1=1, val2=2})
--Change player subscriptions
PlayerTables:RemovePlayerSubscription("new_table", 0)
PlayerTables:SetPlayerSubscriptions("new_table", {[1]=true,[3]=true}) -- the pids object can be a map or array type table
--Retrieve values on the client
var PlayerTables = GameUI.CustomUIConfig().PlayerTables;
$.Msg(PlayerTables.GetTableVaue("new_table", "count"));
--Subscribe to changes on the client
var PlayerTables = GameUI.CustomUIConfig().PlayerTables;
PlayerTables.SubscribeNetTableListener("new_table", function(tableName, changes, deletions){
$.Msg(tableName + " changed: " + changes + " -- " + deletions);
});
]]
if not PlayerTables then
PlayerTables = class({})
end
function PlayerTables:start()
self.tables = {}
self.subscriptions = {}
CustomGameEventManager:RegisterListener("PlayerTables_Connected", Dynamic_Wrap(PlayerTables, "PlayerTables_Connected"))
end
function PlayerTables:equals(o1, o2, ignore_mt)
if o1 == o2 then return true end
local o1Type = type(o1)
local o2Type = type(o2)
if o1Type ~= o2Type then return false end
if o1Type ~= 'table' then return false end
if not ignore_mt then
local mt1 = getmetatable(o1)
if mt1 and mt1.__eq then
--compare using built in method
return o1 == o2
end
end
local keySet = {}
for key1, value1 in pairs(o1) do
local value2 = o2[key1]
if value2 == nil or self:equals(value1, value2, ignore_mt) == false then
return false
end
keySet[key1] = true
end
for key2, _ in pairs(o2) do
if not keySet[key2] then return false end
end
return true
end
function PlayerTables:copy(obj, seen)
if type(obj) ~= 'table' then return obj end
if seen and seen[obj] then return seen[obj] end
local s = seen or {}
local res = setmetatable({}, getmetatable(obj))
s[obj] = res
for k, v in pairs(obj) do res[self:copy(k, s)] = self:copy(v, s) end
return res
end
function PlayerTables:PlayerTables_Connected(args)
--print('PlayerTables_Connected')
--PrintTable(args)
local pid = args.PlayerID
if not pid then
return
end
local player = PlayerResource:GetPlayer(pid)
--print('player: ', player)
for k,v in pairs(PlayerTables.subscriptions) do
if v[pid] then
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_fu", {name=k, table=PlayerTables.tables[k]} )
end
end
end
end
function PlayerTables:CreateTable(tableName, tableContents, pids)
tableContents = tableContents or {}
pids = pids or {}
if pids == true then
pids = {}
for i=0,DOTA_MAX_TEAM_PLAYERS-1 do
pids[#pids+1] = i
end
end
if self.tables[tableName] then
print("[playertables.lua] Warning: player table '" .. tableName .. "' already exists. Overriding.")
end
self.tables[tableName] = tableContents
self.subscriptions[tableName] = {}
for k,v in pairs(pids) do
local pid = k
if type(v) == "number" then
pid = v
end
if pid >= 0 and pid < DOTA_MAX_TEAM_PLAYERS then
self.subscriptions[tableName][pid] = true
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_fu", {name=tableName, table=tableContents} )
end
else
print("[playertables.lua] Warning: Pid value '" .. pid .. "' is not an integer between [0," .. DOTA_MAX_TEAM_PLAYERS .. "]. Ignoring.")
end
end
end
function PlayerTables:DeleteTable(tableName)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local pids = self.subscriptions[tableName]
for k,v in pairs(pids) do
local player = PlayerResource:GetPlayer(k)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_fu", {name=tableName, table=nil} )
end
end
self.tables[tableName] = nil
self.subscriptions[tableName] = nil
end
function PlayerTables:TableExists(tableName)
return self.tables[tableName] ~= nil
end
function PlayerTables:SetPlayerSubscriptions(tableName, pids)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local oldPids = self.subscriptions[tableName]
self.subscriptions[tableName] = {}
for k,v in pairs(pids) do
local pid = k
if type(v) == "number" then
pid = v
end
if pid >= 0 and pid < DOTA_MAX_TEAM_PLAYERS then
self.subscriptions[tableName][pid] = true
local player = PlayerResource:GetPlayer(pid)
if player and oldPids[pid] == nil then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_fu", {name=tableName, table=table} )
end
else
print("[playertables.lua] Warning: Pid value '" .. pid .. "' is not an integer between [0," .. DOTA_MAX_TEAM_PLAYERS .. "]. Ignoring.")
end
end
end
function PlayerTables:AddPlayerSubscription(tableName, pid)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local oldPids = self.subscriptions[tableName]
if not oldPids[pid] then
if pid >= 0 and pid < DOTA_MAX_TEAM_PLAYERS then
self.subscriptions[tableName][pid] = true
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_fu", {name=tableName, table=table} )
end
else
print("[playertables.lua] Warning: Pid value '" .. v .. "' is not an integer between [0," .. DOTA_MAX_TEAM_PLAYERS .. "]. Ignoring.")
end
end
end
function PlayerTables:RemovePlayerSubscription(tableName, pid)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local oldPids = self.subscriptions[tableName]
oldPids[pid] = nil
end
function PlayerTables:GetTableValue(tableName, key)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local ret = self.tables[tableName][key]
if type(ret) == "table" then
return self:copy(ret)
end
return ret
end
function PlayerTables:GetAllTableValues(tableName)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local ret = self.tables[tableName]
if type(ret) == "table" then
return self:copy(ret)
end
return ret
end
function PlayerTables:DeleteTableKey(tableName, key)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local pids = self.subscriptions[tableName]
if table[key] ~= nil then
table[key] = nil
for pid,v in pairs(pids) do
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_kd", {name=tableName, keys={[key]=true}} )
end
end
end
end
function PlayerTables:DeleteTableKeys(tableName, keys)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local pids = self.subscriptions[tableName]
local deletions = {}
local notempty = false
for k,v in pairs(keys) do
if type(k) == "string" then
if table[k] ~= nil then
deletions[k] = true
table[k] = nil
notempty = true
end
elseif type(v) == "string" then
if table[v] ~= nil then
deletions[v] = true
table[v] = nil
notempty = true
end
end
end
if notempty then
for pid,v in pairs(pids) do
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_kd", {name=tableName, keys=deletions} )
end
end
end
end
function PlayerTables:SetTableValue(tableName, key, value)
if value == nil then
self:DeleteTableKey(tableName, key)
return
end
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local pids = self.subscriptions[tableName]
if not self:equals(table[key], value) then
table[key] = value
for pid,v in pairs(pids) do
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_uk", {name=tableName, changes={[key]=value}} )
end
end
end
end
function PlayerTables:SetTableValues(tableName, changes)
if not self.tables[tableName] then
print("[playertables.lua] Warning: Table '" .. tableName .. "' does not exist.")
return
end
local table = self.tables[tableName]
local pids = self.subscriptions[tableName]
for k,v in pairs(changes) do
if self:equals(table[k], v) then
changes[k] = nil
else
table[k] = v
end
end
local notempty, _ = next(changes, nil)
if notempty then
for pid,v in pairs(pids) do
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "pt_uk", {name=tableName, changes=changes} )
end
end
end
end
if not PlayerTables.tables then PlayerTables:start() end | gpl-2.0 |
ffxiphoenix/darkstar | scripts/zones/La_Vaule_[S]/mobs/Lobison.lua | 19 | 1540 | -----------------------------------
-- Area: La Vaule (S)
-- NPC: Lobison
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("transformTime", os.time())
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local spawnTime = mob:getLocalVar("transformTime");
local roamChance = math.random(1,100);
local roamMoonPhase = VanadielMoonPhase();
if (roamChance > 100-roamMoonPhase) then
if (mob:AnimationSub() == 0 and os.time() - transformTime > 300) then
mob:AnimationSub(1);
mob:setLocalVar("transformTime", os.time());
elseif (mob:AnimationSub() == 1 and os.time() - transformTime > 300) then
mob:AnimationSub(0);
mob:setLocalVar("transformTime", os.time());
end
end
end;
-----------------------------------
-- onMobEngaged
-- Change forms every 60 seconds
-----------------------------------
function onMobEngaged(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local chance = math.random(1,100);
local moonPhase = VanadielMoonPhase();
if (chance > 100-moonPhase) then
if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(1);
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Waughroon_Shrine/bcnms/on_my_way.lua | 19 | 1883 | -----------------------------------
-- Area: Waughroon Shrine
-- Name: Mission Rank 7-2 (Bastok)
-- @pos -345 104 -260 144
-----------------------------------
package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Waughroon_Shrine/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompletedMission(BASTOK,ON_MY_WAY)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
if ((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 2)) then
player:addKeyItem(LETTER_FROM_WEREI);
player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_WEREI);
player:setVar("MissionStatus",3);
end
end
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Palborough_Mines/npcs/_3z8.lua | 17 | 1532 | -----------------------------------
-- Area: Palborough Mines
-- NPC: Refiner Lever
-- Involved In Mission: Journey Abroad
-- @zone 143
-- @pos 180 -32 167
-----------------------------------
package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Palborough_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("refiner_input") > 0) then
player:startEvent(0x0011,1,1,1,1,1,1,1,1); -- machine is working, you hear the sound of metal hitting metal down below.
refiner_output = player:getVar("refiner_output");
player:setVar("refiner_output",refiner_output + player:getVar("refiner_input"));
player:setVar("refiner_input",0)
else
player:startEvent(0x0011); -- machine is working, but you cannot discern its purpose.
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/AlTaieu/npcs/qm3.lua | 14 | 1611 | -----------------------------------
-- Area: Al'Taieu
-- NPC: ??? (Jailer of Prudence Spawn)
-- Allows players to spawn the Jailer of Prudence by trading the Third Virtue, Deed of Sensibility, and High-Quality Hpemde Organ to a ???.
-- @pos , 706 -1 22
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade the Third Virtue, Deed of Sensibility, and High-Quality Hpemde Organ
--[[if (GetMobAction(16912846) == 0 and GetMobAction(16912847) == 0 and trade:hasItemQty(1856,1) and trade:hasItemQty(1870,1) and
trade:hasItemQty(1871,1) and trade:getItemCount() == 3) then
player:tradeComplete();
SpawnMob(16912846,900):updateClaim(player);-- Spawn Jailer of Prudence 1
SpawnMob(16912847,900):updateClaim(player);-- Spawn Jailer of Prudence 2
end]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
end; | gpl-3.0 |
AfuSensi/Mr.Green-MTA-Resources | resources/[gameplay]/chatbox_ads/ads_s.lua | 4 | 2828 | adMessages = { }
function loadResourceSettings()
intervalTime = tonumber(get("intervalTime"))*60000
prefix = tostring(get("prefix"))
end
addEventHandler("onResourceStart", resourceRoot, loadResourceSettings)
setTimer( loadResourceSettings, 30000, 0 )
addCommandHandler( "chatboxads", function(p) if hasObjectPermissionTo( p, "function.banPlayer" , false ) then triggerClientEvent( p, "editChatboxAds", resourceRoot,adMessages ) end end )
function loadAds()
local theXML = fileExists"ads.xml" and xmlLoadFile("ads.xml") or xmlCreateFile("ads.xml", "ads")
local childTable = xmlNodeGetChildren( theXML )
if #childTable == 0 then xmlUnloadFile( theXML ) outputDebugString("No ads in ads.xml") return end
for _,n in pairs(childTable) do
local theText = tostring( xmlNodeGetValue(n) )
table.insert(adMessages,theText)
end
outputDebugString(tostring(#childTable).." ads running. /chatboxads to manage them.")
xmlUnloadFile( theXML )
end
addEventHandler("onResourceStart",resourceRoot,loadAds)
function outputAd()
setTimer(outputAd,intervalTime,1)
if #adMessages == 0 then return end
local theMSG = adMessages[1]
table.remove(adMessages,1) -- Remove from table
table.insert(adMessages,theMSG) -- add to the back of the table
if #theMSG+#prefix > 127 then -- if output is longer then 127 characters(outputChatBox limit)
local stringTable = splitStringforChatBox(theMSG)
local outputAmount = 0
for _,s in ipairs(stringTable) do
outputAmount = outputAmount+1
if outputAmount <= 1 then
outputChatBox(prefix.." "..s,root,0,255,0,true)
else
outputChatBox(s,root,0,255,0,true)
end
end
else
outputChatBox(prefix.." "..theMSG,root,0,255,0,true)
end
end
setTimer(outputAd,10000,1)
function splitStringforChatBox(str)
local max_line_length = 127-#prefix
local lines = {}
local line
str:gsub('(%s*)(%S+)',
function(spc, word)
if not line or #line + #spc + #word > max_line_length then
table.insert(lines, line)
line = word
else
line = line..spc..word
end
end
)
table.insert(lines, line)
return lines
end
addEvent("clientSendNewAds",true)
function saveAdsXML(tbl)
local savetheXML = xmlLoadFile( "ads.xml" )
if not savetheXML then
savetheXML = xmlCreateFile( "ads.xml", "ads" )
end
local allNodes = xmlNodeGetChildren( savetheXML )
if #allNodes > 0 then
for d,u in pairs(allNodes) do -- remove all nodes
xmlDestroyNode( u )
end
end
for f,u in ipairs(tbl) do -- add all new nodes
local child = xmlCreateChild( savetheXML, "ad" )
xmlNodeSetValue( child, tostring(u) )
end
xmlSaveFile( savetheXML )
xmlUnloadFile( savetheXML )
outputDebugString("New ads saved by "..getPlayerName(client))
adMessages = tbl
end
addEventHandler("clientSendNewAds",root,saveAdsXML) | mit |
3scale/apicast-xc | xc/storage_keys.lua | 1 | 5055 | -- This module defines the interface of XC with Redis.
-- Specifically, it defines the format of all the keys that contain cached
-- authorizations and reports, and also, the format of the keys used in the
-- pubsub mechanism.
-- If the flusher used changes the format of the storage keys that it needs to
-- work properly, this is the only module that should require changes.
local _M = { AUTH_REQUESTS_CHANNEL = 'xc_channel_auth_requests',
SET_REPORT_KEYS = 'report_keys' }
local AUTH_RESPONSES_CHANNEL_PREFIX = 'xc_channel_auth_response:'
local REPORT_CREDS_IN_KEY = { 'app_id',
'user_key',
'access_token',
'user_id',
'app_key' }
-- Escapes ':' and ','.
local function escape(string)
return string:gsub(':', '\\:'):gsub(',', '\\,')
end
local function sort_table(t)
local res = {}
for elem in pairs(t) do table.insert(res, elem) end
table.sort(res)
return res
end
local function encode(credentials)
local res = {}
for i, cred in ipairs(sort_table(credentials)) do
res[i] = escape(cred) .. ':' .. escape(credentials[cred])
end
return table.concat(res, ',')
end
local function filter_creds_for_report_key(creds)
local res = {}
for _, cred in pairs(REPORT_CREDS_IN_KEY) do
res[cred] = creds[cred]
end
return res
end
local function get_key(key_type, service_id, credentials)
return key_type .. ',' ..
'service_id:' .. escape(service_id) .. ',' ..
encode(credentials)
end
-- Returns an auth key for a { service_id, credentials } pair.
-- Format of the key:
-- auth,service_id:<service_id>,<credentials> where:
-- <service_id>: service ID.
-- <credentials>: credentials needed for authentication separated by ','.
-- For example: app_id:my_app_id,user_key:my_user_key.
-- The credentials appear sorted, to avoid creating 2
-- different keys for the same report/auth.
-- ':' and ',' in the values are escaped.
--
-- Params:
-- service_id: String. Service ID.
-- credentials: Table. credentials needed to authenticate an app.
function _M.get_auth_key(service_id, credentials)
return get_key('auth', service_id, credentials)
end
-- Returns a report key for a { service_id, credentials } pair.
-- Format of the key:
-- report,service_id:<service_id>,<credentials> where:
-- <service_id>: service ID.
-- <credentials>: credentials needed for authentication separated by ','.
-- For example: app_id:my_app_id,user_key:my_user_key.
-- The credentials appear sorted, to avoid creating 2
-- different keys for the same report/auth.
-- ':' and ',' in the values are escaped.
--
-- There are some credentials that are needed for authenticating and not for
-- reporting. For example, a referrer.
-- If all the credentials are equal, but the referrer is different, the auth
-- status might change, and that means we need to store them in 2 different
-- keys. However, for reporting, we do not care about the referrer, because
-- the app is still the same. That's why the referrer is not included in
-- 'report' keys. The credentials that can be used for reporting are: 'app_id',
-- 'user_key', 'access_token', 'user_id', 'app_key'.
--
-- Params:
-- service_id: String. Service ID.
-- credentials: Table. credentials needed to authenticate an app.
function _M.get_report_key(service_id, credentials)
return get_key('report', service_id, filter_creds_for_report_key(credentials))
end
-- Returns the message that needs to be published in the pubsub mechanism to
-- ask for an authorization.
-- Format of the message:
-- service_id:<service_id>,<credentials>,metric:<metric> where:
-- <service_id>: service ID.
-- <credentials>: credentials needed for authentication separated by ','.
-- For example: app_id:my_app_id,user_key:my_user_key.
-- The credentials appear sorted.
-- <metric>: metric name.
-- ':' and ',' in the values are escaped.
--
-- Params:
-- service_id: String. Service ID.
-- credentials: Table. credentials needed to authenticate an app.
-- metric: String. Metric name.
function _M.get_pubsub_req_msg(service_id, credentials, metric)
return 'service_id:' .. escape(service_id) .. ',' ..
encode(credentials) .. ',' ..
'metric:' .. escape(metric)
end
-- Returns the pubsub channel to which the client needs to be subscribed after
-- asking for an authorization to receive the response.
-- The format is the same as the message that needs to be published prefixed
-- by 'xc_channel_auth_response:'.
--
-- Params:
-- service_id: String. Service ID.
-- credentials: Table. credentials needed to authenticate an app.
-- metric: String. Metric name.
function _M.get_pubsub_auths_resp_channel(service_id, credentials, metric)
return AUTH_RESPONSES_CHANNEL_PREFIX ..
_M.get_pubsub_req_msg(service_id, credentials, metric)
end
return _M
| apache-2.0 |
DrayChou/telegram-bot | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
PouriaDev/Signal-New | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-3.0 |
atilaneves/reggae-lua | JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| bsd-3-clause |
elixboyBW/elixboySPM | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
kuoruan/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx6.lua | 78 | 1115 | #!/usr/bin/lua
local json = require "cjson"
local function interpret_suffix(rate)
local value = string.sub(rate, 1, -2)
local suffix = string.sub(rate, -1)
if suffix == "K" then return tonumber(value) * 10^3 end
if suffix == "M" then return tonumber(value) * 10^6 end
if suffix == "G" then return tonumber(value) * 10^9 end
return rate
end
local function scrape()
local status = json.decode(get_contents("/var/run/bmx6/json/status")).status
local labels = {
version = status.version,
id = status.name,
address = status.primaryIp
}
metric("bmx6_status", "gauge", labels, 1)
local links = json.decode(get_contents("/var/run/bmx6/json/links")).links
local metric_bmx6_rxRate = metric("bmx6_link_rxRate","gauge")
local metric_bmx6_txRate = metric("bmx6_link_txRate","gauge")
for _, link in pairs(links) do
local labels = {
source = status.name,
target = link.name,
dev = link.viaDev
}
metric_bmx6_rxRate(labels, interpret_suffix(link.rxRate))
metric_bmx6_txRate(labels, interpret_suffix(link.txRate))
end
end
return { scrape = scrape }
| gpl-2.0 |
dail8859/ScintilluaPlusPlus | ext/scintillua/lexers/ruby.lua | 3 | 5294 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Ruby LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'ruby'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local line_comment = '#' * l.nonnewline_esc^0
local block_comment = l.starts_line('=begin') * (l.any - l.newline * '=end')^0 *
(l.newline * '=end')^-1
local comment = token(l.COMMENT, block_comment + line_comment)
local delimiter_matches = {['('] = ')', ['['] = ']', ['{'] = '}'}
local literal_delimitted = P(function(input, index)
local delimiter = input:sub(index, index)
if not delimiter:find('[%w\r\n\f\t ]') then -- only non alpha-numerics
local match_pos, patt
if delimiter_matches[delimiter] then
-- Handle nested delimiter/matches in strings.
local s, e = delimiter, delimiter_matches[delimiter]
patt = l.delimited_range(s..e, false, false, true)
else
patt = l.delimited_range(delimiter)
end
match_pos = lpeg.match(patt, input, index)
return match_pos or #input + 1
end
end)
-- Strings.
local cmd_str = l.delimited_range('`')
local lit_cmd = '%x' * literal_delimitted
local lit_array = '%w' * literal_delimitted
local sq_str = l.delimited_range("'")
local dq_str = l.delimited_range('"')
local lit_str = '%' * S('qQ')^-1 * literal_delimitted
local heredoc = '<<' * P(function(input, index)
local s, e, indented, _, delimiter =
input:find('(%-?)(["`]?)([%a_][%w_]*)%2[\n\r\f;]+', index)
if s == index and delimiter then
local end_heredoc = (#indented > 0 and '[\n\r\f]+ *' or '[\n\r\f]+')
local _, e = input:find(end_heredoc..delimiter, e)
return e and e + 1 or #input + 1
end
end)
-- TODO: regex_str fails with `obj.method /patt/` syntax.
local regex_str = #P('/') * l.last_char_includes('!%^&*([{-=+|:;,?<>~') *
l.delimited_range('/', true, false) * S('iomx')^0
local lit_regex = '%r' * literal_delimitted * S('iomx')^0
local string = token(l.STRING, (sq_str + dq_str + lit_str + heredoc + cmd_str +
lit_cmd + lit_array) * S('f')^-1) +
token(l.REGEX, regex_str + lit_regex)
local word_char = l.alnum + S('_!?')
-- Numbers.
local dec = l.digit^1 * ('_' * l.digit^1)^0 * S('ri')^-1
local bin = '0b' * S('01')^1 * ('_' * S('01')^1)^0
local integer = S('+-')^-1 * (bin + l.hex_num + l.oct_num + dec)
-- TODO: meta, control, etc. for numeric_literal.
local numeric_literal = '?' * (l.any - l.space) * -word_char
local number = token(l.NUMBER, l.float * S('ri')^-1 + integer + numeric_literal)
-- Keywords.
local keyword = token(l.KEYWORD, word_match({
'BEGIN', 'END', 'alias', 'and', 'begin', 'break', 'case', 'class', 'def',
'defined?', 'do', 'else', 'elsif', 'end', 'ensure', 'false', 'for', 'if',
'in', 'module', 'next', 'nil', 'not', 'or', 'redo', 'rescue', 'retry',
'return', 'self', 'super', 'then', 'true', 'undef', 'unless', 'until', 'when',
'while', 'yield', '__FILE__', '__LINE__'
}, '?!'))
-- Functions.
local func = token(l.FUNCTION, word_match({
'at_exit', 'autoload', 'binding', 'caller', 'catch', 'chop', 'chop!', 'chomp',
'chomp!', 'eval', 'exec', 'exit', 'exit!', 'fail', 'fork', 'format', 'gets',
'global_variables', 'gsub', 'gsub!', 'iterator?', 'lambda', 'load',
'local_variables', 'loop', 'open', 'p', 'print', 'printf', 'proc', 'putc',
'puts', 'raise', 'rand', 'readline', 'readlines', 'require', 'select',
'sleep', 'split', 'sprintf', 'srand', 'sub', 'sub!', 'syscall', 'system',
'test', 'trace_var', 'trap', 'untrace_var'
}, '?!')) * -S('.:|')
-- Identifiers.
local word = (l.alpha + '_') * word_char^0
local identifier = token(l.IDENTIFIER, word)
-- Variables.
local global_var = '$' * (word + S('!@L+`\'=~/\\,.;<>_*"$?:') + l.digit + '-' *
S('0FadiIKlpvw'))
local class_var = '@@' * word
local inst_var = '@' * word
local variable = token(l.VARIABLE, global_var + class_var + inst_var)
-- Symbols.
local symbol = token('symbol', ':' * P(function(input, index)
if input:sub(index - 2, index - 2) ~= ':' then return index end
end) * (word_char^1 + sq_str + dq_str))
-- Operators.
local operator = token(l.OPERATOR, S('!%^&*()[]{}-=+/|:;.,?<>~'))
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'function', func},
{'identifier', identifier},
{'comment', comment},
{'string', string},
{'number', number},
{'variable', variable},
{'symbol', symbol},
{'operator', operator},
}
M._tokenstyles = {
symbol = l.STYLE_CONSTANT
}
local function disambiguate(text, pos, line, s)
return line:sub(1, s - 1):match('^%s*$') and
not text:sub(1, pos - 1):match('\\[ \t]*\r?\n$') and 1 or 0
end
M._foldsymbols = {
_patterns = {'%l+', '[%(%)%[%]{}]', '=begin', '=end', '#'},
[l.KEYWORD] = {
begin = 1, class = 1, def = 1, ['do'] = 1, ['for'] = 1, ['module'] = 1,
case = 1,
['if'] = disambiguate, ['while'] = disambiguate,
['unless'] = disambiguate, ['until'] = disambiguate,
['end'] = -1
},
[l.OPERATOR] = {
['('] = 1, [')'] = -1, ['['] = 1, [']'] = -1, ['{'] = 1, ['}'] = -1
},
[l.COMMENT] = {
['=begin'] = 1, ['=end'] = -1, ['#'] = l.fold_line_comments('#')
}
}
return M
| gpl-2.0 |
ffxiphoenix/darkstar | scripts/zones/Castle_Oztroja/npcs/_47f.lua | 17 | 1240 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47f (Handle)
-- Notes: Opens door _471
-- @pos -182 -15 -19 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- To be implemented (This is temporary)
local DoorID = npc:getID() - 2;
local DoorA = GetNPCByID(DoorID):getAnimation();
if (DoorA == 9 and npc:getAnimation() == 9) then
npc:openDoor(8);
-- Should be a 1 second delay here before the door opens
GetNPCByID(DoorID):openDoor(6);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Port_Windurst/npcs/Paytah.lua | 38 | 1029 | -----------------------------------
-- Area: Port Windurst
-- NPC: Paytah
-- Type: Standard NPC
-- @zone: 240
-- @pos 77.550 -6 117.769
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0120);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/items/rogue_rice_ball.lua | 21 | 1437 | -----------------------------------------
-- ID: 4604
-- Item: Rogue Rice Ball
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +12
-- Vit +3
-- hHP +2
-- Effect with enhancing equipment (Note: these are latents on gear with the effect)
-- Def +50
-- Beast Killer (guesstimated 5%)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4604);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 12);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_HPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 12);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_HPHEAL, 2);
end; | gpl-3.0 |
Chris7/Mudlet2 | src/old_mudlet-lua/lua/StringUtils.lua | 10 | 4592 | ----------------------------------------------------------------------------------
--- Mudlet String Utils
----------------------------------------------------------------------------------
--- Cut string to specified maximum length.
---
--- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>)
---
--- @usage Following call will return 'abc'.
--- <pre>
--- string.cut("abcde", 3)
--- </pre>
--- @usage You can easily pad string to certain length.
--- Example bellow will print 'abcde ' e.g. pad/cut string to 10 characters.
--- <pre>
--- local s = "abcde"
--- s = string.cut(s .. " ", 10) -- append 10 spaces
--- echo("'" .. s .. "'")
--- </pre>
function string.cut(s, maxLen)
if string.len(s) > maxLen then
return string.sub(s, 1, maxLen)
else
return s
end
end
--- Enclose string by long brackets. <br/>
function string.enclose(s, maxlevel)
s = "["..s.."]"
local level = 0
while 1 do
if maxlevel and level == maxlevel then
error( "error: maxlevel too low, "..maxlevel )
elseif string.find( s, "%["..string.rep( "=", level ).."%[" ) or string.find( s, "]"..string.rep( "=", level ).."]" ) then
level = level + 1
else
return "["..string.rep( "=", level )..s..string.rep( "=", level ).."]"
end
end
end
--- Test if string is ending with specified suffix.
---
--- @see string.starts
function string.ends(String, Suffix)
return Suffix=='' or string.sub(String,-string.len(Suffix))==Suffix
end
--- Generate case insensitive search pattern from string.
---
--- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>)
---
--- @return case insensitive pattern string
---
--- @usage Following example will generate and print <i>"123[aA][bB][cC]"</i> string.
--- <pre>
--- echo(string.genNocasePattern("123abc"))
--- </pre>
function string.genNocasePattern(s)
s = string.gsub(s, "%a",
function (c)
return string.format("[%s%s]", string.lower(c), string.upper(c))
end)
return s
end
--- Return first matching substring or nil.
---
--- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>)
---
--- @return nil or first matching substring
---
--- @usage Following example will print: "I did find: Troll" string.
--- <pre>
--- local match = string.findPattern("Troll is here!", "Troll")
--- if match then
--- echo("I did find: " .. match)
--- end
--- </pre>
--- @usage This example will find substring regardless of case.
--- <pre>
--- local match = string.findPattern("Troll is here!", string.genNocasePattern("troll"))
--- if match then
--- echo("I did find: " .. match)
--- end
--- </pre>
---
--- @see string.genNocasePattern
function string.findPattern(text, pattern)
if string.find(text, pattern, 1) then
return string.sub(text, string.find(text, pattern, 1))
else
return nil
end
end
--- Splits a string into a table by the given delimiter.
---
--- @usage Split string by ", " delimiter.
--- <pre>
--- names = "Alice, Bob, Peter"
--- name_table = names:split(", ")
--- display(name_table)
--- </pre>
---
--- Previous code will print out:
--- <pre>
--- table {
--- 1: 'Alice'
--- 2: 'Bob'
--- 3: 'Peter'
--- }
--- </pre>
---
--- @return array with split strings
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
--- Test if string is starting with specified prefix.
---
--- @see string.ends
function string.starts(String, Prefix)
return string.sub(String,1,string.len(Prefix))==Prefix
end
--- Capitalize first character in a string.
---
--- @usage Variable testname is now Anna.
--- <pre>
--- testname = string.title("anna")
--- </pre>
--- @usage Example will set test to "Bob".
--- <pre>
--- test = "bob"
--- test = string.title(test)
--- </pre>
function string:title()
self = self:gsub("^%l", string.upper, 1)
return self
end
--- Trim string (remove all white spaces around string).
---
--- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>)
---
--- @usage Example will print 'Troll is here!'.
--- <pre>
--- local str = string.trim(" Troll is here! ")
--- echo("'" .. str .. "'")
--- </pre>
function string.trim(s)
if s then
return string.gsub(s, "^%s*(.-)%s*$", "%1")
else
return s
end
end
| gpl-2.0 |
ffxiphoenix/darkstar | scripts/globals/spells/doton_san.lua | 17 | 1615 | -----------------------------------------
-- Spell: Doton: San
-- Deals earth damage to an enemy and lowers its resistance against wind.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(MERIT_DOTON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0;
local bonusMab = caster:getMerit(MERIT_DOTON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod
if(caster:getMerit(MERIT_DOTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits
bonusMab = bonusMab + caster:getMerit(MERIT_DOTON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5
bonusAcc = bonusAcc + caster:getMerit(MERIT_DOTON_SAN) - 5;
end;
if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees
bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower();
end
local dmg = doNinjutsuNuke(134,1,caster,spell,target,false,bonusAcc,bonusMab);
handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_WINDRES);
return dmg;
end; | gpl-3.0 |
Quenty/NevermoreEngine | src/characterutils/src/Shared/CharacterUtils.lua | 1 | 2848 | --[=[
General character utility code.
@class CharacterUtils
]=]
local Players = game:GetService("Players")
local CharacterUtils = {}
--[=[
Gets a player's humanoid, if it exists
@param player Player
@return Humanoid? -- Nil if not found
]=]
function CharacterUtils.getPlayerHumanoid(player)
local character = player.Character
if not character then
return nil
end
return character:FindFirstChildOfClass("Humanoid")
end
--[=[
Gets a player's humanoid, and ensures it is alive, otherwise returns nil
@param player Player
@return Humanoid? -- Nil if not found
]=]
function CharacterUtils.getAlivePlayerHumanoid(player)
local humanoid = CharacterUtils.getPlayerHumanoid(player)
if not humanoid or humanoid.Health <= 0 then
return nil
end
return humanoid
end
--[=[
Gets a player's humanoid's rootPart, and ensures the humanoid is alive, otherwise
returns nil
@param player Player
@return BasePart? -- Nil if not found
]=]
function CharacterUtils.getAlivePlayerRootPart(player)
local humanoid = CharacterUtils.getPlayerHumanoid(player)
if not humanoid or humanoid.Health <= 0 then
return nil
end
return humanoid.RootPart
end
--[=[
Gets a player's humanoid's rootPart otherwise returns nil
@param player Player
@return BasePart? -- Nil if not found
]=]
function CharacterUtils.getPlayerRootPart(player)
local humanoid = CharacterUtils.getPlayerHumanoid(player)
if not humanoid then
return nil
end
return humanoid.RootPart
end
--[=[
Unequips all tools for a give player's humanomid, if the humanoid
exists
```lua
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
CharacterUtils.unequipTools(player)
end
```
@param player Player
]=]
function CharacterUtils.unequipTools(player)
local humanoid = CharacterUtils.getPlayerHumanoid(player)
if humanoid then
humanoid:UnequipTools()
end
end
--[=[
Returns the player that a descendent is part of, if it is part of one.
```lua
script.Parent.Touched:Connect(function(inst)
local player = CharacterUtils.getPlayerFromCharacter(inst)
if player then
-- activate button!
end
end)
```
:::tip
This method is useful in a ton of different situations. For example, you can
use it on classes bound to a humanoid, to determine the player. You can also
use it to determine, upon touched events, if a part is part of a character.
:::
@param descendant Instance -- A child of the potential character.
@return Player? -- Nil if not found
]=]
function CharacterUtils.getPlayerFromCharacter(descendant)
local character = descendant
local player = Players:GetPlayerFromCharacter(character)
while not player do
if character.Parent then
character = character.Parent
player = Players:GetPlayerFromCharacter(character)
else
return nil
end
end
return player
end
return CharacterUtils | mit |
ffxiphoenix/darkstar | scripts/zones/Dynamis-Beaucedine/mobs/Goblin_Statue.lua | 12 | 3366 | -----------------------------------
-- Area: Dynamis Beaucedine
-- NPC: Goblin Statue
-- Map Position: http://images1.wikia.nocookie.net/__cb20090312005233/ffxi/images/thumb/b/b6/Bea.jpg/375px-Bea.jpg
-----------------------------------
package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Beaucedine/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = beaucedineGoblinList;
if (mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if (mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if ((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if (mobNBR <= 20) then
if (mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY)
local DynaMob = getDynaMob(target,mobNBR,2);
if (DynaMob ~= nil) then
-- Spawn Mob
SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob):setPos(X,Y,Z);
GetMobByID(DynaMob):setSpawn(X,Y,Z);
-- Spawn Pet for BST, DRG, and SMN
if (mobNBR == 9 or mobNBR == 15) then
SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob + 1):setPos(X,Y,Z);
GetMobByID(DynaMob + 1):setSpawn(X,Y,Z);
end
end
elseif (mobNBR > 20) then
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
local MJob = GetMobByID(mobNBR):getMainJob();
if (MJob == 9 or MJob == 15) then
-- Spawn Pet for BST, DRG, and SMN
SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR + 1):setPos(X,Y,Z);
GetMobByID(mobNBR + 1):setSpawn(X,Y,Z);
end
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
-- Time Bonus: 031 046
if (mobID == 17326860 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
elseif (mobID == 17326875 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
-- HP Bonus: 037 041 044 051 053
elseif (mobID == 17326866 or mobID == 17326870 or mobID == 17326873 or mobID == 17326880 or mobID == 17326882) then
killer:restoreHP(2000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- MP Bonus: 038 040 045 049 052 104
elseif (mobID == 17326867 or mobID == 17326869 or mobID == 17326874 or mobID == 17326878 or mobID == 17326881 or mobID == 17326933) then
killer:restoreMP(2000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
end; | gpl-3.0 |
azekillDIABLO/Voxellar | mods/MAPGEN/mg_villages/terrain_blend.lua | 1 | 3263 |
-- this function needs to be fed house x, z dimensions and rotation
-- it will then calculate the minimum point (xbmin, avsurfy, zbmin) where the house should be spawned
-- and mark a mapchunk-sized 'house area' for terrain blending
-- re-use already created data structures by the perlin noise functions
local noise_object_blending = nil;
local noise_buffer = nil;
mg_villages.village_area_mark_single_house_area = function(village_area, minp, maxp, pos, pr, village_nr, village)
local YFLATMIN = 2 -- Lowest flat area height
local FFAPROP = 0.5 -- front flat area proportion of dimension
local np_blend = {
offset = 0,
scale = 1,
spread = {x=12, y=12, z=12},
seed = 38393,
octaves = 3,
persist = 0.67
}
local sidelen = maxp.x - minp.x + 1
local xdim, zdim -- dimensions of house plus front flat area
if pos.brotate == 0 or pos.brotate == 2 then
xdim = pos.bsizex
zdim = pos.bsizez + math.floor(FFAPROP * pos.bsizez)
else
xdim = pos.bsizex + math.floor(FFAPROP * pos.bsizex)
zdim = pos.bsizez
end
-- 2D noise perlinmap
local chulens = {x=sidelen, y=sidelen, z=sidelen}
local minpos = {x=minp.x, y=minp.z}
noise_object_blending = noise_object_blending or minetest.get_perlin_map(np_blend, chulens);
local nvals_blend = noise_object_blending:get2dMap_flat(minpos, noise_buffer);
-- local nvals_blend = minetest.get_perlin_map(np_blend, chulens):get2dMap_flat(minpos)
-- mark mapchunk-sized house area
local ni = 1
-- for z = minp.z, maxp.z do
-- for x = minp.x, maxp.x do -- for each column do
for z = math.max( village.vz - village.vs, minp.z), math.min(village.vz + village.vs, maxp.z), 1 do
for x = math.max( village.vx - village.vs, minp.x), math.min(village.vx + village.vs, maxp.x), 1 do -- for each column do
local xrm = x - minp.x -- relative to mapchunk minp
local zrm = z - minp.z
local xr = x - village.vx -- relative to blend centre
local zr = z - village.vz
local xre1 = (zdim / 2) * (xr / zr)
local zre1 = zdim / 2
local xre2 = xdim / 2
local zre2 = (xdim / 2) * (zr / xr)
local rade1 = math.sqrt(xre1 ^ 2 + zre1 ^ 2)
local rade2 = math.sqrt(xre2 ^ 2 + zre2 ^ 2)
local flatrad = math.min(rade1, rade2) -- radius at edge of rectangular house flat area
local n_absblend = math.abs(nvals_blend[ni])
local blenradn = village.vs - n_absblend * 2 -- vary blend radius
local flatradn = flatrad + n_absblend * 2 -- vary shape of house flat area
local nodrad = math.sqrt(xr ^ 2 + zr ^ 2) -- node radius
-- only blend the terrain if it does not already belong to another village
if( village_area[ x ][ z ][ 2 ] == 0 ) then
if x >= (pos.x-1) and x <= (pos.x + pos.bsizex + 1) -- area reserved for house
and z >= (pos.z-1) and z <= (pos.z + pos.bsizez + 1) then
village_area[ x ][ z ] = {village_nr, 4}
elseif nodrad <= flatradn or (xr == 0 and zr == 0) then -- irregular flat area around house
village_area[ x ][ z ] = {village_nr, 1}
elseif nodrad <= blenradn then -- terrain blend area
local blenprop = ((nodrad - flatradn) / (blenradn - flatradn))
village_area[ x ][ z ] = {village_nr, -1 * blenprop} -- terrain blending
else -- no change to terrain
--village_area[xrm][zrm] = {village_nr, 0}
end
end
ni = ni + 1
end
end
end
| lgpl-2.1 |
lxl1140989/sdk-for-tb | feeds/luci/applications/luci-tinyproxy/luasrc/model/cbi/tinyproxy.lua | 80 | 7364 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("tinyproxy", translate("Tinyproxy"),
translate("Tinyproxy is a small and fast non-caching HTTP(S)-Proxy"))
s = m:section(TypedSection, "tinyproxy", translate("Server Settings"))
s.anonymous = true
s:tab("general", translate("General settings"))
s:tab("privacy", translate("Privacy settings"))
s:tab("filter", translate("Filtering and ACLs"))
s:tab("limits", translate("Server limits"))
o = s:taboption("general", Flag, "enabled", translate("Enable Tinyproxy server"))
o.rmempty = false
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("tinyproxy")
else
luci.sys.init.disable("tinyproxy")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "Port", translate("Listen port"),
translate("Specifies the HTTP port Tinyproxy is listening on for requests"))
o.optional = true
o.datatype = "port"
o.placeholder = 8888
o = s:taboption("general", Value, "Listen", translate("Listen address"),
translate("Specifies the addresses Tinyproxy is listening on for requests"))
o.optional = true
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0"
o = s:taboption("general", Value, "Bind", translate("Bind address"),
translate("Specifies the address Tinyproxy binds to for outbound forwarded requests"))
o.optional = true
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0"
o = s:taboption("general", Value, "DefaultErrorFile", translate("Error page"),
translate("HTML template file to serve when HTTP errors occur"))
o.optional = true
o.default = "/usr/share/tinyproxy/default.html"
o = s:taboption("general", Value, "StatFile", translate("Statistics page"),
translate("HTML template file to serve for stat host requests"))
o.optional = true
o.default = "/usr/share/tinyproxy/stats.html"
o = s:taboption("general", Flag, "Syslog", translate("Use syslog"),
translate("Writes log messages to syslog instead of a log file"))
o = s:taboption("general", Value, "LogFile", translate("Log file"),
translate("Log file to use for dumping messages"))
o.default = "/var/log/tinyproxy.log"
o:depends("Syslog", "")
o = s:taboption("general", ListValue, "LogLevel", translate("Log level"),
translate("Logging verbosity of the Tinyproxy process"))
o:value("Critical")
o:value("Error")
o:value("Warning")
o:value("Notice")
o:value("Connect")
o:value("Info")
o = s:taboption("general", Value, "User", translate("User"),
translate("Specifies the user name the Tinyproxy process is running as"))
o.default = "nobody"
o = s:taboption("general", Value, "Group", translate("Group"),
translate("Specifies the group name the Tinyproxy process is running as"))
o.default = "nogroup"
--
-- Privacy
--
o = s:taboption("privacy", Flag, "XTinyproxy", translate("X-Tinyproxy header"),
translate("Adds an \"X-Tinyproxy\" HTTP header with the client IP address to forwarded requests"))
o = s:taboption("privacy", Value, "ViaProxyName", translate("Via hostname"),
translate("Specifies the Tinyproxy hostname to use in the Via HTTP header"))
o.placeholder = "tinyproxy"
o.datatype = "hostname"
s:taboption("privacy", DynamicList, "Anonymous", translate("Header whitelist"),
translate("Specifies HTTP header names which are allowed to pass-through, all others are discarded. Leave empty to disable header filtering"))
--
-- Filter
--
o = s:taboption("filter", DynamicList, "Allow", translate("Allowed clients"),
translate("List of IP addresses or ranges which are allowed to use the proxy server"))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("filter", DynamicList, "ConnectPort", translate("Allowed connect ports"),
translate("List of allowed ports for the CONNECT method. A single value \"0\" allows all ports"))
o.placeholder = 0
o.datatype = "port"
s:taboption("filter", FileUpload, "Filter", translate("Filter file"),
translate("Plaintext file with URLs or domains to filter. One entry per line"))
s:taboption("filter", Flag, "FilterURLs", translate("Filter by URLs"),
translate("By default, filtering is done based on domain names. Enable this to match against URLs instead"))
s:taboption("filter", Flag, "FilterExtended", translate("Filter by RegExp"),
translate("By default, basic POSIX expressions are used for filtering. Enable this to activate extended regular expressions"))
s:taboption("filter", Flag, "FilterCaseSensitive", translate("Filter case-sensitive"),
translate("By default, filter strings are treated as case-insensitive. Enable this to make the matching case-sensitive"))
s:taboption("filter", Flag, "FilterDefaultDeny", translate("Default deny"),
translate("By default, the filter rules act as blacklist. Enable this option to only allow matched URLs or domain names"))
--
-- Limits
--
o = s:taboption("limits", Value, "Timeout", translate("Connection timeout"),
translate("Maximum number of seconds an inactive connection is held open"))
o.optional = true
o.datatype = "uinteger"
o.default = 600
o = s:taboption("limits", Value, "MaxClients", translate("Max. clients"),
translate("Maximum allowed number of concurrently connected clients"))
o.datatype = "uinteger"
o.default = 10
o = s:taboption("limits", Value, "MinSpareServers", translate("Min. spare servers"),
translate("Minimum number of prepared idle processes"))
o.datatype = "uinteger"
o.default = 5
o = s:taboption("limits", Value, "MaxSpareServers", translate("Max. spare servers"),
translate("Maximum number of prepared idle processes"))
o.datatype = "uinteger"
o.default = 10
o = s:taboption("limits", Value, "StartServers", translate("Start spare servers"),
translate("Number of idle processes to start when launching Tinyproxy"))
o.datatype = "uinteger"
o.default = 5
o = s:taboption("limits", Value, "MaxRequestsPerChild", translate("Max. requests per server"),
translate("Maximum allowed number of requests per process. If it is exeeded, the process is restarted. Zero means unlimited."))
o.datatype = "uinteger"
o.default = 0
--
-- Upstream
--
s = m:section(TypedSection, "upstream", translate("Upstream Proxies"),
translate("Upstream proxy rules define proxy servers to use when accessing certain IP addresses or domains."))
s.anonymous = true
s.addremove = true
t = s:option(ListValue, "type", translate("Policy"),
translate("<em>Via proxy</em> routes requests to the given target via the specifed upstream proxy, <em>Reject access</em> disables any upstream proxy for the target"))
t:value("proxy", translate("Via proxy"))
t:value("reject", translate("Reject access"))
ta = s:option(Value, "target", translate("Target host"),
translate("Can be either an IP address or range, a domain name or \".\" for any host without domain"))
ta.rmempty = true
ta.placeholder = "0.0.0.0/0"
ta.datatype = "host"
v = s:option(Value, "via", translate("Via proxy"),
translate("Specifies the upstream proxy to use for accessing the target host. Format is <code>address:port</code>"))
v:depends({type="proxy"})
v.placeholder = "10.0.0.1:8080"
return m
| gpl-2.0 |
RK1K/RKScriptFolder | RK Max Flash.lua | 1 | 6113 | -- Developer: PvPSuite (http://forum.botoflegends.com/user/76516-pvpsuite/)
if FileExist(LIB_PATH.."MenuLibRK.lua") then
require 'MenuLibRK'
else
print("Downloading MenuConfig, please don't reload script!")
DownloadFile("https://raw.githubusercontent.com/RK1K/RKScriptFolder/master/MenuLibRK.lua?rand="..math.random(1500, 2500), LIB_PATH.."MenuLibRK.lua", function()
print("Finsihed downloading MenuConfig, please reload script!")
end)
return
end
local version = "4.7"
local reformer = "RK1K"
local SCRIPT_NAME = "RK_Max_Flash"
local AUTOUPDATE = true
local UPDATE_HOST = "raw.githubusercontent.com"
local UPDATE_PATH = "/RK1K/RKScriptFolder/master/RK%20Max%20Flash.lua".."?rand="..math.random(3000,4000)
local UPDATE_FILE_PATH = SCRIPT_PATH..GetCurrentEnv().FILE_NAME
local UPDATE_URL = "https://"..UPDATE_HOST..UPDATE_PATH
local MF = nil
local flashSpell = nil
local spellHeader = nil
local slotPos = nil
local s1H = nil
local s2H = nil
local flashH = nil
local canBeUsed = false
local lastKP = 0
local mh = myHero
local mp = mousePos
function OnLoad() Update()
MF = MenuConfig("RK Max Flash", "RK Max Flash")
MF:Menu("info", "Version: IV.VI Patch: 8.3", "info-sign")
MF:Section("Options", ARGB(255, 114, 223, 230))
MF:KeyBinding("flashKey", "Max Flash Key:", string.byte("T"))
MF:Boolean("FlashReplace", "Replace Flash", true);
MF:Boolean("flashmax", "Max = Only If Wall", true);
MF:Section("Script Draws", ARGB(155, 114, 223, 30))
MF:Boolean("showFlashRange", "Enable Draws", true)
MF:Menu("D", "Range Draw", "riflescope")
MF.D:Boolean("FlashR", "Draw Flash Range", true);
MF.D:Slider("Quality1", "Quality of Range:", 2, 0, 5, 1)
MF.D:Slider("QualityD", "Q Lines of Range:", 20, 19, 80, 1)
MF.D:ColorPick("Color", "Color Flash Range", {255, 255, 153, 0})
MF:Menu("S", "Spot Draw", "target")
MF.S:Slider("Width", "Size of Spot:", 60, 19, 150, 1)
MF.S:Slider("Quality2", "Quality of Spot:", 2, 0, 5, 1)
MF.S:Slider("QualityS", "Q Lines of Spot:", 10, 2, 30, 1)
MF.S:ColorPick("Color2", "Color Flash Spot", {255, 0, 235, 8})
MF.S:ColorPick("Color3", "Color Flash OnWall", {255, 255, 0, 255})
MF.S:ColorPick("Color4", "Color Flash NoWall", {255, 221, 255, 0})
if GetSpellName(SUMMONER_1) == 'SummonerFlash' then
flashSpell = SUMMONER_1
flashH = s1H
elseif GetSpellName(SUMMONER_2) == 'SummonerFlash' then
flashSpell = SUMMONER_2
flashH = s2H
end
if (flashSpell ~= nil) then
canBeUsed = true
else
print('<font color="#FFFF00"><b>[RK Max Flash]</b> </font><font color="#FF0000">Flash not found</font>') return
end
end
function OnDraw()
local rdy = mh:CanUseSpell(flashSpell) == READY
local tu = table.unpack
if canBeUsed and MF.showFlashRange and rdy then
local maxLocation = GetMaxLocation(450)
if MF.D.FlashR then
DrawCircle3D(mh.x, mh.y, mh.z, 400, MF.D.Quality1, ARGB(tu(MF.D.Color)), MF.D.QualityD)
end
local circleColor = ARGB(tu(MF.S.Color2))
if MF.flashmax then
if (IsBehindWall()) then
circleColor = ARGB(tu(MF.S.Color3))
else
circleColor = ARGB(tu(MF.S.Color4))
end
end
DrawCircle3D(maxLocation.x, maxLocation.y, maxLocation.z, MF.S.Width, MF.S.Quality2, circleColor, MF.S.QualityS)
end
end
function OnTick()
local rdy = myHero:CanUseSpell(flashSpell) == READY
if canBeUsed and MF.flashKey and MF.FlashReplace and ((CurrentTimeInMillis() - lastKP) > 250) then
lastKP = CurrentTimeInMillis()
if rdy then
MasterFlash()
end
end
end
function MasterFlash()
local maxLocation = GetMaxLocation(425)
flashPlease = true
if MF.flashmax and not IsBehindWall() then
return CastSpell(flashSpell, mp.x, mp.z)
end
return CastSpell(flashSpell, maxLocation.x, maxLocation.z)
end
function IsBehindWall()
for I = 250, 450, 50 do
local maxLocation = GetMaxLocation(I);
if (CalculatePath(mh, D3DXVECTOR3(maxLocation.x, maxLocation.y, maxLocation.z)).count ~= 2) and (IsWall(D3DXVECTOR3(maxLocation.x, maxLocation.y, maxLocation.z))) then
return true
end
end
return false
end
function GetSpellName(whatSpell)
local theSpell = mh:GetSpellData(whatSpell)
if (theSpell ~= nil) then
return theSpell.name
end
return nil
end
function GetMaxLocation(tR)
local mVector = Vector(mp.x, mp.z, mp.y)
local hVector = Vector(mh.x, mh.z, mh.y)
local bVector = ((mVector - hVector):normalized() * tR) + hVector
local theX, theZ, theY = bVector:unpack()
return {x = theX, y = theY, z = theZ}
end
function CurrentTimeInMillis()
local clok = os.clock() * 1000
return clok
end
function Update()
if AUTOUPDATE then
local ServerData = GetWebResult(UPDATE_HOST, "/RK1K/RKScriptFolder/master/Skinchanger.version")
if ServerData then
ServerVersion = type(tonumber(ServerData)) == "number" and tonumber(ServerData) or nil
if ServerVersion then
if tonumber(version) < ServerVersion then
DelayAction(function() print("<font color=\"#000000\"> | </font><font color=\"#FF0000\"><font color=\"#FFFFFF\">New version found for RK Max Flash... <font color=\"#000000\"> | </font><font color=\"#FF0000\"></font><font color=\"#FF0000\"><b> Version "..ServerVersion.."</b></font>") end, 3)
DelayAction(function() print("<font color=\"#FFFFFF\"><b> >> Updating, please don't press F9 << </b></font>") end, 4)
DelayAction(function() DownloadFile(UPDATE_URL, UPDATE_FILE_PATH, function () print("<font color=\"#000000\"> | </font><font color=\"#FF0000\"><font color=\"#FFFFFF\">RK Max Flash</font> <font color=\"#000000\"> | </font><font color=\"#FF0000\">UPDATED <font color=\"#FF0000\"><b>("..version.." => "..ServerVersion..")</b></font> Press F9 twice to load the updated version.") end) end, 5)
else
DelayAction(function() print("<b><font color=\"#000000\"> | </font><font color=\"#FF0000\"><font color=\"#FFFFFF\">RK Max Flash</font><font color=\"#000000\"> | </font><font color=\"#FF0000\"><font color=\"#FF0000\"> Version "..ServerVersion.."</b></font>") end, 1)
end
end
else
DelayAction(function() print("<font color=\"#FFFF00\">RK Max Flash - Error while downloading version info, RE-DOWNLOAD MANUALLY.</font>")end, 1)
end
end
end
| gpl-3.0 |
dail8859/ScintilluaPlusPlus | ext/scintillua/lexers/batch.lua | 5 | 2073 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Batch LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'batch'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local rem = (P('REM') + 'rem') * l.space
local comment = token(l.COMMENT, (rem + '::') * l.nonnewline^0)
-- Strings.
local string = token(l.STRING, l.delimited_range('"', true))
-- Keywords.
local keyword = token(l.KEYWORD, word_match({
'cd', 'chdir', 'md', 'mkdir', 'cls', 'for', 'if', 'echo', 'echo.', 'move',
'copy', 'ren', 'del', 'set', 'call', 'exit', 'setlocal', 'shift',
'endlocal', 'pause', 'defined', 'exist', 'errorlevel', 'else', 'in', 'do',
'NUL', 'AUX', 'PRN', 'not', 'goto', 'pushd', 'popd'
}, nil, true))
-- Functions.
local func = token(l.FUNCTION, word_match({
'APPEND', 'ATTRIB', 'CHKDSK', 'CHOICE', 'DEBUG', 'DEFRAG', 'DELTREE',
'DISKCOMP', 'DISKCOPY', 'DOSKEY', 'DRVSPACE', 'EMM386', 'EXPAND', 'FASTOPEN',
'FC', 'FDISK', 'FIND', 'FORMAT', 'GRAPHICS', 'KEYB', 'LABEL', 'LOADFIX',
'MEM', 'MODE', 'MORE', 'MOVE', 'MSCDEX', 'NLSFUNC', 'POWER', 'PRINT', 'RD',
'REPLACE', 'RESTORE', 'SETVER', 'SHARE', 'SORT', 'SUBST', 'SYS', 'TREE',
'UNDELETE', 'UNFORMAT', 'VSAFE', 'XCOPY'
}, nil, true))
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Variables.
local variable = token(l.VARIABLE,
'%' * (l.digit + '%' * l.alpha) +
l.delimited_range('%', true, true))
-- Operators.
local operator = token(l.OPERATOR, S('+|&!<>='))
-- Labels.
local label = token(l.LABEL, ':' * l.word)
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'function', func},
{'comment', comment},
{'identifier', identifier},
{'string', string},
{'variable', variable},
{'label', label},
{'operator', operator},
}
M._LEXBYLINE = true
M._foldsymbols = {
_patterns = {'[A-Za-z]+'},
[l.KEYWORD] = {setlocal = 1, endlocal = -1, SETLOCAL = 1, ENDLOCAL = -1}
}
return M
| gpl-2.0 |
ffxiphoenix/darkstar | scripts/zones/Windurst_Waters/npcs/Clais.lua | 36 | 1715 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Clais
-- Involved In Quest: Hat in Hand
-- @zone = 238
-- @pos = -31 -3 11
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND);
if ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and testflag(tonumber(player:getVar("QuestHatInHand_var")),8) == false) then
player:startEvent(0x0039); -- Show Off Hat
else
player:startEvent(0x025a); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0039) then -- Show Off Hat
player:setVar("QuestHatInHand_var",player:getVar("QuestHatInHand_var")+8);
player:setVar("QuestHatInHand_count",player:getVar("QuestHatInHand_count")+1);
end
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.