repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
OctoEnigma/shiny-octo-system | addons/advdupe2-master/lua/advdupe2/sv_file.lua | 1 | 2918 | --[[
Title: Adv. Dupe 2 Filing Clerk (Serverside)
Desc: Reads/writes AdvDupe2 files.
Author: AD2 Team
Version: 1.0
]]
file.CreateDir("advdupe2")
local PlayerMeta = FindMetaTable("Player")
function PlayerMeta:SteamIDSafe()
return self:SteamID():gsub(":","_")
end
--[[
Name: WriteAdvDupe2File
Desc: Writes a dupe file to the dupe folder.
Params: <string> dupe, <string> name
Return: <boolean> success/<string> path
]]
function AdvDupe2.WriteFile(ply, name, dupe)
name = name:lower()
if name:find("[<>:\\\"|%?%*%.]") then return false end
name = name:gsub("//","/")
local path
if game.SinglePlayer() then
path = string.format("%s/%s", AdvDupe2.DataFolder, name)
else
path = string.format("%s/%s/%s", AdvDupe2.DataFolder, ply and ply:SteamIDSafe() or "=Public=", name)
end
--if a file with this name already exists, we have to come up with a different name
if file.Exists(path..".txt", "DATA") then
for i = 1, AdvDupe2.FileRenameTryLimit do
--check if theres already a file with the name we came up with, and retry if there is
--otherwise, we can exit the loop and write the file
if not file.Exists(path.."_"..i..".txt", "DATA") then
path = path.."_"..i
break
end
end
--if we still can't find a unique name we give up
if file.Exists(path..".txt", "DATA") then return false end
end
--write the file
file.Write(path..".txt", dupe)
--returns if the write was successful and the name the path ended up being saved under
return path..".txt", path:match("[^/]-$")
end
--[[
Name: ReadAdvDupe2File
Desc: Reads a dupe file from the dupe folder.
Params: <string> name
Return: <string> contents
]]
function AdvDupe2.ReadFile(ply, name, dirOverride)
if game.SinglePlayer() then
local path = string.format("%s/%s.txt", dirOverride or AdvDupe2.DataFolder, name)
if(!file.Exists(path, "DATA"))then
if(ply)then AdvDupe2.Notify(ply, "File does not exist!", NOTIFY_ERROR) end
return nil
else
return file.Read(path)
end
else
local path = string.format("%s/%s/%s.txt", dirOverride or AdvDupe2.DataFolder, ply and ply:SteamIDSafe() or "=Public=", name)
if(!file.Exists(path, "DATA"))then
if(ply)then AdvDupe2.Notify(ply, "File does not exist!", NOTIFY_ERROR) end
return nil
elseif(file.Size(path, "DATA")/1024>tonumber(GetConVarString("AdvDupe2_MaxFileSize")))then
if(ply)then AdvDupe2.Notify(ply,"File size is greater than "..GetConVarString("AdvDupe2_MaxFileSize"), NOTIFY_ERROR) end
return false
else
return file.Read(path)
end
end
end
function PlayerMeta:WriteAdvDupe2File(name, dupe)
return AdvDupe2.WriteFile(self, name, dupe)
end
function PlayerMeta:ReadAdvDupe2File(name)
return AdvDupe2.ReadFile(self, name)
end
function PlayerMeta:GetAdvDupe2Folder()
if game.SinglePlayer() then
return AdvDupe2.DataFolder
else
return string.format("%s/%s", AdvDupe2.DataFolder, self:SteamIDSafe())
end
end
| mit |
RunAwayDSP/darkstar | scripts/globals/abilities/curing_waltz_iv.lua | 12 | 2467 | -----------------------------------
-- Ability: Curing Waltz IV
-- Heals HP to target player.
-- Obtained: Dancer Level 70
-- TP Required: 65%
-- Recast Time: 00:17
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
if (target:getHP() == 0) then
return dsp.msg.basic.CANNOT_ON_THAT_TARG,0
elseif (player:hasStatusEffect(dsp.effect.SABER_DANCE)) then
return dsp.msg.basic.UNABLE_TO_USE_JA2, 0
elseif (player:hasStatusEffect(dsp.effect.TRANCE)) then
return 0,0
elseif (player:getTP() < 650) then
return dsp.msg.basic.NOT_ENOUGH_TP,0
else
--[[ Apply "Waltz Ability Delay" reduction
1 modifier = 1 second]]
local recastMod = player:getMod(dsp.mod.WALTZ_DELAY)
if (recastMod ~= 0) then
local newRecast = ability:getRecast() +recastMod
ability:setRecast(utils.clamp(newRecast,0,newRecast))
end
-- Apply "Fan Dance" Waltz recast reduction
if (player:hasStatusEffect(dsp.effect.FAN_DANCE)) then
local fanDanceMerits = target:getMerit(dsp.merit.FAN_DANCE)
-- Every tier beyond the 1st is -5% recast time
if (fanDanceMerits > 5) then
ability:setRecast(ability:getRecast() * ((fanDanceMerits -5)/100))
end
end
return 0,0
end
end
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(dsp.effect.TRANCE) then
player:delTP(650)
end
--Grabbing variables.
local vit = target:getStat(dsp.mod.VIT)
local chr = player:getStat(dsp.mod.CHR)
local mjob = player:getMainJob() --19 for DNC main.
local cure = 0
--Performing mj check.
if mjob == dsp.job.DNC then
cure = (vit+chr)+450
end
-- apply waltz modifiers
cure = math.floor(cure * (1.0 + (player:getMod(dsp.mod.WALTZ_POTENTCY)/100)))
--Reducing TP.
--Applying server mods....
cure = cure * CURE_POWER
--Cap the final amount to max HP.
if ((target:getMaxHP() - target:getHP()) < cure) then
cure = (target:getMaxHP() - target:getHP())
end
--Do it
target:restoreHP(cure)
target:wakeUp()
player:updateEnmityFromCure(target,cure)
return cure
end
| gpl-3.0 |
KSDaemon/lua-websockets | src/websocket/sync.lua | 3 | 5386 | local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local tools = require'websocket.tools'
local ssl = require'ssl'
local tinsert = table.insert
local tconcat = table.concat
local receive = function(self)
if self.state ~= 'OPEN' and not self.is_closing then
return nil,nil,false,1006,'wrong state'
end
local first_opcode
local frames
local bytes = 3
local encoded = ''
local clean = function(was_clean,code,reason)
self.state = 'CLOSED'
self:sock_close()
if self.on_close then
self:on_close()
end
return nil,nil,was_clean,code,reason or 'closed'
end
while true do
local chunk,err = self:sock_receive(bytes)
if err then
return clean(false,1006,err)
end
encoded = encoded..chunk
local decoded,fin,opcode,_,masked = frame.decode(encoded)
if not self.is_server and masked then
return clean(false,1006,'Websocket receive failed: frame was not masked')
end
if decoded then
if opcode == frame.CLOSE then
if not self.is_closing then
local code,reason = frame.decode_close(decoded)
-- echo code
local msg = frame.encode_close(code)
local encoded = frame.encode(msg,frame.CLOSE,not self.is_server)
local n,err = self:sock_send(encoded)
if n == #encoded then
return clean(true,code,reason)
else
return clean(false,code,err)
end
else
return decoded,opcode
end
end
if not first_opcode then
first_opcode = opcode
end
if not fin then
if not frames then
frames = {}
elseif opcode ~= frame.CONTINUATION then
return clean(false,1002,'protocol error')
end
bytes = 3
encoded = ''
tinsert(frames,decoded)
elseif not frames then
return decoded,first_opcode
else
tinsert(frames,decoded)
return tconcat(frames),first_opcode
end
else
assert(type(fin) == 'number' and fin > 0)
bytes = fin
end
end
assert(false,'never reach here')
end
local send = function(self,data,opcode)
if self.state ~= 'OPEN' then
return nil,false,1006,'wrong state'
end
local encoded = frame.encode(data,opcode or frame.TEXT,not self.is_server)
local n,err = self:sock_send(encoded)
if n ~= #encoded then
return nil,self:close(1006,err)
end
return true
end
local close = function(self,code,reason)
if self.state ~= 'OPEN' then
return false,1006,'wrong state'
end
if self.state == 'CLOSED' then
return false,1006,'wrong state'
end
local msg = frame.encode_close(code or 1000,reason)
local encoded = frame.encode(msg,frame.CLOSE,not self.is_server)
local n,err = self:sock_send(encoded)
local was_clean = false
local code = 1005
local reason = ''
if n == #encoded then
self.is_closing = true
local rmsg,opcode = self:receive()
if rmsg and opcode == frame.CLOSE then
code,reason = frame.decode_close(rmsg)
was_clean = true
end
else
reason = err
end
self:sock_close()
if self.on_close then
self:on_close()
end
self.state = 'CLOSED'
return was_clean,code,reason or ''
end
local connect = function(self,ws_url,ws_protocol,ssl_params)
if self.state ~= 'CLOSED' then
return nil,'wrong state',nil
end
local protocol,host,port,uri = tools.parse_url(ws_url)
-- Preconnect (for SSL if needed)
local _,err = self:sock_connect(host,port)
if err then
return nil,err,nil
end
if protocol == 'wss' then
self.sock = ssl.wrap(self.sock, ssl_params)
self.sock:dohandshake()
elseif protocol ~= "ws" then
return nil, 'bad protocol'
end
local ws_protocols_tbl = {''}
if type(ws_protocol) == 'string' then
ws_protocols_tbl = {ws_protocol}
elseif type(ws_protocol) == 'table' then
ws_protocols_tbl = ws_protocol
end
local key = tools.generate_key()
local req = handshake.upgrade_request
{
key = key,
host = host,
port = port,
protocols = ws_protocols_tbl,
uri = uri
}
local n,err = self:sock_send(req)
if n ~= #req then
return nil,err,nil
end
local resp = {}
repeat
local line,err = self:sock_receive('*l')
resp[#resp+1] = line
if err then
return nil,err,nil
end
until line == ''
local response = table.concat(resp,'\r\n')
local headers = handshake.http_headers(response)
local expected_accept = handshake.sec_websocket_accept(key)
if headers['sec-websocket-accept'] ~= expected_accept then
local msg = 'Websocket Handshake failed: Invalid Sec-Websocket-Accept (expected %s got %s)'
return nil,msg:format(expected_accept,headers['sec-websocket-accept'] or 'nil'),headers
end
self.state = 'OPEN'
return true,headers['sec-websocket-protocol'],headers
end
local extend = function(obj)
assert(obj.sock_send)
assert(obj.sock_receive)
assert(obj.sock_close)
assert(obj.is_closing == nil)
assert(obj.receive == nil)
assert(obj.send == nil)
assert(obj.close == nil)
assert(obj.connect == nil)
if not obj.is_server then
assert(obj.sock_connect)
end
if not obj.state then
obj.state = 'CLOSED'
end
obj.receive = receive
obj.send = send
obj.close = close
obj.connect = connect
return obj
end
return {
extend = extend
}
| mit |
taiha/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/network.lua | 53 | 2738 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("Network Plugin Configuration"),
translate(
"The network plugin provides network based communication between " ..
"different collectd instances. Collectd can operate both in client " ..
"and server mode. In client mode locally collected data is " ..
"transferred to a collectd server instance, in server mode the " ..
"local instance receives data from other hosts."
))
-- collectd_network config section
s = m:section( NamedSection, "collectd_network", "luci_statistics" )
-- collectd_network.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_network_listen config section (Listen)
listen = m:section( TypedSection, "collectd_network_listen",
translate("Listener interfaces"),
translate(
"This section defines on which interfaces collectd will wait " ..
"for incoming connections."
))
listen.addremove = true
listen.anonymous = true
-- collectd_network_listen.host
listen_host = listen:option( Value, "host", translate("Listen host") )
listen_host.default = "0.0.0.0"
-- collectd_network_listen.port
listen_port = listen:option( Value, "port", translate("Listen port") )
listen_port.default = 25826
listen_port.isinteger = true
listen_port.optional = true
-- collectd_network_server config section (Server)
server = m:section( TypedSection, "collectd_network_server",
translate("server interfaces"),
translate(
"This section defines to which servers the locally collected " ..
"data is sent to."
))
server.addremove = true
server.anonymous = true
-- collectd_network_server.host
server_host = server:option( Value, "host", translate("Server host") )
server_host.default = "0.0.0.0"
-- collectd_network_server.port
server_port = server:option( Value, "port", translate("Server port") )
server_port.default = 25826
server_port.isinteger = true
server_port.optional = true
-- collectd_network.timetolive (TimeToLive)
ttl = s:option( Value, "TimeToLive", translate("TTL for network packets") )
ttl.default = 128
ttl.isinteger = true
ttl.optional = true
ttl:depends( "enable", 1 )
-- collectd_network.forward (Forward)
forward = s:option( Flag, "Forward", translate("Forwarding between listen and server addresses") )
forward.default = 0
forward.optional = true
forward:depends( "enable", 1 )
-- collectd_network.cacheflush (CacheFlush)
cacheflush = s:option( Value, "CacheFlush",
translate("Cache flush interval"), translate("Seconds") )
cacheflush.default = 86400
cacheflush.isinteger = true
cacheflush.optional = true
cacheflush:depends( "enable", 1 )
return m
| apache-2.0 |
OctoEnigma/shiny-octo-system | gamemodes/darkrp/gamemode/modules/fadmin/fadmin/playeractions/voicemute/cl_init.lua | 10 | 3196 | hook.Add("PlayerBindPress", "FAdmin_voicemuted", function(ply, bind, pressed)
if ply:FAdmin_GetGlobal("FAdmin_voicemuted") and string.find(string.lower(bind), "voicerecord") then return true end
-- The voice muting is not done clientside, this is just so people know they can't talk
end)
FAdmin.StartHooks["VoiceMute"] = function()
FAdmin.Messages.RegisterNotification{
name = "voicemute",
hasTarget = true,
message = {"instigator", " voice muted ", "targets", " ", "extraInfo.1"},
readExtraInfo = function()
local time = net.ReadUInt(16)
return {time == 0 and FAdmin.PlayerActions.commonTimes[time] or string.format("for %s", FAdmin.PlayerActions.commonTimes[time] or (time .. " seconds"))}
end
}
FAdmin.Messages.RegisterNotification{
name = "voiceunmute",
hasTarget = true,
message = {"instigator", " voice unmuted ", "targets"}
}
FAdmin.Access.AddPrivilege("Voicemute", 2)
FAdmin.Commands.AddCommand("Voicemute", nil, "<Player>")
FAdmin.Commands.AddCommand("UnVoicemute", nil, "<Player>")
FAdmin.ScoreBoard.Player:AddActionButton(function(ply)
if ply:FAdmin_GetGlobal("FAdmin_voicemuted") then return "Unmute voice globally" end
return "Mute voice globally"
end,
function(ply)
if ply:FAdmin_GetGlobal("FAdmin_voicemuted") then return "fadmin/icons/voicemute" end
return "fadmin/icons/voicemute", "fadmin/icons/disable"
end,
Color(255, 130, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Voicemute", ply) end,
function(ply, button)
if not ply:FAdmin_GetGlobal("FAdmin_voicemuted") then
FAdmin.PlayerActions.addTimeMenu(function(secs)
RunConsoleCommand("_FAdmin", "Voicemute", ply:UserID(), secs)
button:SetImage2("null")
button:SetText("Unmute voice globally")
button:GetParent():InvalidateLayout()
end)
else
RunConsoleCommand("_FAdmin", "UnVoicemute", ply:UserID())
end
button:SetImage2("fadmin/icons/disable")
button:SetText("Mute voice globally")
button:GetParent():InvalidateLayout()
end)
FAdmin.ScoreBoard.Player:AddActionButton(function(ply)
return ply.FAdminMuted and "Unmute voice" or "Mute voice"
end,
function(ply)
if ply.FAdminMuted then return "fadmin/icons/voicemute" end
return "fadmin/icons/voicemute", "fadmin/icons/disable"
end,
Color(255, 130, 0, 255),
true,
function(ply, button)
ply:SetMuted(not ply.FAdminMuted)
ply.FAdminMuted = not ply.FAdminMuted
if ply.FAdminMuted then button:SetImage2("null") button:SetText("Unmute voice") button:GetParent():InvalidateLayout() return end
button:SetImage2("fadmin/icons/disable")
button:SetText("Mute voice")
button:GetParent():InvalidateLayout()
end)
FAdmin.ScoreBoard.Main.AddPlayerRightClick("Mute/Unmute", function(ply, Panel)
ply:SetMuted(not ply.FAdminMuted)
ply.FAdminMuted = not ply.FAdminMuted
end)
end
| mit |
RunAwayDSP/darkstar | scripts/globals/abilities/pets/attachments/tension_spring_iii.lua | 11 | 1329 | -----------------------------------
-- Attachment: Tension Spring III
-----------------------------------
require("scripts/globals/automaton")
require("scripts/globals/status")
-----------------------------------
function onEquip(pet)
onUpdate(pet, 0)
end
function onUnequip(pet)
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 0)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 0)
end
function onManeuverGain(pet, maneuvers)
onUpdate(pet, maneuvers)
end
function onManeuverLose(pet, maneuvers)
onUpdate(pet, maneuvers - 1)
end
function onUpdate(pet, maneuvers)
if maneuvers == 0 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 12)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 12)
elseif maneuvers == 1 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 15)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 15)
elseif maneuvers == 2 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 18)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 18)
elseif maneuvers == 3 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 21)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 21)
end
end
| gpl-3.0 |
DrYaling/eluna-trinitycore | src/server/scripts/Scripts-master/Extensions/ObjectCooldownExtension.lua | 1 | 1093 | local cooldowns = {};
function Player:SetLuaCooldown(seconds, opt_id)
assert(type(self) == "userdata");
seconds = assert(tonumber(seconds));
opt_id = opt_id or 1;
local guid, source = self:GetGUIDLow(), debug.getinfo(2, 'S').short_src;
if (not cooldowns[guid]) then
cooldowns[guid] = { [source] = {}; };
end
cooldowns[guid][source][opt_id] = os.clock() + seconds;
end
function Player:GetLuaCooldown(opt_id)
assert(type(self) == "userdata");
local guid, source = self:GetGUIDLow(), debug.getinfo(2, 'S').short_src;
opt_id = opt_id or 1;
if (not cooldowns[guid]) then
cooldowns[guid] = { [source] = {}; };
end
local cd = cooldowns[guid][source][opt_id];
if (not cd or cd < os.clock()) then
cooldowns[guid][source][opt_id] = 0
return 0;
else
return cooldowns[guid][source][opt_id] - os.clock();
end
end
--[[ Example:
if(player:GetLuaCooldown() == 0) then -- Check if cooldown is present
player:SetLuaCooldown(30)
print("Cooldown is set to 30 seconds")
else
print("There are still "..player:GetLuaCooldown().." seconds remaining of your cooldown!")
end
]] | gpl-2.0 |
lichtl/darkstar | scripts/zones/Port_Jeuno/npcs/Horst.lua | 29 | 3441 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Horst
-- Type: Abyssea Warp NPC
-- @pos -54.379 0.001 -10.061 246
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CRUOR = player:getCurrency("cruor");
if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED) then
player:startEvent(0x0153,1,CRUOR,7,7,7); -- Temp activated all locations till param handling sorted out.
elseif (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_COMPLETED) then
player:startEvent(0x0153,2,CRUOR,7,7,7); -- Temp activated all locations till param handling sorted out.
else
player:startEvent(0x0153, 0);
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);
local CRUOR = player:getCurrency("cruor");
if (csid == 0x0153) then
if (option == 260) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(-562,0.001,640,26,102); -- La Theine Plateau
end
elseif (option == 264) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(91,-68,-582,237,108); -- Konshtat Highlands
end
elseif (option == 268) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(-28,46,-680,76,117); -- Tahrongi Canyon
end
elseif (option == 272) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(241,0.001,11,42,104); -- Jugner Forest
end
elseif (option == 276) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(362,0.001,-119,4,103); -- Valkrum
end
elseif (option == 280) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(-338,-23,47,167,118); -- Buburimu Peninsula
end
elseif (option == 288) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(269,-7,-75,192,112); -- Xarcabard
end
elseif (option == 284) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(337,0.001,-675,52,107); -- South Gustaberg
end
elseif (option == 292) then
if (CRUOR >= 200) then
player:delCurrency("cruor", 200);
player:setPos(-71,0.001,601,126,106); -- North Gustaberg
end
end
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Jugner_Forest/npcs/Signpost.lua | 17 | 2835 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Signpost
-- Involved in Quest: Grimy Signposts
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local X = player:getXPos();
local Z = player:getZPos();
if ((X > -79.3 and X < -67.3) and (Z > 94.5 and Z < 106.5)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),0)) then
player:startEvent(0x0006,1);
else
player:startEvent(0x0001);
end
elseif ((X > -266.2 and X < -254.2) and (Z > -29.2 and Z < -17.2)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),1)) then
player:startEvent(0x0007,1);
else
player:startEvent(0x0002);
end
elseif ((X > -463.7 and X < -451.7) and (Z > -422.1 and Z < -410.1)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),2)) then
player:startEvent(0x0008,1);
else
player:startEvent(0x0003);
end
elseif ((X > 295.4 and X < 307.3) and (Z > 412.8 and Z < 424.8)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),3)) then
player:startEvent(0x0009,1);
else
player:startEvent(0x0004);
end
else
print("Unknown Signpost");
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 6 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",0,true);
elseif (csid == 7 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",1,true);
elseif (csid == 8 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",2,true);
elseif (csid == 9 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",3,true);
end
end; | gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Dynamis-Tavnazia/IDs.lua | 9 | 4410 | -----------------------------------
-- Area: Dynamis-Tavnazia
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/dynamis")
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.DYNAMIS_TAVNAZIA] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
CONQUEST_BASE = 7149, -- Tallying conquest results...
DYNAMIS_TIME_BEGIN = 7314, -- The sands of the <item> have begun to fall. You have <number> minutes (Earth time) remaining in Dynamis.
DYNAMIS_TIME_EXTEND = 7315, -- our stay in Dynamis has been extended by <number> minute[/s].
DYNAMIS_TIME_UPDATE_1 = 7316, -- ou will be expelled from Dynamis in <number> [second/minute] (Earth time).
DYNAMIS_TIME_UPDATE_2 = 7317, -- ou will be expelled from Dynamis in <number> [seconds/minutes] (Earth time).
DYNAMIS_TIME_EXPIRED = 7319, -- The sands of the hourglass have emptied...
DIABOLOS = 7328, -- You sense that something might happen if you possessed one of these...
OMINOUS_PRESENCE = 7330, -- You feel an ominous presence, as if something might happen if you possessed <item>.
},
mob =
{
TIME_EXTENSION =
{
{minutes = 10, ki = dsp.ki.CRIMSON_GRANULES_OF_TIME, mob = 16949272},
{minutes = 10, ki = dsp.ki.AZURE_GRANULES_OF_TIME, mob = 16949292},
{minutes = 10, ki = dsp.ki.AMBER_GRANULES_OF_TIME, mob = 16949306},
{minutes = 10, ki = dsp.ki.ALABASTER_GRANULES_OF_TIME, mob = 16949325},
{minutes = 20, ki = dsp.ki.OBSIDIAN_GRANULES_OF_TIME, mob = 16949380},
},
REFILL_STATUE =
{
{
{mob = 16949269, eye = dynamis.eye.RED }, -- Adamantking_Effigy
{mob = 16949270, eye = dynamis.eye.BLUE },
{mob = 16949271, eye = dynamis.eye.GREEN},
},
{
{mob = 16949289, eye = dynamis.eye.RED }, -- Serjeant_Tombstone
{mob = 16949290, eye = dynamis.eye.BLUE },
{mob = 16949291, eye = dynamis.eye.GREEN},
},
{
{mob = 16949303, eye = dynamis.eye.RED }, -- Manifest_Icon
{mob = 16949304, eye = dynamis.eye.BLUE },
{mob = 16949305, eye = dynamis.eye.GREEN},
},
{
{mob = 16949322, eye = dynamis.eye.RED }, -- Goblin_Replica
{mob = 16949323, eye = dynamis.eye.BLUE },
{mob = 16949324, eye = dynamis.eye.GREEN},
},
{
{mob = 16949356, eye = dynamis.eye.RED }, -- Goblin_Replica
{mob = 16949357, eye = dynamis.eye.BLUE },
{mob = 16949358, eye = dynamis.eye.GREEN},
},
{
{mob = 16949362, eye = dynamis.eye.RED }, -- Manifest_Icon
{mob = 16949363, eye = dynamis.eye.BLUE },
{mob = 16949364, eye = dynamis.eye.GREEN},
},
{
{mob = 16949369, eye = dynamis.eye.RED }, -- Adamantking_Effigy
{mob = 16949370, eye = dynamis.eye.BLUE },
{mob = 16949371, eye = dynamis.eye.GREEN},
},
{
{mob = 16949376, eye = dynamis.eye.RED }, -- Serjeant_Tombstone
{mob = 16949377, eye = dynamis.eye.BLUE },
{mob = 16949378, eye = dynamis.eye.GREEN},
},
},
},
npc =
{
QM =
{
[16949396] =
{
param = {3459, 3483, 3484, 3485, 3486},
trade =
{
{item = 3459, mob = {16949249, 16949250, 16949251, 16949252}}, -- Diabolos Spade/Heart/Diamond/Club
{item = {3483, 3484, 3485, 3486}, mob = {16949326, 16949327, 16949328, 16949329}}, -- Diabolos Somnus/Nox/Umbra/Letum
}
},
},
},
}
return zones[dsp.zone.DYNAMIS_TAVNAZIA] | gpl-3.0 |
scscgit/scsc_wildstar_addons | NoisyQ/NoisyQ.lua | 1 | 7013 | -----------------------------------------------------------------------------------------------
-- Client Lua Script for NoisyQ
-- Created by boe2. For questions/comments, mail me at apollo@boe2.be
-----------------------------------------------------------------------------------------------
require "Window"
require "Sound"
local NoisyQ = {}
function NoisyQ:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
self.alarmTypes = {}
self.alarmTypes.Disabled = 0
self.alarmTypes.Once = 1
self.alarmTypes.Repeating = 2
self.settings = {}
self.settings.soundID = 149
self.settings.alarmType = self.alarmTypes.Once
self.settings.confirmAfterQueue = true
self.settings.useCustomVolume = true
self.settings.customeVolumeLevel = 1
self.originalGeneralVolumeLevel = 1
self.originalVoiceVolumeLevel = 1
return o
end
function NoisyQ:Init()
Apollo.RegisterAddon(self)
end
function NoisyQ:OnLoad()
Apollo.CreateTimer("AlarmSoundTimer", 3, true)
Apollo.RegisterSlashCommand("noisyq", "OnNoisyQOn", self)
Apollo.RegisterEventHandler("MatchingJoinQueue", "OnJoinQueue", self)
Apollo.RegisterEventHandler("MatchingLeaveQueue", "OnLeaveQueue", self)
Apollo.RegisterEventHandler("MatchingGameReady", "OnMatchingGameReady", self)
Apollo.RegisterEventHandler("MatchEntered", "OnMatchEntered", self)
Apollo.RegisterTimerHandler("AlarmSoundTimer", "OnAlarmTick", self)
end
function NoisyQ:OnCancel()
self.wndMain:Show(false)
end
function NoisyQ:OnNoisyQOn()
if self.wndMain == nil then
self.wndMain = Apollo.LoadForm("NoisyQ.xml", "NoisyQForm", nil, self)
end
self.wndMain:Show(true)
local askButton = self.wndMain:FindChild("btnAsk")
local onceButton = self.wndMain:FindChild("btnOnce")
local continuousButton = self.wndMain:FindChild("btnContinuous")
local noneButton = self.wndMain:FindChild("btnNothing")
if self.settings.confirmAfterQueue then
self.wndMain:SetRadioSelButton("SoundSelectionGroup", askButton)
elseif self.settings.alarmType == self.alarmTypes.Disabled then
self.wndMain:SetRadioSelButton("SoundSelectionGroup", noneButton)
elseif self.settings.alarmType == self.alarmTypes.Once then
self.wndMain:SetRadioSelButton("SoundSelectionGroup", onceButton)
else
self.wndMain:SetRadioSelButton("SoundSelectionGroup", continuousButton)
end
end
function NoisyQ:OnMatchingGameReady(bInProgress)
self:AlertUser()
self:DismissOptions()
end
function NoisyQ:OnMatchEntered()
self:DismissAlert()
self:DismissOptions()
end
function NoisyQ:OnJoinQueue()
if self.settings.confirmAfterQueue then
if self.wndOptions == nil then
self.wndOptions = Apollo.LoadForm("NoisyQ.xml", "OptionsDialog", nil, self)
end
self.wndOptions:Show(true)
self.wndOptions:ToFront()
end
end
function NoisyQ:OnLeaveQueue()
self:DismissAlert();
self:DismissOptions();
end
function NoisyQ:OnAlarmTick()
if self.wndAlert ~= nil then
if self.wndAlert:IsVisible() then
Sound.Play(self.settings.soundID)
end
end
end
function NoisyQ:OnSave(eLevel)
if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then
return nil
end
local save = {}
save.settings = self.settings
save.saved = true
return save
end
function NoisyQ:OnRestore(eLevel, tData)
if tData.saved ~= nil then
self.settings = tData.settings
end
end
function NoisyQ:AlertUser()
if self.settings.alarmType ~= self.alarmTypes.Disabled then
self:SetCustomVolumeLevels()
if self.settings.alarmType == self.alarmTypes.Once then
Sound.Play(self.settings.soundID)
elseif self.settings.alarmType == self.alarmTypes.Repeating then
if self.wndAlert == nil then
self.wndAlert = Apollo.LoadForm("NoisyQ.xml", "AlertForm", nil, self)
end
self.wndAlert:Show(true)
self.wndAlert:ToFront()
Apollo.StartTimer("AlarmSoundTimer")
end
end
end
function NoisyQ:DismissAlert()
if self.wndAlert ~= nil then
self.wndAlert:Show(false)
Apollo.StopTimer("AlarmSoundTimer")
end
self:RestoreVolumeLevels()
end
function NoisyQ:DismissOptions()
if self.wndOptions ~= nil then
if self.wndOptions:IsVisible() then
self.wndOptions:Show(false)
end
end
end
function NoisyQ:SetCustomVolumeLevels()
if self.settings.useCustomVolume then
self.originalVolumeLevel = Apollo.GetConsoleVariable("sound.volumeMaster")
self.originalVoiceVolumeLevel = Apollo.GetConsoleVariable("sound.volumeVoice")
Apollo.SetConsoleVariable("sound.volumeMaster", self.settings.customeVolumeLevel)
Apollo.SetConsoleVariable("sound.volumeVoice", self.settings.customeVolumeLevel)
end
end
function NoisyQ:RestoreVolumeLevels()
if self.settings.useCustomVolume then
Apollo.SetConsoleVariable("sound.volumeMaster", self.originalVolumeLevel)
Apollo.SetConsoleVariable("sound.volumeVoice", self.originalVoiceVolumeLevel)
end
end
---------------------------------------------------------------------------------------------------
-- AlertForm Functions
---------------------------------------------------------------------------------------------------
function NoisyQ:OnDismissAlert( wndHandler, wndControl, eMouseButton )
self:DismissAlert()
end
---------------------------------------------------------------------------------------------------
-- OptionsDialog Functions
---------------------------------------------------------------------------------------------------
function NoisyQ:OnAudioPrefSet( wndHandler, wndControl, eMouseButton )
local control = wndControl:GetName()
if control == "btnAudioNone" then
self.settings.alarmType = self.alarmTypes.Disabled
elseif control == "btnAudioOnce" then
self.settings.alarmType = self.alarmTypes.Once
else
self.settings.alarmType = self.alarmTypes.Repeating
end
self:DismissOptions()
end
function NoisyQ:OnRememberChoiceToggle( wndHandler, wndControl, eMouseButton )
self.settings.confirmAfterQueue = not wndControl:IsChecked()
end
---------------------------------------------------------------------------------------------------
-- NoisyQForm Functions
---------------------------------------------------------------------------------------------------
function NoisyQ:OnOKClicked( wndHandler, wndControl, eMouseButton )
self.wndMain:Show(false)
end
function NoisyQ:OnAudioPrefSelected( wndHandler, wndControl, eMouseButton )
local selectedButton = wndControl:GetParent():GetRadioSelButton("SoundSelectionGroup")
if selectedButton ~= nil then
local name = selectedButton:GetName()
self.settings.confirmAfterQueue = name == "btnAsk"
if name == "btnOnce" then
self.settings.alarmType = self.alarmTypes.Once
elseif name == "btnContinuous" then
self.settings.alarmType = self.alarmTypes.Repeating
else
self.settings.alarmType = self.alarmTypes.Disabled
end
end
end
-----------------------------------------------------------------------------------------------
-- NoisyQ Instance
-----------------------------------------------------------------------------------------------
local NoisyQInst = NoisyQ:new()
NoisyQInst:Init()
| mit |
OctoEnigma/shiny-octo-system | lua/vgui/dnumslider.lua | 1 | 5287 |
local PANEL = {}
function PANEL:Init()
self.TextArea = self:Add( "DTextEntry" )
self.TextArea:Dock( RIGHT )
self.TextArea:SetPaintBackground( false )
self.TextArea:SetWide( 45 )
self.TextArea:SetNumeric( true )
self.TextArea.OnChange = function( textarea, val ) self:SetValue( self.TextArea:GetText() ) end
-- Causes automatic clamp to min/max, disabled for now. TODO: Enforce this with a setter/getter?
--self.TextArea.OnEnter = function( textarea, val ) textarea:SetText( self.Scratch:GetTextValue() ) end -- Update the text
self.Slider = self:Add( "DSlider", self )
self.Slider:SetLockY( 0.5 )
self.Slider.TranslateValues = function( slider, x, y ) return self:TranslateSliderValues( x, y ) end
self.Slider:SetTrapInside( true )
self.Slider:Dock( FILL )
self.Slider:SetHeight( 16 )
Derma_Hook( self.Slider, "Paint", "Paint", "NumSlider" )
self.Label = vgui.Create ( "DLabel", self )
self.Label:Dock( LEFT )
self.Label:SetMouseInputEnabled( true )
self.Scratch = self.Label:Add( "DNumberScratch" )
self.Scratch:SetImageVisible( false )
self.Scratch:Dock( FILL )
self.Scratch.OnValueChanged = function() self:ValueChanged( self.Scratch:GetFloatValue() ) end
self:SetTall( 32 )
self:SetMin( 0 )
self:SetMax( 1 )
self:SetDecimals( 2 )
self:SetText( "" )
self:SetValue( 0.5 )
--
-- You really shouldn't be messing with the internals of these controls from outside..
-- .. but if you are, this might stop your code from fucking us both.
--
self.Wang = self.Scratch
end
function PANEL:SetMinMax( min, max )
self.Scratch:SetMin( tonumber( min ) )
self.Scratch:SetMax( tonumber( max ) )
self:UpdateNotches()
end
function PANEL:SetDark( b )
self.Label:SetDark( b )
end
function PANEL:GetMin()
return self.Scratch:GetMin()
end
function PANEL:GetMax()
return self.Scratch:GetMax()
end
function PANEL:GetRange()
return self:GetMax() - self:GetMin()
end
function PANEL:SetMin( min )
if ( !min ) then min = 0 end
self.Scratch:SetMin( tonumber( min ) )
self:UpdateNotches()
end
function PANEL:SetMax( max )
if ( !max ) then max = 0 end
self.Scratch:SetMax( tonumber( max ) )
self:UpdateNotches()
end
function PANEL:SetValue( val )
val = math.Clamp( tonumber( val ) || 0, self:GetMin(), self:GetMax() )
if ( self:GetValue() == val ) then return end
self.Scratch:SetValue( val ) -- This will also call ValueChanged
self:ValueChanged( self:GetValue() ) -- In most cases this will cause double execution of OnValueChanged
end
function PANEL:GetValue()
return self.Scratch:GetFloatValue()
end
function PANEL:SetDecimals( d )
self.Scratch:SetDecimals( d )
self:UpdateNotches()
self:ValueChanged( self:GetValue() ) -- Update the text
end
function PANEL:GetDecimals()
return self.Scratch:GetDecimals()
end
--
-- Are we currently changing the value?
--
function PANEL:IsEditing()
return self.Scratch:IsEditing() || self.TextArea:IsEditing() || self.Slider:IsEditing()
end
function PANEL:PerformLayout()
self.Label:SetWide( self:GetWide() / 2.4 )
end
function PANEL:SetConVar( cvar )
self.Scratch:SetConVar( cvar )
self.TextArea:SetConVar( cvar )
end
function PANEL:SetText( text )
self.Label:SetText( text )
end
function PANEL:ValueChanged( val )
val = math.Clamp( tonumber( val ) || 0, self:GetMin(), self:GetMax() )
if ( self.TextArea != vgui.GetKeyboardFocus() ) then
self.TextArea:SetValue( self.Scratch:GetTextValue() )
end
self.Slider:SetSlideX( self.Scratch:GetFraction( val ) )
self:OnValueChanged( val )
end
function PANEL:OnValueChanged( val )
-- For override
end
function PANEL:TranslateSliderValues( x, y )
self:SetValue( self.Scratch:GetMin() + ( x * self.Scratch:GetRange() ) )
return self.Scratch:GetFraction(), y
end
function PANEL:GetTextArea()
return self.TextArea
end
function PANEL:UpdateNotches()
local range = self:GetRange()
self.Slider:SetNotches( nil )
if ( range < self:GetWide() / 4 ) then
return self.Slider:SetNotches( range )
else
self.Slider:SetNotches( self:GetWide() / 4 )
end
end
function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height )
local ctrl = vgui.Create( ClassName )
ctrl:SetWide( 200 )
ctrl:SetMin( 1 )
ctrl:SetMax( 10 )
ctrl:SetText( "Example Slider!" )
ctrl:SetDecimals( 0 )
PropertySheet:AddSheet( ClassName, ctrl, nil, true, true )
end
derma.DefineControl( "DNumSlider", "Menu Option Line", table.Copy( PANEL ), "Panel" )
-- No example for this fella
PANEL.GenerateExample = nil
function PANEL:PostMessage( name, _, val )
if ( name == "SetInteger" ) then
if ( val == "1" ) then
self:SetDecimals( 0 )
else
self:SetDecimals( 2 )
end
end
if ( name == "SetLower" ) then
self:SetMin( tonumber( val ) )
end
if ( name == "SetHigher" ) then
self:SetMax( tonumber( val ) )
end
if ( name == "SetValue" ) then
self:SetValue( tonumber( val ) )
end
end
function PANEL:PerformLayout()
self.Scratch:SetVisible( false )
self.Label:SetVisible( false )
self.Slider:StretchToParent( 0, 0, 0, 0 )
self.Slider:SetSlideX( self.Scratch:GetFraction() )
end
function PANEL:SetActionFunction( func )
self.OnValueChanged = function( self, val ) func( self, "SliderMoved", val, 0 ) end
end
-- Compat
derma.DefineControl( "Slider", "Backwards Compatibility", PANEL, "Panel" )
| mit |
RunAwayDSP/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Knuckles.lua | 9 | 1185 | -----------------------------------
-- Area: Dynamis - Xarcabard
-- Mob: Animated Knuckles
-----------------------------------
require("scripts/globals/status");
local ID = require("scripts/zones/Dynamis-Xarcabard/IDs");
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(108,1571,1000);
else
SetDropRate(108,1571,0);
end
target:showText(mob,ID.text.ANIMATED_KNUCKLES_DIALOG);
SpawnMob(17330309):updateEnmity(target);
SpawnMob(17330310):updateEnmity(target);
SpawnMob(17330311):updateEnmity(target);
SpawnMob(17330319):updateEnmity(target);
SpawnMob(17330320):updateEnmity(target);
SpawnMob(17330321):updateEnmity(target);
end;
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
function onMobDisengage(mob)
mob:showText(mob,ID.text.ANIMATED_KNUCKLES_DIALOG+2);
end;
function onMobDeath(mob, player, isKiller)
player:showText(mob,ID.text.ANIMATED_KNUCKLES_DIALOG+1);
DespawnMob(17330309);
DespawnMob(17330310);
DespawnMob(17330311);
DespawnMob(17330319);
DespawnMob(17330320);
DespawnMob(17330321);
end; | gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Bearclaw_Pinnacle/bcnms/flames_for_the_dead.lua | 9 | 1404 | -----------------------------------
-- Flames for the Dead
-- Bearclaw Pinnacle mission battlefield
-----------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/missions")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:getCurrentMission(COP) ~= dsp.mission.id.cop.THREE_PATHS or player:getCharVar("COP_Ulmia_s_Path") ~= 6) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
if player:getCurrentMission(COP) == dsp.mission.id.cop.THREE_PATHS and player:getCharVar("COP_Ulmia_s_Path") == 6 then
player:setCharVar("COP_Ulmia_s_Path", 7)
end
player:addExp(1000)
end
end
| gpl-3.0 |
OctoEnigma/shiny-octo-system | gamemodes/darkrp/gamemode/modules/fadmin/fadmin/messaging/cl_init.lua | 7 | 5817 | local showChat = CreateClientConVar("FAdmin_ShowChatNotifications", 1, true, false)
local HUDNote_c = 0
local HUDNote_i = 1
local HUDNotes = {}
--Notify ripped off the Sandbox notify, changed to my likings
function FAdmin.Messages.AddMessage(MsgType, Message)
local tab = {}
tab.text = Message
tab.recv = SysTime()
tab.velx = 0
tab.vely = -5
surface.SetFont("GModNotify")
local w, _ = surface.GetTextSize( Message )
tab.x = ScrW() / 2 + w * 0.5 + (ScrW() / 20)
tab.y = ScrH()
tab.a = 255
local MsgTypeNames = {"ERROR", "NOTIFY", "QUESTION", "GOOD", "BAD"}
if not MsgTypeNames[MsgType] then return end
tab.col = FAdmin.Messages.MsgTypes[MsgTypeNames[MsgType]].COLOR
table.insert( HUDNotes, tab )
HUDNote_c = HUDNote_c + 1
HUDNote_i = HUDNote_i + 1
LocalPlayer():EmitSound("npc/turret_floor/click1.wav", 30, 100)
end
usermessage.Hook("FAdmin_SendMessage", function(u) FAdmin.Messages.AddMessage(u:ReadShort(), u:ReadString()) end)
local function DrawNotice(k, v, i)
local H = ScrH() / 1024
local x = v.x - 75 * H
local y = v.y - 27
surface.SetFont("GModNotify")
local w, h = surface.GetTextSize(v.text)
h = h + 16
local col = v.col
draw.RoundedBox(4, x - w - h + 24, y - 8, w + h - 16, h, col)
-- Draw Icon
surface.SetDrawColor(255, 255, 255, v.a)
draw.DrawNonParsedSimpleText(v.text, "GModNotify", x + 1, y + 1, Color(0, 0, 0, v.a * 0.8), TEXT_ALIGN_RIGHT)
draw.DrawNonParsedSimpleText(v.text, "GModNotify", x - 1, y - 1, Color(0, 0, 0, v.a * 0.5), TEXT_ALIGN_RIGHT)
draw.DrawNonParsedSimpleText(v.text, "GModNotify", x + 1, y - 1, Color(0, 0, 0, v.a * 0.6), TEXT_ALIGN_RIGHT)
draw.DrawNonParsedSimpleText(v.text, "GModNotify", x - 1, y + 1, Color(0, 0, 0, v.a * 0.6), TEXT_ALIGN_RIGHT)
draw.DrawNonParsedSimpleText(v.text, "GModNotify", x, y, Color(255, 255, 255, v.a), TEXT_ALIGN_RIGHT)
local ideal_y = ScrH() - (HUDNote_c - i) * h
local ideal_x = ScrW() / 2 + w * 0.5 + (ScrW() / 20)
local timeleft = 6 - (SysTime() - v.recv)
-- Cartoon style about to go thing
if (timeleft < 0.8) then
ideal_x = ScrW() / 2 + w * 0.5 + 200
end
-- Gone!
if (timeleft < 0.5) then
ideal_y = ScrH() + 50
end
local spd = RealFrameTime() * 15
v.y = v.y + v.vely * spd
v.x = v.x + v.velx * spd
local dist = ideal_y - v.y
v.vely = v.vely + dist * spd * 1
if (math.abs(dist) < 2 and math.abs(v.vely) < 0.1) then
v.vely = 0
end
dist = ideal_x - v.x
v.velx = v.velx + dist * spd * 1
if math.abs(dist) < 2 and math.abs(v.velx) < 0.1 then
v.velx = 0
end
-- Friction.. kind of FPS independant.
v.velx = v.velx * (0.95 - RealFrameTime() * 8)
v.vely = v.vely * (0.95 - RealFrameTime() * 8)
end
local function HUDPaint()
if not HUDNotes then return end
local i = 0
for k, v in pairs(HUDNotes) do
if v ~= 0 then
i = i + 1
DrawNotice(k, v, i)
end
end
for k, v in pairs(HUDNotes) do
if v ~= 0 and v.recv + 6 < SysTime() then
HUDNotes[k] = 0
HUDNote_c = HUDNote_c - 1
if HUDNote_c == 0 then
HUDNotes = {}
end
end
end
end
hook.Add("HUDPaint", "FAdmin_MessagePaint", HUDPaint)
local function ConsoleMessage(um)
MsgC(Color(255, 0, 0, 255), "(FAdmin) ", Color(200, 0, 200, 255), um:ReadString() .. "\n")
end
usermessage.Hook("FAdmin_ConsoleMessage", ConsoleMessage)
local red = Color(255, 0, 0)
local white = Color(190, 190, 190)
local brown = Color(102, 51, 0)
local blue = Color(102, 0, 255)
-- Inserts the instigator into a notification message
local function insertInstigator(res, instigator, _)
table.insert(res, brown)
table.insert(res, FAdmin.PlayerName(instigator))
end
-- Inserts the targets into the notification message
local function insertTargets(res, _, targets)
table.insert(res, blue)
table.insert(res, FAdmin.TargetsToString(targets))
end
local modMessage = {
instigator = insertInstigator,
you = function(res) table.insert(res, brown) table.insert(res, "you") end,
targets = insertTargets,
}
local function showNotification(notification, instigator, targets, extraInfo)
local res = {red, "[", white, "FAdmin", red, "] "}
for _, text in pairs(notification.message) do
if modMessage[text] then modMessage[text](res, instigator, targets) continue end
if string.sub(text, 1, 10) == "extraInfo." then
local id = tonumber(string.sub(text, 11))
table.insert(res, notification.extraInfoColors and notification.extraInfoColors[id] or white)
table.insert(res, extraInfo[id])
continue
end
table.insert(res, white)
table.insert(res, text)
end
if showChat:GetBool() then
chat.AddText(unpack(res))
else
local msgTbl = {}
for i = 8, #res, 2 do table.insert(msgTbl, res[i]) end
FAdmin.Messages.AddMessage(FAdmin.Messages.MsgTypesByName[notification.msgType], table.concat(msgTbl, ""))
MsgC(unpack(res))
Msg("\n")
end
end
local function receiveNotification()
local id = net.ReadUInt(16)
local notification = FAdmin.Notifications[id]
local instigator = net.ReadEntity()
local targets = {}
if notification.hasTarget then
local targetCount = net.ReadUInt(8)
for i = 1, targetCount do
table.insert(targets, net.ReadEntity())
end
end
local extraInfo = notification.readExtraInfo and notification.readExtraInfo()
showNotification(notification, instigator, targets, extraInfo)
end
net.Receive("FAdmin_Notification", receiveNotification)
| mit |
lichtl/darkstar | scripts/globals/items/bowl_of_ulbuconut_milk_+1.lua | 18 | 1195 | -----------------------------------------
-- ID: 5977
-- Item: Bowl of Ulbuconut Milk +1
-- Food Effect: 3Min, All Races
-----------------------------------------
-- Charisma +4
-- Vitality -1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,180,5977);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_CHR, 4);
target:addMod(MOD_VIT, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_CHR, 4);
target:delMod(MOD_VIT, -1);
end;
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/items/beluga.lua | 12 | 1066 | -----------------------------------------
-- ID: Beluga
-- Beluga
-- Additional Effect: Ice Damage
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10
if (math.random(0,99) >= chance) then
return 0,0,0
else
local dmg = math.random(7,21)
local params = {}
params.bonusmab = 0
params.includemab = false
dmg = addBonusesAbility(player, dsp.magic.ele.WATER, target, dmg, params)
dmg = dmg * applyResistanceAddEffect(player,target,dsp.magic.ele.WATER,0)
dmg = adjustForTarget(target,dmg,dsp.magic.ele.WATER)
dmg = finalMagicNonSpellAdjustments(player,target,dsp.magic.ele.WATER,dmg)
local message = dsp.msg.basic.ADD_EFFECT_DMG
if (dmg < 0) then
message = dsp.msg.basic.ADD_EFFECT_HEAL
end
return dsp.subEffect.WATER_DAMAGE,message,dmg
end
end | gpl-3.0 |
ShahriyarB/Warcraft-Lua-Engine-2 | luasocket-master/test/testmesg.lua | 45 | 2957 | -- load the smtp support and its friends
local smtp = require("socket.smtp")
local mime = require("mime")
local ltn12 = require("ltn12")
function filter(s)
if s then io.write(s) end
return s
end
source = smtp.message {
headers = { ['content-type'] = 'multipart/alternative' },
body = {
[1] = {
headers = { ['Content-type'] = 'text/html' },
body = "<html> <body> Hi, <b>there</b>...</body> </html>"
},
[2] = {
headers = { ['content-type'] = 'text/plain' },
body = "Hi, there..."
}
}
}
r, e = smtp.send{
rcpt = {"<diego@tecgraf.puc-rio.br>",
"<diego@princeton.edu>" },
from = "<diego@princeton.edu>",
source = ltn12.source.chain(source, filter),
--server = "mail.cs.princeton.edu"
server = "localhost",
port = 2525
}
print(r, e)
-- creates a source to send a message with two parts. The first part is
-- plain text, the second part is a PNG image, encoded as base64.
source = smtp.message{
headers = {
-- Remember that headers are *ignored* by smtp.send.
from = "Sicrano <sicrano@tecgraf.puc-rio.br>",
to = "Fulano <fulano@tecgraf.puc-rio.br>",
subject = "Here is a message with attachments"
},
body = {
preamble = "If your client doesn't understand attachments, \r\n" ..
"it will still display the preamble and the epilogue.\r\n" ..
"Preamble might show up even in a MIME enabled client.",
-- first part: No headers means plain text, us-ascii.
-- The mime.eol low-level filter normalizes end-of-line markers.
[1] = {
body = mime.eol(0, [[
Lines in a message body should always end with CRLF.
The smtp module will *NOT* perform translation. It will
perform necessary stuffing, though.
]])
},
-- second part: Headers describe content the to be an image,
-- sent under the base64 transfer content encoding.
-- Notice that nothing happens until the message is sent. Small
-- chunks are loaded into memory and translation happens on the fly.
[2] = {
headers = {
["ConTenT-tYpE"] = 'image/png; name="luasocket.png"',
["content-disposition"] = 'attachment; filename="luasocket.png"',
["content-description"] = 'our logo',
["content-transfer-encoding"] = "BASE64"
},
body = ltn12.source.chain(
ltn12.source.file(io.open("luasocket.png", "rb")),
ltn12.filter.chain(
mime.encode("base64"),
mime.wrap()
)
)
},
epilogue = "This might also show up, but after the attachments"
}
}
r, e = smtp.send{
rcpt = {"<diego@tecgraf.puc-rio.br>",
"<diego@princeton.edu>" },
from = "<diego@princeton.edu>",
source = ltn12.source.chain(source, filter),
--server = "mail.cs.princeton.edu",
--port = 25
server = "localhost",
port = 2525
}
print(r, e)
| gpl-2.0 |
RunAwayDSP/darkstar | scripts/globals/weaponskills/blade_to.lua | 10 | 1417 | -----------------------------------
-- Blade To
-- Katana weapon skill
-- Skill Level: 100
-- Deals ice elemental damage. Damage varies with TP.
-- Aligned with the Snow Gorget & Breeze Gorget.
-- Aligned with the Snow Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: STR:30% INT:30%
-- 100%TP 200%TP 300%TP
-- 0.50 0.75 1.00
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 0.5 params.ftp200 = 0.75 params.ftp300 = 1
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.3 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1 params.atk200 = 1 params.atk300 = 1
params.hybridWS = true
params.ele = dsp.magic.ele.ICE
params.skill = dsp.skill.KATANA
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4 params.int_wsc = 0.4
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Port_San_dOria/npcs/Portaure.lua | 9 | 1160 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Portaure
-- Standard Info NPC
-----------------------------------
local ID = require("scripts/zones/Port_San_dOria/IDs");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getCharVar("tradePortaure") == 0) then
player:messageSpecial(ID.text.PORTAURE_DIALOG);
player:addCharVar("FFR", -1)
player:setCharVar("tradePortaure",1);
player:messageSpecial(ID.text.FLYER_ACCEPTED);
player:messageSpecial(ID.text.FLYERS_HANDED,17 - player:getCharVar("FFR"));
player:tradeComplete();
elseif (player:getCharVar("tradePortaure") ==1) then
player:messageSpecial(ID.text.FLYER_ALREADY);
end
end
end;
function onTrigger(player,npc)
player:startEvent(651);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/items/bowl_of_goulash.lua | 11 | 1252 | -----------------------------------------
-- ID: 5750
-- Item: bowl_of_goulash
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- VIT +3
-- INT -2
-- Accuracy +10% (cap 54)
-- DEF +10% (cap 30)
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5750)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.VIT, 3)
target:addMod(dsp.mod.INT, -2)
target:addMod(dsp.mod.FOOD_ACCP, 10)
target:addMod(dsp.mod.FOOD_ACC_CAP, 54)
target:addMod(dsp.mod.FOOD_DEFP, 10)
target:addMod(dsp.mod.FOOD_DEF_CAP, 30)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.VIT, 3)
target:delMod(dsp.mod.INT, -2)
target:delMod(dsp.mod.FOOD_ACCP, 10)
target:delMod(dsp.mod.FOOD_ACC_CAP, 54)
target:delMod(dsp.mod.FOOD_DEFP, 10)
target:delMod(dsp.mod.FOOD_DEF_CAP, 30)
end
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/weaponskills/avalanche_axe.lua | 10 | 1392 | -----------------------------------
-- Avalanche Axe
-- Axe weapon skill
-- Skill level: 100
-- Delivers a single-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Soil Gorget & Thunder Gorget.
-- Aligned with the Soil Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.50 2.00 2.50
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 1.5 params.ftp200 = 2 params.ftp300 = 2.5
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.0 params.chr_wsc = 0.0
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.6
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
mertaytore/koding | go/src/vendor/github.com/caglar10ur/lxc/src/lxc/lxc-top.lua | 62 | 7453 | #!/usr/bin/env lua
--
-- top(1) like monitor for lxc containers
--
-- Copyright © 2012 Oracle.
--
-- Authors:
-- Dwight Engen <dwight.engen@oracle.com>
--
-- This library is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License version 2, as
-- published by the Free Software Foundation.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program; if not, write to the Free Software Foundation, Inc.,
-- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--
local lxc = require("lxc")
local core = require("lxc.core")
local getopt = require("alt_getopt")
local USER_HZ = 100
local ESC = string.format("%c", 27)
local TERMCLEAR = ESC.."[H"..ESC.."[J"
local TERMNORM = ESC.."[0m"
local TERMBOLD = ESC.."[1m"
local TERMRVRS = ESC.."[7m"
local containers = {}
local stats = {}
local stats_total = {}
local max_containers
function printf(...)
local function wrapper(...) io.write(string.format(...)) end
local status, result = pcall(wrapper, ...)
if not status then
error(result, 2)
end
end
function string:split(delim, max_cols)
local cols = {}
local start = 1
local nextc
repeat
nextc = string.find(self, delim, start)
if (nextc and #cols ~= max_cols - 1) then
table.insert(cols, string.sub(self, start, nextc-1))
start = nextc + #delim
else
table.insert(cols, string.sub(self, start, string.len(self)))
nextc = nil
end
until nextc == nil or start > #self
return cols
end
function strsisize(size, width)
local KiB = 1024
local MiB = 1048576
local GiB = 1073741824
local TiB = 1099511627776
local PiB = 1125899906842624
local EiB = 1152921504606846976
local ZiB = 1180591620717411303424
if (size >= ZiB) then
return string.format("%d.%2.2d ZB", size / ZiB, (math.floor(size % ZiB) * 100) / ZiB)
end
if (size >= EiB) then
return string.format("%d.%2.2d EB", size / EiB, (math.floor(size % EiB) * 100) / EiB)
end
if (size >= PiB) then
return string.format("%d.%2.2d PB", size / PiB, (math.floor(size % PiB) * 100) / PiB)
end
if (size >= TiB) then
return string.format("%d.%2.2d TB", size / TiB, (math.floor(size % TiB) * 100) / TiB)
end
if (size >= GiB) then
return string.format("%d.%2.2d GB", size / GiB, (math.floor(size % GiB) * 100) / GiB)
end
if (size >= MiB) then
return string.format("%d.%2.2d MB", size / MiB, (math.floor(size % MiB) * 1000) / (MiB * 10))
end
if (size >= KiB) then
return string.format("%d.%2.2d KB", size / KiB, (math.floor(size % KiB) * 1000) / (KiB * 10))
end
return string.format("%3d.00 ", size)
end
function tty_lines()
local rows = 25
local f = assert(io.popen("stty -a | head -n 1"))
for line in f:lines() do
local stty_rows
_,_,stty_rows = string.find(line, "rows (%d+)")
if (stty_rows ~= nil) then
rows = stty_rows
break
end
end
f:close()
return rows
end
function container_sort(a, b)
if (optarg["r"]) then
if (optarg["s"] == "n") then return (a > b)
elseif (optarg["s"] == "c") then return (stats[a].cpu_use_nanos < stats[b].cpu_use_nanos)
elseif (optarg["s"] == "d") then return (stats[a].blkio < stats[b].blkio)
elseif (optarg["s"] == "m") then return (stats[a].mem_used < stats[b].mem_used)
elseif (optarg["s"] == "k") then return (stats[a].kmem_used < stats[b].kmem_used)
end
else
if (optarg["s"] == "n") then return (a < b)
elseif (optarg["s"] == "c") then return (stats[a].cpu_use_nanos > stats[b].cpu_use_nanos)
elseif (optarg["s"] == "d") then return (stats[a].blkio > stats[b].blkio)
elseif (optarg["s"] == "m") then return (stats[a].mem_used > stats[b].mem_used)
elseif (optarg["s"] == "k") then return (stats[a].kmem_used > stats[b].kmem_used)
end
end
end
function container_list_update()
local now_running
now_running = lxc.containers_running(true)
-- check for newly started containers
for _,v in ipairs(now_running) do
if (containers[v] == nil) then
local ct = lxc.container:new(v)
-- note, this is a "mixed" table, ie both dictionary and list
containers[v] = ct
table.insert(containers, v)
end
end
-- check for newly stopped containers
local indx = 1
while (indx <= #containers) do
local ctname = containers[indx]
if (now_running[ctname] == nil) then
containers[ctname] = nil
stats[ctname] = nil
table.remove(containers, indx)
else
indx = indx + 1
end
end
-- get stats for all current containers and resort the list
lxc.stats_clear(stats_total)
for _,ctname in ipairs(containers) do
stats[ctname] = containers[ctname]:stats_get(stats_total)
end
table.sort(containers, container_sort)
end
function stats_print_header(stats_total)
printf(TERMRVRS .. TERMBOLD)
printf("%-15s %8s %8s %8s %10s %10s", "Container", "CPU", "CPU", "CPU", "BlkIO", "Mem")
if (stats_total.kmem_used > 0) then printf(" %10s", "KMem") end
printf("\n")
printf("%-15s %8s %8s %8s %10s %10s", "Name", "Used", "Sys", "User", "Total", "Used")
if (stats_total.kmem_used > 0) then printf(" %10s", "Used") end
printf("\n")
printf(TERMNORM)
end
function stats_print(name, stats, stats_total)
printf("%-15s %8.2f %8.2f %8.2f %10s %10s",
name,
stats.cpu_use_nanos / 1000000000,
stats.cpu_use_sys / USER_HZ,
stats.cpu_use_user / USER_HZ,
strsisize(stats.blkio),
strsisize(stats.mem_used))
if (stats_total.kmem_used > 0) then
printf(" %10s", strsisize(stats.kmem_used))
end
end
function usage()
printf("Usage: lxc-top [options]\n" ..
" -h|--help print this help message\n" ..
" -m|--max display maximum number of containers\n" ..
" -d|--delay delay in seconds between refreshes (default: 3.0)\n" ..
" -s|--sort sort by [n,c,d,m] (default: n) where\n" ..
" n = Name\n" ..
" c = CPU use\n" ..
" d = Disk I/O use\n" ..
" m = Memory use\n" ..
" k = Kernel memory use\n" ..
" -r|--reverse sort in reverse (descending) order\n"
)
os.exit(1)
end
local long_opts = {
help = "h",
delay = "d",
max = "m",
reverse = "r",
sort = "s",
}
optarg,optind = alt_getopt.get_opts (arg, "hd:m:rs:", long_opts)
optarg["d"] = tonumber(optarg["d"]) or 3.0
optarg["m"] = tonumber(optarg["m"]) or tonumber(tty_lines() - 3)
optarg["r"] = optarg["r"] or false
optarg["s"] = optarg["s"] or "n"
if (optarg["h"] ~= nil) then
usage()
end
while true
do
container_list_update()
-- if some terminal we care about doesn't support the simple escapes, we
-- may fall back to this, or ncurses. ug.
--os.execute("tput clear")
printf(TERMCLEAR)
stats_print_header(stats_total)
for index,ctname in ipairs(containers) do
stats_print(ctname, stats[ctname], stats_total)
printf("\n")
if (index >= optarg["m"]) then
break
end
end
stats_print(string.format("TOTAL (%-2d)", #containers), stats_total, stats_total)
io.flush()
core.usleep(optarg["d"] * 1000000)
end
| agpl-3.0 |
lichtl/darkstar | scripts/zones/RaKaznar_Inner_Court/Zone.lua | 33 | 1290 | -----------------------------------
--
-- Zone: Ra’Kanzar Inner Court (276)
--
-----------------------------------
package.loaded["scripts/zones/RaKaznar_Inner_Court/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/RaKaznar_Inner_Court/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-476,-520.5,20,0);
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 |
OctoEnigma/shiny-octo-system | lua/vgui/dcolorbutton.lua | 1 | 1552 |
local PANEL = {}
local matGrid = Material( "gui/alpha_grid.png", "nocull" )
AccessorFunc( PANEL, "m_bBorder", "DrawBorder", FORCE_BOOL )
AccessorFunc( PANEL, "m_bSelected", "Selected", FORCE_BOOL )
AccessorFunc( PANEL, "m_Color", "Color" )
AccessorFunc( PANEL, "m_PanelID", "ID" )
function PANEL:Init()
self:SetSize( 10, 10 )
self:SetMouseInputEnabled( true )
self:SetText( "" )
self:SetCursor( "hand" )
self:SetZPos( 0 )
self:SetColor( Color( 255, 0, 255 ) )
end
function PANEL:IsDown()
return self.Depressed
end
function PANEL:SetColor( color )
local colorStr = "R: " .. color.r .. "\nG: " .. color.g .. "\nB: " .. color.b .. "\nA: " .. color.a
self:SetTooltip( colorStr )
self.m_Color = color
end
function PANEL:Paint( w, h )
if ( self:GetColor().a < 255 ) then -- Grid for Alpha
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( matGrid )
local size = math.max( 128, math.max( w, h ) )
local x, y = w / 2 - size / 2, h / 2 - size / 2
surface.DrawTexturedRect( x, y , size, size )
end
surface.SetDrawColor( self:GetColor() )
self:DrawFilledRect()
surface.SetDrawColor( 0, 0, 0, 200 )
surface.DrawRect( 0, 0, w, 1 )
surface.DrawRect( 0, 0, 1, h )
return false
end
function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height )
local ctrl = vgui.Create( ClassName )
ctrl:SetSize( 64, 64 )
ctrl:SetColor( Color( 255, 0, 0, 128 ) )
PropertySheet:AddSheet( ClassName, ctrl, nil, true, true )
end
derma.DefineControl( "DColorButton", "A Color Button", PANEL, "DLabel" )
| mit |
lichtl/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Travonce.lua | 14 | 1060 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Travonce
-- Type: Standard NPC
-- @zone 26
-- @pos -89.068 -14.367 -0.030
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00d2);
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 |
grehujt/RestfulApiServer | ngx/lua/handle_tables.lua | 1 | 2173 |
local lbs = lbs
local find = string.find
local method = ngx.req.get_method()
if method == "GET" then
local getArgs = ngx.ctx.qs
if getArgs==nil then
getArgs = ngx.req.get_uri_args()
end
local proj = "*"
if getArgs.proj then
proj = getArgs.proj
if find(proj," ") then
return ngx.exit(500)
end
end
local where = ""
if getArgs.where then
where = getArgs.where
if find(where,";") then
return ngx.exit(500)
end
end
local limit = ""
if getArgs.limit then
limit = getArgs.limit
if find(limit,";") then
return ngx.exit(500)
end
end
if #limit>0 then
where = where.." "..limit
end
lbs:select("lbs_"..ngx.var.db,ngx.var.table,proj,where)
else
local args = ngx.ctx['body']
if args==nil then
local decode = decode
ngx.req.read_body()
local tmp = ngx.req.get_body_data()
args = decode(tmp)
end
if not args then return end
if method == "POST" then
local tmp1 = {}
local tmp2 = {}
for key,value in pairs(args) do
if key~="auth" and key~="ver" then
table.insert(tmp1,key)
table.insert(tmp2,ngx.quote_sql_str(value))
end
end
if #tmp1==0 or #tmp2==0 or #tmp1~=#tmp2 then
-- ngx.say("POST invalid: no para")
return ngx.exit(500)
end
lbs:insert("lbs_"..ngx.var.db,ngx.var.table,tmp1,tmp2)
elseif method == "PUT" then
local tmp1 = {}
local tmp2 = {}
local tmp3 = {}
local idx = 1
for key,value in pairs(args) do
if key~="auth" and key~="ver" then
tmp1[idx] = key
tmp2[idx] = ngx.quote_sql_str(value)
tmp3[idx] = key.."=VALUES("..key..")"
idx = idx+1
end
end
if #tmp1==0 or #tmp2==0 or #tmp1~=#tmp2 then
-- ngx.say("PUT invalid: no para")
return ngx.exit(500)
end
lbs:upsert("lbs_"..ngx.var.db,ngx.var.table,tmp1,tmp2,tmp3)
end
end
| mit |
lichtl/darkstar | scripts/zones/Port_Bastok/npcs/Numa.lua | 17 | 1786 | -----------------------------------
-- Area: Port Bastok
-- NPC: Numa
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,NUMA_SHOP_DIALOG);
stock = {
0x30A9, 5079,1, --Cotton Hachimaki
0x3129, 7654,1, --Cotton Dogi
0x31A9, 4212,1, --Cotton Tekko
0x3229, 6133,1, --Cotton Sitabaki
0x32A9, 3924,1, --Cotton Kyahan
0x3395, 3825,1, --Silver Obi
0x30A8, 759,2, --Hachimaki
0x3128, 1145,2, --Kenpogi
0x31A8, 630,2, --Tekko
0x3228, 915,2, --Sitabaki
0x32A8, 584,2, --Kyahan
0x02C0, 132,2, --Bamboo Stick
0x025D, 180,3, --Pickaxe
0x16EB, 13500,3, --Toolbag (Ino)
0x16EC, 18000,3, --Toolbag (Shika)
0x16ED, 18000,3 --Toolbag (Cho)
}
showNationShop(player, NATION_BASTOK, 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 |
lichtl/darkstar | scripts/zones/Crawlers_Nest/npcs/qm10.lua | 57 | 2127 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: qm10 (??? - Exoray Mold Crumbs)
-- Involved in Quest: In Defiant Challenge
-- @pos -83.391 -8.222 79.065 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Crawlers_Nest/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB1) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(EXORAY_MOLD_CRUMB1);
player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB1);
end
if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1089, 1);
player:messageSpecial(ITEM_OBTAINED, 1089);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089);
end
end
if (player:hasItem(1089)) then
player:delKeyItem(EXORAY_MOLD_CRUMB1);
player:delKeyItem(EXORAY_MOLD_CRUMB2);
player:delKeyItem(EXORAY_MOLD_CRUMB3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/PsoXja/npcs/_09a.lua | 14 | 2875 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _09a (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- @pos 261.600 -1.925 -50.000 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == JOBS.THF) then
local X=player:getXPos();
if (npc:getAnimation() == 9) then
if (X <= 261) then
if (GetMobAction(16814091) == 0) then
local Rand = math.random(1,2); -- estimated 50% success as per the wiki
if (Rand == 1) then -- Spawn Gargoyle
player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true);
SpawnMob(16814091):updateClaim(player); -- Gargoyle
else
player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true);
npc:openDoor(30);
end
player:tradeComplete();
else
player:messageSpecial(DOOR_LOCKED);
end
end
end
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local X=player:getXPos();
if (npc:getAnimation() == 9) then
if (X <= 261) then
if (GetMobAction(16814091) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true);
SpawnMob(16814091):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif (X >= 262) then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Selbina/npcs/Gabwaleid.lua | 14 | 1534 | -----------------------------------
-- Area: Selbina
-- NPC: Gabwaleid
-- Involved in Quest: Riding on the Clouds
-- @pos -17 -7 11 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 4) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_3",0);
player:tradeComplete();
player:addKeyItem(SOMBER_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0258);
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 |
lichtl/darkstar | scripts/globals/mobskills/Calcifying_Deluge.lua | 18 | 1056 | ---------------------------------------------
-- Calcifying Deluge
--
-- Description: Delivers a threefold ranged attack to targets in an area of effect. Additional effect: Petrification
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Unknown
-- Notes: Used only by Medusa.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,MOBPARAM_3_SHADOW);
target:delHP(dmg);
local typeEffect = EFFECT_PETRIFICATION;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 120);
return dmg;
end;
| gpl-3.0 |
PUMpITapp/getsmart | src/gfx.lua | 2 | 2294 | local gfx = {}
--------------------------------------------------------------------------------
--- Surface Class
--------------------------------------------------------------------------------
Surface = {}
function Surface:new(w, h)
o = { cref=surface_new(w, h) }
self.__index = self
return setmetatable(o, self)
end
function Surface:newJPEG(path)
o = { cref=gfx_loadjpeg(path) }
self.__index = self
return setmetatable(o, self)
end
function Surface:newPNG(path)
o = { cref=gfx_loadpng(path) }
self.__index = self
return setmetatable(o, self)
end
function Surface:getDefaultSurface()
o = { cref=surface_get_window_surface() }
self.__index = self
return setmetatable(o, self)
end
function Surface:clear(c, r)
surface_clear(self.cref, c, r)
end
function Surface:fill(c, r)
surface_fill(self.cref, c, r)
end
function Surface:copyfrom(ss, sr, dr, b)
surface_copyfrom(self.cref, ss.cref, sr, dr, b)
end
function Surface:get_width()
return surface_get_width(self.cref)
end
function Surface:get_height()
return surface_get_height(self.cref)
end
function Surface:get_pixel(x, y)
print("Not implemented yet.")
end
function Surface:set_pixel(x, y, c)
print("Not implemented yet.")
end
function Surface:premultiply()
surface_premultiply(self.cref)
end
function Surface:destroy()
surface_destroy(self.cref)
end
--------------------------------------------------------------------------------
--- GFX Module definitions
--------------------------------------------------------------------------------
gfx.screen = Surface:getDefaultSurface()
function gfx.set_auto_update()
return gfx_set_auto_update()
end
function gfx.new_surface(w, h)
if w < 0 or h > 9999 then
error("invalid width")
end
if w < 0 or h > 9999 then
error("invalid height")
end
return Surface:new(w, h)
end
function gfx.get_memory_use()
return gfx_get_memory_use()
end
function gfx.get_memory_limit()
return gfx_get_memory_limit()
end
function gfx.update()
return gfx_update()
end
function gfx.loadpng(path)
local img = Surface:newPNG(path)
if img.cref ~= nil then
return img
end
return nil
end
function gfx.loadjpeg(path)
local img = Surface:newJPEG(path)
if img.cref ~= nil then
return img
end
return nil
end
return gfx
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Arrapago_Reef/npcs/_1ie.lua | 12 | 2591 | -----------------------------------
-- Area: Arrapago Reef
-- Door: Iron Gate (Lamian Fang Key)
-- !pos 580 -17 120
-----------------------------------
local ID = require("scripts/zones/Arrapago_Reef/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/status")
-----------------------------------
function onTrade(player,npc,trade)
if npc:getAnimation() == dsp.anim.CLOSE_DOOR then
if npcUtil.tradeHas(trade, 2219) then
npc:openDoor()
player:messageSpecial(ID.text.KEY_BREAKS,2219)
player:confirmTrade()
elseif npcUtil.tradeHas(trade, 1022) and player:getMainJob() == dsp.job.THF then -- thief's tools
if math.random(1,2) == 1 then -- TODO: figure out actual percentage chance to pick locks; 50% for now
player:messageSpecial(ID.text.LOCK_SUCCESS,1022)
npc:openDoor()
else
player:messageSpecial(ID.text.LOCK_FAIL,1022)
end
player:confirmTrade()
elseif npcUtil.tradeHas(trade, 1023) and player:getMainJob() == dsp.job.THF then -- living key
if math.random(1,2) == 1 then -- TODO: figure out actual percentage chance to pick locks; 50% for now
player:messageSpecial(ID.text.LOCK_SUCCESS,1023)
npc:openDoor()
else
player:messageSpecial(ID.text.LOCK_FAIL,1023)
end
player:confirmTrade()
elseif npcUtil.tradeHas(trade, 1115) and player:getMainJob() == dsp.job.THF then -- skeleton key
if math.random(1,2) == 1 then -- TODO: figure out actual percentage chance to pick locks; 50% for now
player:messageSpecial(ID.text.LOCK_SUCCESS,1115)
npc:openDoor()
else
player:messageSpecial(ID.text.LOCK_FAIL,1115)
end
player:confirmTrade()
end
end
end
function onTrigger(player,npc)
if player:getZPos() < 120 and npc:getAnimation() == dsp.anim.CLOSE_DOOR then
if player:getMainJob() == dsp.job.THF then
player:messageSpecial(ID.text.DOOR_IS_LOCKED2, 2219, 1022) -- message only THF's get
else
player:messageSpecial(ID.text.DOOR_IS_LOCKED, 2219)
end
elseif player:getZPos() >= 120 and npc:getAnimation() == dsp.anim.CLOSE_DOOR then
player:messageSpecial(ID.text.YOU_UNLOCK_DOOR) -- message from "inside" of door
npc:openDoor()
end
end
function onEventUpdate(player,csid,option,target)
end
function onEventFinish(player,csid,option,target)
end | gpl-3.0 |
lichtl/darkstar | scripts/zones/Ilrusi_Atoll/npcs/Excaliace.lua | 30 | 4512 | -----------------------------------
-- Area: Periqia
-- NPC: Excaliace
-----------------------------------
require("scripts/zones/Periqia/IDs");
require("scripts/globals/pathfind");
local start = {-322,-16.5,380};
local startToChoice1 = {
-320.349548, -16.046591, 379.684570
-318.312317, -16.046591, 379.579865
-316.286530, -16.046591, 379.472992
-314.249298, -16.048323, 379.368164
-312.212616, -16.050047, 379.263855
-310.348267, -16.057688, 378.513367
-309.100250, -16.063747, 376.912720
-307.959656, -16.077335, 375.221832
-306.816345, -16.077335, 373.532349
-305.671082, -16.077335, 371.846008
-304.516022, -16.077335, 370.168579
-303.362549, -16.077335, 368.489624
-302.209167, -16.087559, 366.807190
-301.054626, -16.087715, 365.125336
-299.976593, -16.119972, 363.402710
-299.820740, -16.189123, 361.399994
-300.012909, -16.189123, 359.369080
-300.204407, -16.189123, 357.341705
-300.397125, -16.189123, 355.314880
-300.588409, -16.189123, 353.283936
-300.780060, -16.189123, 351.253296
-300.971313, -16.191444, 349.222321
-301.163574, -16.214754, 347.192749
-301.389923, -16.229296, 345.167511
-302.813599, -16.249445, 343.574554
-304.622406, -16.276562, 342.632568
-306.459869, -16.276562, 341.757172
-308.455261, -16.276562, 341.393158
-310.489380, -16.276562, 341.389252
-312.521088, -16.279837, 341.571747
-314.551819, -16.298687, 341.754822
-316.585144, -15.753593, 341.876556
-318.621338, -15.789236, 341.765198
-320.658966, -15.779417, 341.662872
-322.697296, -15.765886, 341.574463
-324.727234, -15.980421, 341.479340
-326.660187, -16.012735, 342.099487
-328.550476, -15.933064, 342.860687
-330.435150, -15.771011, 343.625427
-332.294006, -15.696083, 344.450684
-333.912903, -16.043205, 345.705078
-335.720062, -15.788860, 346.616364
-337.668945, -15.706074, 347.100769
-339.570679, -15.741604, 346.444336
-340.824524, -15.691669, 344.865021
-341.839478, -15.428291, 343.124268
-342.645996, -15.079435, 341.120239
-342.902252, -15.113903, 339.113068
-342.625366, -15.397438, 337.113739
-342.355469, -15.772522, 335.126404
-341.725372, -16.081879, 333.186157
-341.358307, -16.052465, 331.183319
-340.988190, -15.890514, 329.183777
-340.739380, -15.852081, 327.166229
-340.652344, -15.829269, 325.153931
-340.602631, -15.811451, 323.125397
-340.650421, -15.682171, 321.093201
-340.440063, -15.661972, 318.978729
-340.534454, -15.702602, 316.816895
-340.532501, -15.702147, 314.776947
-340.536591, -15.697933, 312.737244
-340.542572, -15.670002, 310.697632
-340.545624, -15.678772, 308.657776
-340.554047, -15.631170, 306.619476
-340.412598, -15.624416, 304.459137
-340.379303, -15.661182, 302.420258
};
function onSpawn(npc)
npc:initNpcAi();
npc:pathThrough(start, PATHFLAG_REPEAT);
end;
function onPath(npc)
local instance = npc:getInstance();
local progress = instance:getProgress();
local chars = instance:getChars();
if (progress == 0) then
for tid,player in pairs(chars) do
if (npc:checkDistance(player) < 10) then
instance:setProgress(1);
npc:messageText(npc,Periqia.text.EXCALIACE_START);
npc:pathThrough(startToChoice1);
end
end
elseif (progress == 1) then
local run = true;
for tid,player in pairs(chars) do
if (npc:checkDistance(player) < 10) then
run = false;
end
end
if (run) then
npc:messageText(npc,Periqia.text.EXCALIACE_RUN);
end
end
-- go back and forth the set path
-- pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
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);
end; | gpl-3.0 |
omid1212/avint | plugins/groupmanager.lua | 3 | 11505 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "Hi\nI Don't Create Groups!\n For Creating Group You Have To Pay 2000 Tomans\nEACH MONTH\nThe Smart Bot Is\n@UltraKing\nFor Order Group Join↙️\nhttps://telegram.me/joinchat/B4ghtgIvpYlMkBZTG57OhQ"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == 'lock' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Plugin to manage group chat.",
usage = {
"!creategroup <group_name> : Create a new group (admin only)",
"!setabout <description> : Set group description",
"!about : Read group description",
"!setrules <rules> : Set group rules",
"!rules : Read group rules",
"!setname <new_name> : Set group name",
"!setphoto : Set group photo",
"!group <lock|unlock> name : Lock/unlock group name",
"!group <lock|unlock> photo : Lock/unlock group photo",
"!group <lock|unlock> member : Lock/unlock group member",
"!group settings : Show group settings"
},
patterns = {
"^!(creategroup) (.*)$",
"^!(setabout) (.*)$",
"^!(about)$",
"^!(setrules) (.*)$",
"^!(rules)$",
"^!(setname) (.*)$",
"^!(setphoto)$",
"^!(group) (lock) (.*)$",
"^!(group) (unlock) (.*)$",
"^!(group) (settings)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end
| gpl-2.0 |
lichtl/darkstar | scripts/zones/RuLude_Gardens/npcs/Tillecoe.lua | 14 | 1050 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Tillecoe
-- Type: Standard NPC
-- @zone 243
-- @pos 38.528 -0.997 -6.363
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0046);
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 |
lichtl/darkstar | scripts/globals/items/roll_of_sylvan_excursion.lua | 18 | 1574 | -----------------------------------------
-- ID: 5551
-- Item: Roll of Sylvan Excursion
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10
-- MP +3% Cap 15
-- Intelligence +3
-- HP Recovered while healing +2
-- MP Recovered while healing +5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5551);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 3);
target:addMod(MOD_FOOD_MP_CAP, 15);
target:addMod(MOD_HP, 10);
target:addMod(MOD_INT, 3);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 3);
target:delMod(MOD_FOOD_MP_CAP, 15);
target:delMod(MOD_HP, 10);
target:delMod(MOD_INT, 3);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
NiLuJe/koreader | frontend/ui/widget/pathchooser.lua | 4 | 6442 | local BD = require("ui/bidi")
local ButtonDialog = require("ui/widget/buttondialog")
local ButtonDialogTitle = require("ui/widget/buttondialogtitle")
local Device = require("device")
local Event = require("ui/event")
local FileChooser = require("ui/widget/filechooser")
local UIManager = require("ui/uimanager")
local ffiutil = require("ffi/util")
local lfs = require("libs/libkoreader-lfs")
local util = require("util")
local _ = require("gettext")
local T = ffiutil.template
local PathChooser = FileChooser:extend{
title = true, -- or a string
-- if let to true, a generic title will be set in init()
no_title = false,
show_path = true,
is_popout = false,
covers_fullscreen = true, -- set it to false if you set is_popout = true
is_borderless = true,
select_directory = true, -- allow selecting directories
select_file = true, -- allow selecting files
show_files = true, -- show files, even if select_file=false
-- (directories are always shown, to allow navigation)
detailed_file_info = true, -- show size and last mod time in Select message (if select_file=true only)
}
function PathChooser:init()
if self.title == true then -- default title depending on options
if self.select_directory and not self.select_file then
self.title = _("Long-press to choose a folder")
elseif not self.select_directory and self.select_file then
self.title = _("Long-press to choose a file")
else
self.title = _("Long-press to choose")
end
end
self.show_hidden = G_reader_settings:isTrue("show_hidden")
if not self.show_files then
self.file_filter = function() return false end -- filter out regular files
end
if self.select_directory then
-- Let FileChooser display "Long-press to choose current folder"
self.show_current_dir_for_hold = true
end
self.title_bar_left_icon = "home"
self.onLeftButtonTap = function()
self:goHome()
end
self.onLeftButtonHold = function()
self:showPlusMenu()
end
FileChooser.init(self)
end
function PathChooser:onMenuSelect(item)
local path = item.path
if path:sub(-2, -1) == "/." then -- with show_current_dir_for_hold
if not Device:isTouchDevice() and self.select_directory then -- let non-touch device can select the folder
return self:onMenuHold(item)
end
-- Don't navigate to same directory
return true
end
path = ffiutil.realpath(path)
if not path then
-- If starting in a no-more existing directory, allow
-- not getting stuck in it
self:changeToPath("/")
return true
end
local attr = lfs.attributes(path)
if not attr then
-- Same as above
self:changeToPath("/")
return true
end
if attr.mode ~= "directory" then
if not Device:isTouchDevice() and self.select_file then -- let non-touch device can select the file
return self:onMenuHold(item)
end
-- Do nothing if Tap on other than directories
return true
end
-- Let this method check permissions and if we can list
-- this directory: we should get at least one item: ".."
local sub_table = self:genItemTableFromPath(path)
if #sub_table > 0 then
self:changeToPath(path)
end
return true
end
function PathChooser:onMenuHold(item)
local path = item.path
if path:sub(-2, -1) == "/." then -- with show_current_dir_for_hold
path = path:sub(1, -3)
end
path = ffiutil.realpath(path)
if not path then
return true
end
local attr = lfs.attributes(path)
if not attr then
return true
end
if attr.mode == "file" and not self.select_file then
return true
end
if attr.mode == "directory" and not self.select_directory then
return true
end
local title
if attr.mode == "file" then
if self.detailed_file_info then
local filesize = util.getFormattedSize(attr.size)
local lastmod = os.date("%Y-%m-%d %H:%M", attr.modification)
title = T(_("Choose this file?\n\n%1\n\nFile size: %2 bytes\nLast modified: %3"),
BD.filepath(path), filesize, lastmod)
else
title = T(_("Choose this file?\n\n%1"), BD.filepath(path))
end
elseif attr.mode == "directory" then
title = T(_("Choose this folder?\n\n%1"), BD.dirpath(path))
else -- just in case we get something else
title = T(_("Choose this path?\n\n%1"), BD.path(path))
end
local onConfirm = self.onConfirm
self.button_dialog = ButtonDialogTitle:new{
title = title,
buttons = {
{
{
text = _("Cancel"),
callback = function()
UIManager:close(self.button_dialog)
end,
},
{
text = _("Choose"),
callback = function()
if onConfirm then
onConfirm(path)
end
UIManager:close(self.button_dialog)
UIManager:close(self)
end,
},
},
},
}
UIManager:show(self.button_dialog)
return true
end
function PathChooser:showPlusMenu()
local button_dialog
button_dialog = ButtonDialog:new{
buttons = {
{
{
text = _("Folder shortcuts"),
callback = function()
UIManager:close(button_dialog)
UIManager:broadcastEvent(Event:new("ShowFolderShortcutsDialog",
function(path) self:changeToPath(path) end))
end,
},
},
{
{
text = _("New folder"),
callback = function()
UIManager:close(button_dialog)
local FileManager = require("apps/filemanager/filemanager")
FileManager.file_chooser = self
FileManager:createFolder()
end,
},
},
},
}
UIManager:show(button_dialog)
end
return PathChooser
| agpl-3.0 |
lichtl/darkstar | scripts/zones/Norg/npcs/Achika.lua | 14 | 1299 | -----------------------------------
-- Area: Norg
-- NPC: Achika
-- Type: Tenshodo Merchant
-- @pos 1.300 0.000 19.259 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60421,9,23,7)) then
player:showText(npc, ACHIKA_SHOP_DIALOG);
end
else
-- player:startEvent(0x0096);
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 |
sdkbox/sdkbox-facebook-sample-v2 | samples/Lua/TestLua/Resources/luaScript/TouchesTest/TouchesTest.lua | 6 | 3339 | require "luaScript/testResource"
require "luaScript/TouchesTest/Ball"
require "luaScript/TouchesTest/Paddle"
require "luaScript/VisibleRect"
local kHighPlayer = 0
local kLowPlayer = 1
local kStatusBarHeight = 0.0
local kSpriteTag = 0
local m_ball = nil
local m_ballStartingVelocity = nil
local m_paddles = {}
local layer = nil
local function backCallback(sender)
local scene = CCScene:create()
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():replaceScene(scene)
end
local function resetAndScoreBallForPlayer(player)
m_ballStartingVelocity = ccpMult(m_ballStartingVelocity, -1.1);
m_ball:setVelocity( m_ballStartingVelocity );
m_ball:setPosition( VisibleRect:center() );
end
local function doStep(delta)
m_ball:move(delta);
for _,paddle in ipairs(m_paddles) do
if(paddle == nil) then
break
end
m_ball:collideWithPaddle( paddle );
end
local ballPosition = ccp(m_ball:getPosition())
if (ballPosition.y > VisibleRect:top().y - kStatusBarHeight + m_ball:radius()) then
resetAndScoreBallForPlayer( kLowPlayer );
elseif (ballPosition.y < VisibleRect:bottom().y-m_ball:radius()) then
resetAndScoreBallForPlayer( kHighPlayer );
end
m_ball:draw();
end
local function onTouch(event, x, y)
for _,paddle in ipairs(m_paddles) do
if paddle:containsTouchLocation(x,y) == true then
return paddle:onTouch(event, x, y)
end
end
return true
end
local function CreateTouchesLayer()
layer = CCLayer:create()
m_ballStartingVelocity = ccp(20.0, -100.0);
local mgr = CCTextureCache:sharedTextureCache()
local texture = mgr:addImage(s_Ball)
m_ball = Ball.ballWithTexture(texture);
m_ball:setPosition( VisibleRect:center() );
m_ball:setVelocity( m_ballStartingVelocity );
layer:addChild( m_ball );
m_ball:retain();
local paddleTexture = CCTextureCache:sharedTextureCache():addImage(s_Paddle);
local paddlesM = {}
local paddle = Paddle:paddleWithTexture(paddleTexture);
paddle:setPosition( ccp(VisibleRect:center().x, VisibleRect:bottom().y + 15) );
paddlesM[#paddlesM+1] = paddle
paddle = Paddle:paddleWithTexture( paddleTexture );
paddle:setPosition( ccp(VisibleRect:center().x, VisibleRect:top().y - kStatusBarHeight - 15) );
paddlesM[#paddlesM+1] = paddle
paddle = Paddle:paddleWithTexture( paddleTexture );
paddle:setPosition( ccp(VisibleRect:center().x, VisibleRect:bottom().y + 100) );
paddlesM[#paddlesM+1] = paddle
paddle = Paddle:paddleWithTexture( paddleTexture );
paddle:setPosition( ccp(VisibleRect:center().x, VisibleRect:top().y - kStatusBarHeight - 100) );
paddlesM[#paddlesM+1] = paddle
m_paddles = paddlesM
for i = 1,#paddlesM do
paddle = paddlesM[i]
if(paddle == nil) then
break
end
layer:addChild(paddle);
end
-- schedule
layer:scheduleUpdateWithPriorityLua(doStep, 0)
layer:setTouchEnabled(true)
layer:registerScriptTouchHandler(onTouch)
return layer
end
local function nextAction()
return CreateTouchesLayer()
end
function TouchesTest()
local scene = CCScene:create()
scene:addChild(nextAction())
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
lichtl/darkstar | scripts/zones/Lower_Jeuno/npcs/_l10.lua | 7 | 1569 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @zone 245
-- @pos -19 0 -4.625
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
if (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (player:getVar("cService") == 1) then
player:setVar("cService",2);
end
elseif (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (player:getVar("cService") == 14) then
player:setVar("cService",15);
end
end
end
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 |
ld-test/loop | lua/precompiler.lua | 6 | 6255 | #!/usr/bin/env lua
--------------------------------------------------------------------------------
-- @script Lua Script Pre-Compiler
-- @version 1.1
-- @author Renato Maia <maia@tecgraf.puc-rio.br>
--
local assert = assert
local error = error
local ipairs = ipairs
local loadfile = loadfile
local pairs = pairs
local select = select
local io = require "io"
local os = require "os"
local package = require "package"
local string = require "string"
local table = require "table"
module("precompiler", require "loop.compiler.Arguments")
local FILE_SEP = "/"
local FUNC_SEP = "_"
local PATH_SEP = ";"
local PATH_MARK = "?"
help = false
bytecodes = false
names = false
luapath = package.path
output = "precompiled"
prefix = "LUAOPEN_API"
directory = ""
_optpat = "^%-(%-?%w+)(=?)(.-)$"
_alias = { ["-help"] = "help" }
for name in pairs(_M) do
_alias[name:sub(1, 1)] = name
end
local start, errmsg = _M(...)
if not start or help then
if errmsg then io.stderr:write("ERROR: ", errmsg, "\n") end
io.stderr:write([[
Lua Script Pre-Compiler 1.1 Copyright (C) 2006-2008 Tecgraf, PUC-Rio
Usage: ]],_NAME,[[.lua [options] [inputs]
[inputs] is a sequence of names that may be file paths or package names, use
the options described below to indicate how they should be interpreted. If no
[inputs] is provided then such names are read from the standard input.
Options:
-b, -bytecodes Flag that indicates the provided [inputs] are files containing
bytecodes (e.g. instead of source code), like the output of
the 'luac' compiler. When this flag is used no compilation is
performed by this script.
-d, -directory Directory where the output files should be generated. Its
default is the current directory.
-l, -luapath Sequence os path templates used to infer package names from
file paths and vice versa. These templates follows the same
format of the 'package.path' field of Lua. Its default is the
value of 'package.path' that currently is set to:
"]],luapath,[["
-n, -names Flag that indicates provided input names are actually package
names and the real file path should be inferred from
the path defined by -luapath option. This flag can be used in
conjunction with the -bytecodes flag to indicate that inferred
file paths contains bytecodes instead of source code.
-o, -output Name used to form the name of the files generated. Two files
are generated: a source code file with the sufix '.c' with
the pre-compiled scripts and a header file with the sufix
'.h' with function signatures. Its default is ']],output,[['.
-p, -prefix Prefix added to the signature of the functions generated.
Its default is ']],prefix,[['.
]])
os.exit(1)
end
--------------------------------------------------------------------------------
local function escapepattern(pattern)
return pattern:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
end
local filesep = escapepattern(FILE_SEP)
local pathsep = escapepattern(PATH_SEP)
local pathmark = escapepattern(PATH_MARK)
local function adjustpath(path)
if path ~= "" and not path:find(filesep.."$") then
return path..FILE_SEP
end
return path
end
local filepath = adjustpath(directory)..output
--------------------------------------------------------------------------------
local function readinput(file, name)
if bytecodes then
file = assert(io.open(file))
file = file:read("*a"), file:close()
else
file = string.dump(assert(loadfile(file)))
end
return file
end
local template = "[^"..pathsep.."]+"
local function getbytecodes(name)
if names then
local file = name:gsub("%.", FILE_SEP)
local err = {}
for path in luapath:gmatch(template) do
path = path:gsub(pathmark, file)
local file = io.open(path)
if file then
file:close()
return readinput(path)
end
table.insert(err, string.format("\tno file '%s'", path))
end
err = table.concat(err, "\n")
error(string.format("module '%s' not found:\n%s", name, err))
end
return readinput(name)
end
local function allequals(...)
local name = ...
for i = 2, select("#", ...) do
if name ~= select(i, ...) then return nil end
end
return name
end
local function funcname(name)
if not names then
local result
for path in luapath:gmatch(template) do
path = path:gsub(pathmark, "\0")
path = escapepattern(path)
path = path:gsub("%z", "(.-)")
path = string.format("^%s$", path)
result = allequals(name:match(path)) or result
end
if not result then
return nil, "unable to figure package name for file '"..name.."'"
end
return result:gsub(filesep, FUNC_SEP)
end
return name:gsub("%.", FUNC_SEP)
end
--------------------------------------------------------------------------------
local inputs = { select(start, ...) }
if #inputs == 0 then
for name in io.stdin:lines() do
inputs[#inputs+1] = name
end
end
local outc = assert(io.open(filepath..".c", "w"))
local outh = assert(io.open(filepath..".h", "w"))
local guard = output:upper():gsub("[^%w]", "_")
outh:write([[
#ifndef __]],guard,[[__
#define __]],guard,[[__
#include <lua.h>
#ifndef ]],prefix,[[
#define ]],prefix,[[
#endif
]])
outc:write([[
#include <lua.h>
#include <lauxlib.h>
#include "]],output,[[.h"
]])
for i, input in ipairs(inputs) do
local bytecodes = getbytecodes(input)
outc:write("static const unsigned char B",i,"[]={\n")
for j = 1, #bytecodes do
outc:write(string.format("%3u,", bytecodes:byte(j)))
if j % 20 == 0 then outc:write("\n") end
end
outc:write("\n};\n\n")
end
for i, input in ipairs(inputs) do
local func = assert(funcname(input))
outh:write(prefix," int luaopen_",func,"(lua_State *L);\n")
outc:write(
prefix,[[ int luaopen_]],func,[[(lua_State *L) {
int arg = lua_gettop(L);
luaL_loadbuffer(L,(const char*)B]],i,[[,sizeof(B]],i,[[),"]],input,[[");
lua_insert(L,1);
lua_call(L,arg,1);
return 1;
}
]])
end
outh:write([[
#endif /* __]],guard,[[__ */
]])
outh:close()
outc:close()
| mit |
lichtl/darkstar | scripts/zones/Throne_Room/mobs/Shadow_Lord.lua | 23 | 5454 | -----------------------------------
-- Area: Throne Room
-- MOB: Shadow Lord
-- Mission 5-2 BCNM Fight
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
-- 1st form
-- after change magic or physical immunity every 5min or 1k dmg
-- 2nd form
-- the Shadow Lord will do nothing but his Implosion attack. This attack hits everyone in the battlefield, but he only has 4000 HP
if (mob:getID() < 17453060) then -- first phase AI
-- once he's under 50% HP, start changing immunities and attack patterns
if (mob:getHP() / mob:getMaxHP() <= 0.5) then
-- have to keep track of both the last time he changed immunity and the HP he changed at
local changeTime = mob:getLocalVar("changeTime");
local changeHP = mob:getLocalVar("changeHP");
-- subanimation 0 is first phase subanim, so just go straight to magic mode
if (mob:AnimationSub() == 0) then
mob:AnimationSub(1);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0);
mob:SetAutoAttackEnabled(false);
mob:SetMagicCastingEnabled(true);
mob:setMobMod(MOBMOD_MAGIC_COOL, 2);
--and record the time and HP this immunity was started
mob:setLocalVar("changeTime", mob:getBattleTime());
mob:setLocalVar("changeHP", mob:getHP());
-- subanimation 2 is physical mode, so check if he should change into magic mode
elseif (mob:AnimationSub() == 2 and (mob:getHP() <= changeHP - 1000 or
mob:getBattleTime() - changeTime > 300)) then
mob:AnimationSub(1);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0);
mob:SetAutoAttackEnabled(false);
mob:SetMagicCastingEnabled(true);
mob:setMobMod(MOBMOD_MAGIC_COOL, 2);
mob:setLocalVar("changeTime", mob:getBattleTime());
mob:setLocalVar("changeHP", mob:getHP());
-- subanimation 1 is magic mode, so check if he should change into physical mode
elseif (mob:AnimationSub() == 1 and (mob:getHP() <= changeHP - 1000 or
mob:getBattleTime() - changeTime > 300)) then
-- and use an ability before changing
mob:useMobAbility(673);
mob:AnimationSub(2);
mob:delStatusEffect(EFFECT_MAGIC_SHIELD);
mob:addStatusEffectEx(EFFECT_PHYSICAL_SHIELD, 0, 1, 0, 0);
mob:SetAutoAttackEnabled(true);
mob:SetMagicCastingEnabled(false);
mob:setMobMod(MOBMOD_MAGIC_COOL, 10);
mob:setLocalVar("changeTime", mob:getBattleTime());
mob:setLocalVar("changeHP", mob:getHP());
end
end
else
-- second phase AI: Implode every 9 seconds
local lastImplodeTime = mob:getLocalVar("lastImplodeTime");
-- second phase AI: Implode every 9 seconds
if (mob:getBattleTime() - lastImplodeTime > 9) then
mob:useMobAbility(669);
mob:setLocalVar("lastImplodeTime", mob:getBattleTime());
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
if (mob:getID() < 17453060) then
player:startEvent(0x7d04);
player:setVar("mobid",mob:getID());
else
player:addTitle(SHADOW_BANISHER);
end
-- reset everything on death
mob:AnimationSub(0);
mob:SetAutoAttackEnabled(true);
mob:SetMagicCastingEnabled(true);
mob:delStatusEffect(EFFECT_MAGIC_SHIELD);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
-- reset everything on despawn
mob:AnimationSub(0);
mob:SetAutoAttackEnabled(true);
mob:SetMagicCastingEnabled(true);
mob:delStatusEffect(EFFECT_MAGIC_SHIELD);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("updateCSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("finishCSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x7d04) then
local mobid = player:getVar("mobid");
DespawnMob(mobid);
player:setVar("mobid",0);
--first phase dies, spawn second phase ID, make him engage, and disable
-- magic, auto attack, and abilities (all he does is case Implode by script)
mob = SpawnMob(mobid+3);
mob:updateEnmity(player);
mob:SetMagicCastingEnabled(false);
mob:SetAutoAttackEnabled(false);
mob:SetMobAbilityEnabled(false);
end
end;
| gpl-3.0 |
NiLuJe/koreader | frontend/device/sdl/device.lua | 3 | 14342 | local Event = require("ui/event")
local Generic = require("device/generic/device")
local SDL = require("ffi/SDL2_0")
local ffi = require("ffi")
local logger = require("logger")
local time = require("ui/time")
-- SDL computes WM_CLASS on X11/Wayland based on process's binary name.
-- Some desktop environments rely on WM_CLASS to name the app and/or to assign the proper icon.
if jit.os == "Linux" or jit.os == "BSD" or jit.os == "POSIX" then
if not os.getenv("SDL_VIDEO_WAYLAND_WMCLASS") then ffi.C.setenv("SDL_VIDEO_WAYLAND_WMCLASS", "KOReader", 1) end
if not os.getenv("SDL_VIDEO_X11_WMCLASS") then ffi.C.setenv("SDL_VIDEO_X11_WMCLASS", "KOReader", 1) end
end
local function yes() return true end
local function no() return false end
local function notOSX() return jit.os ~= "OSX" end
local function isUrl(s)
return type(s) == "string" and s:match("*?://")
end
local function isCommand(s)
return os.execute("which "..s.." >/dev/null 2>&1") == 0
end
local function runCommand(command)
local env = jit.os ~= "OSX" and 'env -u LD_LIBRARY_PATH ' or ""
return os.execute(env..command) == 0
end
local function getDesktopDicts()
local t = {
{ "Goldendict", "Goldendict", false, "goldendict" },
}
-- apple dict is always present in osx
if jit.os == "OSX" then
table.insert(t, 1, { "Apple", "AppleDict", false, "dict://" })
end
return t
end
local function getLinkOpener()
if jit.os == "Linux" and isCommand("xdg-open") then
return true, "xdg-open"
elseif jit.os == "OSX" and isCommand("open") then
return true, "open"
end
return false
end
-- thirdparty app support
local external = require("device/thirdparty"):new{
dicts = getDesktopDicts(),
check = function(self, app)
if (isUrl(app) and getLinkOpener()) or isCommand(app) then
return true
end
return false
end,
}
local Device = Generic:extend{
model = "SDL",
isSDL = yes,
home_dir = os.getenv("XDG_DOCUMENTS_DIR") or os.getenv("HOME"),
hasBattery = SDL.getPowerInfo,
hasKeyboard = yes,
hasKeys = yes,
hasDPad = yes,
hasWifiToggle = no,
isTouchDevice = yes,
isDefaultFullscreen = no,
needsScreenRefreshAfterResume = no,
hasColorScreen = yes,
hasEinkScreen = no,
hasSystemFonts = yes,
canSuspend = no,
canStandby = no,
startTextInput = SDL.startTextInput,
stopTextInput = SDL.stopTextInput,
canOpenLink = getLinkOpener,
openLink = function(self, link)
local enabled, tool = getLinkOpener()
if not enabled or not tool or not link or type(link) ~= "string" then return end
return runCommand(tool .. " '" .. link .. "'")
end,
canExternalDictLookup = yes,
getExternalDictLookupList = function() return external.dicts end,
doExternalDictLookup = function(self, text, method, callback)
external.when_back_callback = callback
local ok, app = external:checkMethod("dict", method)
if app then
if isUrl(app) and getLinkOpener() then
ok = self:openLink(app..text)
elseif isCommand(app) then
ok = runCommand(app .. " " .. text .. " &")
end
end
if ok and external.when_back_callback then
external.when_back_callback()
external.when_back_callback = nil
end
end,
window = G_reader_settings:readSetting("sdl_window", {}),
}
local AppImage = Device:extend{
model = "AppImage",
hasMultitouch = no,
hasOTAUpdates = yes,
isDesktop = yes,
}
local Desktop = Device:extend{
model = SDL.getPlatform(),
isDesktop = yes,
canRestart = notOSX,
hasExitOptions = notOSX,
}
local Emulator = Device:extend{
model = "Emulator",
isEmulator = yes,
hasBattery = yes,
hasEinkScreen = yes,
hasFrontlight = yes,
hasNaturalLight = yes,
hasNaturalLightApi = yes,
hasWifiToggle = yes,
hasWifiManager = yes,
-- Not really, Device:reboot & Device:powerOff are not implemented, so we just exit ;).
canPowerOff = yes,
canReboot = yes,
-- NOTE: Via simulateSuspend
canSuspend = yes,
canStandby = no,
}
local UbuntuTouch = Device:extend{
model = "UbuntuTouch",
hasFrontlight = yes,
isDefaultFullscreen = yes,
}
function Device:init()
-- allows to set a viewport via environment variable
-- syntax is Lua table syntax, e.g. EMULATE_READER_VIEWPORT="{x=10,w=550,y=5,h=790}"
local viewport = os.getenv("EMULATE_READER_VIEWPORT")
if viewport then
self.viewport = require("ui/geometry"):new(loadstring("return " .. viewport)())
end
local touchless = os.getenv("DISABLE_TOUCH") == "1"
if touchless then
self.isTouchDevice = no
end
local portrait = os.getenv("EMULATE_READER_FORCE_PORTRAIT")
if portrait then
self.isAlwaysPortrait = yes
end
self.hasClipboard = yes
self.screen = require("ffi/framebuffer_SDL2_0"):new{
device = self,
debug = logger.dbg,
w = self.window.width,
h = self.window.height,
x = self.window.left,
y = self.window.top,
is_always_portrait = self.isAlwaysPortrait(),
}
self.powerd = require("device/sdl/powerd"):new{device = self}
local ok, re = pcall(self.screen.setWindowIcon, self.screen, "resources/koreader.png")
if not ok then logger.warn(re) end
local input = require("ffi/input")
self.input = require("device/input"):new{
device = self,
event_map = require("device/sdl/event_map_sdl2"),
handleSdlEv = function(device_input, ev)
local Geom = require("ui/geometry")
local UIManager = require("ui/uimanager")
-- SDL events can remain cdata but are almost completely transparent
local SDL_TEXTINPUT = 771
local SDL_MOUSEWHEEL = 1027
local SDL_MULTIGESTURE = 2050
local SDL_DROPFILE = 4096
local SDL_WINDOWEVENT_MOVED = 4
local SDL_WINDOWEVENT_RESIZED = 5
if ev.code == SDL_MOUSEWHEEL then
local scrolled_x = ev.value.x
local scrolled_y = ev.value.y
local up = 1
local down = -1
local pos = Geom:new{
x = 0,
y = 0,
w = 0, h = 0,
}
local fake_ges = {
ges = "pan",
distance = 200,
relative = {
x = 50*scrolled_x,
y = 100*scrolled_y,
},
pos = pos,
time = time.timeval(ev.time),
mousewheel_direction = scrolled_y,
}
local fake_ges_release = {
ges = "pan_release",
distance = fake_ges.distance,
relative = fake_ges.relative,
pos = pos,
time = time.timeval(ev.time),
from_mousewheel = true,
}
local fake_pan_ev = Event:new("Pan", nil, fake_ges)
local fake_release_ev = Event:new("Gesture", fake_ges_release)
if scrolled_y == down then
fake_ges.direction = "north"
UIManager:broadcastEvent(fake_pan_ev)
UIManager:broadcastEvent(fake_release_ev)
elseif scrolled_y == up then
fake_ges.direction = "south"
UIManager:broadcastEvent(fake_pan_ev)
UIManager:broadcastEvent(fake_release_ev)
end
elseif ev.code == SDL_MULTIGESTURE then
-- no-op for now
do end -- luacheck: ignore 541
elseif ev.code == SDL_DROPFILE then
local dropped_file_path = ev.value
if dropped_file_path and dropped_file_path ~= "" then
local ReaderUI = require("apps/reader/readerui")
ReaderUI:doShowReader(dropped_file_path)
end
elseif ev.code == SDL_WINDOWEVENT_RESIZED then
device_input.device.screen.screen_size.w = ev.value.data1
device_input.device.screen.screen_size.h = ev.value.data2
device_input.device.screen.resize(device_input.device.screen, ev.value.data1, ev.value.data2)
self.window.width = ev.value.data1
self.window.height = ev.value.data2
local new_size = device_input.device.screen:getSize()
logger.dbg("Resizing screen to", new_size)
-- try to catch as many flies as we can
-- this means we can't just return one ScreenResize or SetDimensons event
UIManager:broadcastEvent(Event:new("SetDimensions", new_size))
UIManager:broadcastEvent(Event:new("ScreenResize", new_size))
--- @todo Toggle this elsewhere based on ScreenResize?
-- this triggers paged media like PDF and DjVu to redraw
-- CreDocument doesn't need it
UIManager:broadcastEvent(Event:new("RedrawCurrentPage"))
local FileManager = require("apps/filemanager/filemanager")
if FileManager.instance then
FileManager.instance:reinit(FileManager.instance.path,
FileManager.instance.focused_file)
end
elseif ev.code == SDL_WINDOWEVENT_MOVED then
self.window.left = ev.value.data1
self.window.top = ev.value.data2
elseif ev.code == SDL_TEXTINPUT then
UIManager:sendEvent(Event:new("TextInput", tostring(ev.value)))
end
end,
hasClipboardText = function()
return input.hasClipboardText()
end,
getClipboardText = function()
return input.getClipboardText()
end,
setClipboardText = function(text)
return input.setClipboardText(text)
end,
gameControllerRumble = function(left_intensity, right_intensity, duration)
return input.gameControllerRumble(left_intensity, right_intensity, duration)
end,
file_chooser = input.file_chooser,
}
self.keyboard_layout = require("device/sdl/keyboard_layout")
if self.input.gameControllerRumble(0, 0, 0) then
self.isHapticFeedbackEnabled = yes
self.performHapticFeedback = function(type)
self.input.gameControllerRumble()
end
end
if portrait then
self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY)
self.input:registerEventAdjustHook(
self.input.adjustTouchMirrorX,
(self.screen:getScreenWidth() - 1)
)
end
Generic.init(self)
end
function Device:setDateTime(year, month, day, hour, min, sec)
if hour == nil or min == nil then return true end
local command
if year and month and day then
command = string.format("date -s '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("date -s '%d:%d'",hour, min)
end
if os.execute(command) == 0 then
os.execute('hwclock -u -w')
return true
else
return false
end
end
function Device:isAlwaysFullscreen()
-- return true on embedded devices, which should default to fullscreen
return self:isDefaultFullscreen()
end
function Device:toggleFullscreen()
local current_mode = self.fullscreen or self:isDefaultFullscreen()
local new_mode = not current_mode
local ok, err = SDL.setWindowFullscreen(new_mode)
if not ok then
logger.warn("Unable to toggle fullscreen mode to", new_mode, "\n", err)
else
self.fullscreen = new_mode
end
end
function Device:setEventHandlers(UIManager)
if not self:canSuspend() then
-- If we can't suspend, we have no business even trying to, as we may not have overloaded `Device:simulateResume`.
-- Instead, rely on the Generic Suspend/Resume handlers.
return
end
UIManager.event_handlers.Suspend = function()
self:_beforeSuspend()
self:simulateSuspend()
end
UIManager.event_handlers.Resume = function()
self:simulateResume()
self:_afterResume()
end
UIManager.event_handlers.PowerRelease = function()
-- Resume if we were suspended
if self.screen_saver_mode then
UIManager.event_handlers.Resume()
else
UIManager.event_handlers.Suspend()
end
end
end
function Emulator:supportsScreensaver() return true end
function Emulator:simulateSuspend()
local Screensaver = require("ui/screensaver")
Screensaver:setup()
Screensaver:show()
end
function Emulator:simulateResume()
local Screensaver = require("ui/screensaver")
Screensaver:close()
end
-- fake network manager for the emulator
function Emulator:initNetworkManager(NetworkMgr)
local UIManager = require("ui/uimanager")
local connectionChangedEvent = function()
if G_reader_settings:nilOrTrue("emulator_fake_wifi_connected") then
UIManager:broadcastEvent(Event:new("NetworkConnected"))
else
UIManager:broadcastEvent(Event:new("NetworkDisconnected"))
end
end
function NetworkMgr:turnOffWifi(complete_callback)
G_reader_settings:flipNilOrTrue("emulator_fake_wifi_connected")
UIManager:scheduleIn(2, connectionChangedEvent)
end
function NetworkMgr:turnOnWifi(complete_callback)
G_reader_settings:flipNilOrTrue("emulator_fake_wifi_connected")
UIManager:scheduleIn(2, connectionChangedEvent)
end
function NetworkMgr:isWifiOn()
return G_reader_settings:nilOrTrue("emulator_fake_wifi_connected")
end
end
io.write("Starting SDL in " .. SDL.getBasePath() .. "\n")
-------------- device probe ------------
if os.getenv("APPIMAGE") then
return AppImage
elseif os.getenv("KO_MULTIUSER") then
return Desktop
elseif os.getenv("UBUNTU_APPLICATION_ISOLATION") then
return UbuntuTouch
else
return Emulator
end
| agpl-3.0 |
ryuslash/avandu-lua | spec/helpers.lua | 1 | 3386 | local avandu = require 'avandu'
local https = require 'ssl.https'
local posix = require 'posix'
local helpers = {}
function helpers.yes () return true end
function helpers.no () return false end
function helpers.goreadable () return 'rw-rw-rw-' end
function helpers.ureadable () return 'rw-------' end
function helpers.fakefile()
return {read = function ()
return '{"user": "user", "password": "password"}'
end,
close = function () end}
end
function helpers.proper_file_situation (url)
return function ()
posix.access = helpers.yes
posix.stat = helpers.ureadable
io.open = helpers.fakefile
avandu.ttrss_url = url
end
end
function helpers.define_credentials_existence_test_for (testfunc)
return function ()
posix.access = helpers.no
credfile = os.getenv('HOME') .. '/.avandu.json'
assert.has_error(testfunc,
'The file ' .. credfile .. ' could not be found')
end
end
function helpers.define_credentials_permission_test_for (testfunc)
return function ()
posix.access = helpers.yes
posix.stat = helpers.goreadable
credfile = os.getenv('HOME') .. '/.avandu.json'
assert.has_error(testfunc,
'The file ' .. credfile .. ' has incorrect permissions')
end
end
function helpers.define_nourl_test_for (testfunc)
return function ()
avandu.ttrss_url = nil
local result, err = testfunc()
assert.falsy(result)
assert.are.same({message = 'no URL set'}, err)
assert.are.same(avandu.Exception, getmetatable(err))
end
end
function helpers.define_params_test_for (testfunc, url)
return function ()
https.request = function (params)
assert.are.same(params.url, url)
assert.are.same(params.method, 'POST')
assert.are.same(
{['Content-Length'] = params.source():len()}, params.headers)
assert.are.same(params.protocol, 'tlsv1')
assert.truthy(params.sink)
assert.truthy(params.source)
return 1, 200, {}, ''
end
testfunc()
end
end
function helpers.define_404_test_for (testfunc, url)
return function ()
https.request = function (params)
return '', 404, {}, 'Not Found'
end
local results, err = testfunc()
assert.falsy(results)
assert.are.same({message = 'URL not found', url = url, code = 404,
status = 'Not Found'}, err)
assert.are.same(avandu.Exception, getmetatable(err))
end
end
function helpers.define_unexpected_test_for (testfunc, url)
return function ()
https.request = function (params)
return '', 500, {}, 'Internal Server Error'
end
local results, err = testfunc()
assert.falsy(results)
assert.are.same({message = 'Unexpected HTTP status returned',
url = url, code = 500,
status = 'Internal Server Error'}, err)
assert.are.same(avandu.Exception, getmetatable(err))
end
end
function helpers.define_nonzero_test_for (testfunc, expected)
return function ()
https.request = function (params)
params.sink('{"status": 1}')
return '', 200, {}, ''
end
local results, err = testfunc()
assert.are.same(expected, results)
assert.falsy(err)
end
end
return helpers
| gpl-3.0 |
taiha/luci | protocols/luci-proto-ppp/luasrc/model/network/proto_ppp.lua | 18 | 2363 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g", "l2tp", "pppossh"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
elseif p == "l2tp" then
return luci.i18n.translate("L2TP")
elseif p == "pppossh" then
return luci.i18n.translate("PPPoSSH")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pptp" then
return "ppp-mod-pptp"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
elseif p == "l2tp" then
return "xl2tpd"
elseif p == "pppossh" then
return "pppossh"
end
end
function proto.is_installed(self)
if p == "pppoa" then
return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil)
elseif p == "pppoe" then
return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil)
elseif p == "pptp" then
return (nixio.fs.glob("/usr/lib/pppd/*/pptp.so")() ~= nil)
elseif p == "3g" then
return nixio.fs.access("/lib/netifd/proto/3g.sh")
elseif p == "l2tp" then
return nixio.fs.access("/lib/netifd/proto/l2tp.sh")
elseif p == "pppossh" then
return nixio.fs.access("/lib/netifd/proto/pppossh.sh")
else
return nixio.fs.access("/lib/netifd/proto/ppp.sh")
end
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
| apache-2.0 |
RunAwayDSP/darkstar | scripts/zones/Horlais_Peak/bcnms/under_observation.lua | 9 | 1064 | -----------------------------------
-- Under Observation
-- Horlais Peak BCNM40, Star Orb
-- !additem 1131
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Beaucedine_Glacier/npcs/Torino-Samarino.lua | 9 | 2648 | -----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Torino-Samarino
-- Type: Quest NPC
-- Involved in Quests: Curses, Foiled A-Golem!?, Tuning Out
-- !pos 105 -20 140 111
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
local ID = require("scripts/zones/Beaucedine_Glacier/IDs");
require("scripts/globals/keyitems");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local FoiledAGolem = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.CURSES_FOILED_A_GOLEM);
-- Curses, Foiled A_Golem!?
if (player:hasKeyItem(dsp.ki.SHANTOTTOS_EXSPELL) and FoiledAGolem == QUEST_ACCEPTED) then
player:startEvent(108); -- key item taken, wait one game day for new spell
elseif (player:getCharVar("golemwait") == 1 and FoiledAGolem == QUEST_ACCEPTED) then
local gDay = VanadielDayOfTheYear();
local gYear = VanadielYear();
local dFinished = player:getCharVar("golemday");
local yFinished = player:getCharVar("golemyear");
if (gDay == dFinished and gYear == yFinished) then
player:startEvent(113); -- re-write reminder
elseif (gDay == dFinished + 1 and gYear == yFinished) then
player:startEvent(109); -- re-write done
end
elseif (player:getCharVar("foiledagolemdeliverycomplete") == 1) then
player:startEvent(110); -- talk to Shantotto reminder
elseif (FoiledAGolem == QUEST_ACCEPTED) then
player:startEvent(104); -- receive key item
else
player:startEvent(101); -- standard dialog
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
-- Curses, Foiled A_Golem!?
if (csid == 104 and option == 1) then
player:addKeyItem(dsp.ki.SHANTOTTOS_NEW_SPELL);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SHANTOTTOS_NEW_SPELL); -- add new spell key item
elseif (csid == 108) then -- start wait for new scroll
player:delKeyItem(dsp.ki.SHANTOTTOS_EXSPELL);
player:setCharVar("golemday",VanadielDayOfTheYear());
player:setCharVar("golemyear",VanadielYear());
player:setCharVar("golemwait",1);
elseif (csid == 109) then
player:addKeyItem(dsp.ki.SHANTOTTOS_NEW_SPELL);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SHANTOTTOS_NEW_SPELL); -- add new spell key item
player:setCharVar("golemday",0);
player:setCharVar("golemyear",0);
player:setCharVar("golemwait",0);
end
end; | gpl-3.0 |
punisherbot/he | plugins/Gp_Moderator.lua | 4 | 11328 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "Only Global admins can use it!"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'creategp' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == 'lock' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Plugin to manage group chat.",
usage = {
"!creategp <group_name> : Create a new group (admin only)",
"!setabout <description> : Set group description",
"!about : Read group description",
"!setrules <rules> : Set group rules",
"!rules : Read group rules",
"!setname <new_name> : Set group name",
"!setphoto : Set group photo",
"!group <lock|unlock> name : Lock/unlock group name",
"!group <lock|unlock> photo : Lock/unlock group photo",
"!group <lock|unlock> member : Lock/unlock group member",
"!group settings : Show group settings"
},
patterns = {
"^!(creategp) (.*)$",
"^!(setabout) (.*)$",
"^!(about)$",
"^!(setrules) (.*)$",
"^!(rules)$",
"^!(setname) (.*)$",
"^!(setphoto)$",
"^!(group) (lock) (.*)$",
"^!(group) (unlock) (.*)$",
"^!(group) (settings)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end
| gpl-2.0 |
lichtl/darkstar | scripts/globals/items/piece_of_witch_nougat.lua | 18 | 1272 | -----------------------------------------
-- ID: 5645
-- Item: piece_of_witch_nougat
-- Food Effect: 1hour, All Races
-----------------------------------------
-- HP 50
-- Intelligence 3
-- Agility -3
-----------------------------------------
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,5645);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 50);
target:addMod(MOD_INT, 3);
target:addMod(MOD_AGI, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 50);
target:delMod(MOD_INT, 3);
target:delMod(MOD_AGI, -3);
end;
| gpl-3.0 |
lichtl/darkstar | scripts/globals/items/wild_steak.lua | 18 | 1371 | -----------------------------------------
-- ID: 4519
-- Item: wild_steak
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Strength 4
-- Intelligence -2
-- Attack % 25
-- Attack Cap 50
-----------------------------------------
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,14400,4519);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_INT, -2);
target:addMod(MOD_FOOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 50);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_INT, -2);
target:delMod(MOD_FOOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 50);
end;
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Beadeaux/npcs/_43b.lua | 11 | 1312 | -----------------------------------
-- Area: Beadeaux
-- NPC: Jail Door
-- Involved in Quests: The Rescue
-- !pos 56 0.1 -23 147
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Beadeaux/IDs");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.THE_RESCUE) == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TRADERS_SACK) == false) then
if (trade:hasItemQty(495,1) == true and trade:getItemCount() == 1) then
player:startEvent(1000);
end
end
end;
function onTrigger(player,npc)
if (player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.THE_RESCUE) == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TRADERS_SACK) == false) then
player:messageSpecial(ID.text.LOCKED_DOOR_QUADAV_HAS_KEY);
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY);
end
return 1;
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 1000) then
player:addKeyItem(dsp.ki.TRADERS_SACK);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.TRADERS_SACK);
end
end;
| gpl-3.0 |
lichtl/darkstar | scripts/globals/weaponskills/rock_crusher.lua | 23 | 1258 | -----------------------------------
-- Rock Crusher
-- Staff weapon skill
-- Skill Level: 40
-- Delivers an earth elemental attack. Damage varies with TP.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: Earth
-- Modifiers: STR:40% ; INT:40%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_EARTH;
params.skill = SKILL_STF;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
scscgit/scsc_wildstar_addons | LUI_Holdem/libs/LibJSON/LibJSON-2.5.lua | 13 | 18391 | --[==[
David Kolf's JSON module for Lua 5.1/5.2
Version 2.5
For the documentation see the corresponding readme.txt or visit
<http://dkolf.de/src/dkjson-lua.fsl/>.
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
Copyright (C) 2010-2013 David Heiko Kolf
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]==]
local MAJOR, MINOR = "Lib:dkJSON-2.5", 2
-- Get a reference to the package information if any
local APkg = Apollo.GetPackage(MAJOR)
-- If there was an older version loaded we need to see if this is newer
if APkg and (APkg.nVersion or 0) >= MINOR then
return -- no upgrade needed
end
-- Set a reference to the actual package or create an empty table
local JSON = APkg and APkg.tPackage or {}
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, debug.getmetatable, setmetatable, rawset
local error, pcall, select = error, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
JSON.version = "dkjson 2.5"
local _ENV = nil -- blocking globals in Lua 5.2
JSON.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
JSON.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function JSON.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder, state)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder, state)
end
local function appendcustom(res, buffer, state)
local buflen = state.bufferlen
if type (res) == 'string' then
buflen = buflen + 1
buffer[buflen] = res
end
return buflen
end
local function exception(reason, value, state, buffer, buflen, defaultmessage)
defaultmessage = defaultmessage or reason
local handler = state.exception
if not handler then
return nil, defaultmessage
else
state.bufferlen = buflen
local ret, msg = handler (reason, value, state, defaultmessage)
if not ret then return nil, msg or defaultmessage end
return appendcustom(ret, buffer, state)
end
end
function JSON.encodeexception(reason, value, state, defaultmessage)
return quotestring("<" .. defaultmessage .. ">")
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder, state)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return exception('reference cycle', value, state, buffer, buflen)
end
tables[value] = true
state.bufferlen = buflen
local ret, msg = valtojson (value, state)
if not ret then return exception('custom encoder failed', value, state, buffer, buflen, msg) end
tables[value] = nil
buflen = appendcustom(ret, buffer, state)
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return exception('reference cycle', value, state, buffer, buflen)
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder, state)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return exception ('unsupported type', value, state, buffer, buflen,
"type '" .. valtype .. "' is not supported by JSON.")
end
return buflen
end
function JSON.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
state.buffer = buffer
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder, state)
if not ret then
error (msg, 2)
elseif oldbuffer == buffer then
state.bufferlen = ret
return true
else
state.bufferlen = nil
state.buffer = nil
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
local sub2 = strsub (str, pos, pos + 1)
if sub2 == "\239\187" and strsub (str, pos + 2, pos + 2) == "\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
elseif sub2 == "//" then
pos = strfind (str, "[\n\r]", pos + 2)
if not pos then return nil end
elseif sub2 == "/*" then
pos = strfind (str, "*/", pos + 2)
if not pos then return nil end
pos = pos + 2
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function JSON.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function JSON:OnLoad() end
Apollo.RegisterPackage(JSON, MAJOR, MINOR, {}) | mit |
RunAwayDSP/darkstar | scripts/globals/items/slice_of_ziz_meat.lua | 11 | 1070 | -----------------------------------------
-- ID: 5581
-- Item: Slice of Ziz Meat
-- Effect: 5 Minutes, food effect, Galka Only
-----------------------------------------
-- Strength +4
-- Intelligence -6
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:getRace() ~= dsp.race.GALKA) then
result = dsp.msg.basic.CANNOT_EAT
end
if (target:getMod(dsp.mod.EAT_RAW_MEAT) == 1) then
result = 0
end
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,300,5581)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.STR, 4)
target:addMod(dsp.mod.INT,-6)
end
function onEffectLose(target,effect)
target:delMod(dsp.mod.STR, 4)
target:delMod(dsp.mod.INT,-6)
end | gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Port_San_dOria/npcs/Vounebariont.lua | 11 | 1647 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Vounebariont
-- Starts and Finishes Quest: Thick Shells
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
local ID = require("scripts/zones/Port_San_dOria/IDs");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(889,5) and trade:getItemCount() == 5) then -- Trade Beetle Shell
player:startEvent(514);
end
end
end;
function onTrigger(player,npc)
if (player:getFameLevel(SANDORIA) >= 2) then
player:startEvent(516);
else
player:startEvent(568);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 516) then
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS) == QUEST_AVAILABLE) then
player:addQuest(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS);
end
elseif (csid == 514) then
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS) == QUEST_ACCEPTED) then
player:completeQuest(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS);
player:addFame(SANDORIA,30);
else
player:addFame(SANDORIA,5);
end
player:tradeComplete();
player:addTitle(dsp.title.BUG_CATCHER);
player:addGil(GIL_RATE*750);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*750)
end
end; | gpl-3.0 |
scscgit/scsc_wildstar_addons | Threat/Modules/List.lua | 1 | 11591 | require "Apollo"
require "GameLib"
require "GroupLib"
local Threat = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("Threat")
local List = Threat:NewModule("List")
List.nBarSlots = 0
List.bInPreview = false
--[[ Initial functions ]]--
function List:OnInitialize()
self.oXml = XmlDoc.CreateFromFile("Forms/List.xml")
Apollo.LoadSprites("Textures/Threat_Textures.xml", "")
if self.oXml == nil then
Apollo.AddAddonErrorText(Threat, "Could not load the Threat list window!")
return
end
self.oXml:RegisterCallback("OnDocumentReady", self)
end
function List:OnDocumentReady()
self.wndMain = Apollo.LoadForm(self.oXml, "ThreatList", nil, self)
self.wndList = self.wndMain:FindChild("BarList")
self:UpdatePosition()
self:UpdateLockStatus()
self:SetBarSlots()
end
function List:SetBarSlots()
local nOffset = Threat.tOptions.profile.tList.nBarOffset
self.nBarSlots = math.floor((self.wndList:GetHeight() + nOffset) / (Threat.tOptions.profile.tList.nBarHeight + nOffset))
end
function List:OnEnable()
end
function List:OnDisable()
end
--[[ Update and Clear ]]--
function List:Update(tThreatList, nPlayerId, nHighest)
if self.wndMain == nil or self.bInPreview then return end
self:CreateBars(#tThreatList)
local nBars = #self.wndList:GetChildren()
for nIndex, tEntry in ipairs(tThreatList) do
if nBars >= nIndex then
self:SetupBar(self.wndList:GetChildren()[nIndex], tEntry, nIndex == 1, nHighest, nPlayerId)
else break end
end
self.wndList:ArrangeChildrenVert()
end
function List:Clear()
if self.wndMain == nil or self.bInPreview then return end
self.wndList:DestroyChildren()
end
--[[ Bar setup functions ]]--
function List:CreateBars(nTListNum)
local nListNum = #self.wndList:GetChildren()
local nThreatListNum = math.min(self.nBarSlots, nTListNum)
--Check if needs to do any work
if nListNum ~= nThreatListNum then
if nListNum > nThreatListNum then
--If needs to remove some bars
for nIdx = nListNum, nThreatListNum + 1, -1 do
self.wndList:GetChildren()[nIdx]:Destroy()
end
else
--If needs to create some bars
for nIdx = nListNum + 1, nThreatListNum do
local wndBar = Apollo.LoadForm(self.oXml, "Bar", self.wndList, self)
self:SetBarOptions(wndBar)
end
end
end
end
function List:SetBarOptions(wndBar)
if Threat.tOptions.profile.tList.nBarStyle == 1 then
wndBar:FindChild("Background"):SetSprite("Threat_Textures:Threat_Smooth")
elseif Threat.tOptions.profile.tList.nBarStyle == 2 then
wndBar:FindChild("Background"):SetSprite("Threat_Textures:Threat_Edge")
end
local nOffset = Threat.tOptions.profile.tList.nBarOffset
local nL, nT, nR, nB = wndBar:GetAnchorOffsets()
wndBar:SetAnchorOffsets(nL, nT, nR, Threat.tOptions.profile.tList.nBarHeight + nOffset)
for _, v in ipairs(wndBar:GetChildren()) do
local nL, nT, nR, nB = v:GetAnchorOffsets()
v:SetAnchorOffsets(nL, nT, nR, nB - nOffset)
end
end
function List:SetupBar(wndBar, tEntry, bFirst, nHighest, nPlayerId)
-- Perform calculations for this entry.
local nPercent = 1
local sValue = self:FormatNumber(tEntry.nValue, 2)
-- Show the difference if enabled and not the first bar
if not bFirst then
nPercent = tEntry.nValue / nHighest
if Threat.tOptions.profile.tList.bShowDifferences then
sValue = "-"..self:FormatNumber(nHighest - tEntry.nValue, 2)
end
end
-- Set the name string to the character name
wndBar:FindChild("Name"):SetText(tEntry.sName)
-- Print the total as a string with the formatted number and percentage of total. (Ex. 300k 42%)
wndBar:FindChild("Total"):SetText(string.format("%s %d%s", sValue, nPercent * 100, "%"))
-- Update the progress bar with the new values and set the bar color.
local wndBarBackground = wndBar:FindChild("Background")
local nR, nG, nB, nA = self:GetColorForEntry(tEntry, bFirst, nPlayerId)
local _, nTop, _, nBottom = wndBarBackground:GetAnchorPoints()
if Threat.tOptions.profile.tList.bRightToLeftBars then
wndBarBackground:SetAnchorPoints(1 - nPercent, nTop, 1, nBottom)
else
wndBarBackground:SetAnchorPoints(0, nTop, nPercent, nBottom)
end
wndBarBackground:SetBGColor(ApolloColor.new(nR, nG, nB, nA))
end
function List:GetColorForEntry(tEntry, bFirst, nPlayerId)
local tColor = nil
local tWhite = { nR = 255, nG = 255, nB = 255, nA = 255 }
local bForceSelfColor = false
if tEntry.bPet then
tColor = Threat.tOptions.profile.tList.tColors.tPet or tWhite
else
-- Determine the color of the bar based on user settings.
if Threat.tOptions.profile.tList.nColorMode == 2 then
-- Use class color. Defaults to white if not found.
tColor = Threat.tOptions.profile.tList.tColors[tEntry.eClass] or tWhite
elseif Threat.tOptions.profile.tList.nColorMode == 1 and GroupLib.InGroup() then
-- Use role color. Defaults to white if not found.
for nIdx = 1, GroupLib.GetMemberCount() do
local tMemberData = GroupLib.GetGroupMember(nIdx)
if tMemberData.strCharacterName == tEntry.sName then
if tMemberData.bTank then
tColor = Threat.tOptions.profile.tList.tColors.tTank or tWhite
elseif tMemberData.bHealer then
tColor = Threat.tOptions.profile.tList.tColors.tHealer or tWhite
else
tColor = Threat.tOptions.profile.tList.tColors.tDamage or tWhite
end
end
end
if tColor == nil then
tColor = Threat.tOptions.profile.tList.tColors.tOthers or tWhite
end
else
-- Use non-class colors. Defaults to white if not found.
bForceSelfColor = true
tColor = Threat.tOptions.profile.tList.tColors.tOthers or tWhite
end
if Threat.tOptions.profile.tList.bAlwaysUseSelfColor or bForceSelfColor then
if nPlayerId == tEntry.nId then
-- This unit is the current player.
if Threat.tOptions.profile.tList.bUseSelfWarning and bFirst then
tColor = Threat.tOptions.profile.tList.tColors.tSelfWarning or tWhite
else
tColor = Threat.tOptions.profile.tList.tColors.tSelf or tWhite
end
end
end
end
return (tColor.nR / 255), (tColor.nG / 255), (tColor.nB / 255), (tColor.nA / 255)
end
function List:FormatNumber(nNumber, nPrecision)
nPrecision = nPrecision or 0
if nNumber >= 1000000 then
return string.format("%."..nPrecision.."fm", nNumber / 1000000)
elseif nNumber >= 10000 then
return string.format("%."..nPrecision.."fk", nNumber / 1000)
else
return tostring(nNumber)
end
end
--[[ Window events ]]--
function List:OnMouseEnter(wndHandler, wndControl)
if wndControl ~= self.wndMain then return end
if not Threat.tOptions.profile.bLocked then
self.wndMain:FindChild("Background"):Show(true)
end
end
function List:OnMouseExit(wndHandler, wndControl)
if wndControl ~= self.wndMain then return end
if Threat:GetModule("Settings").nCurrentTab == 0 then
self.wndMain:FindChild("Background"):Show(false)
end
end
function List:OnMouseButtonUp(wndHandler, wndControl, eMouseButton)
if eMouseButton == GameLib.CodeEnumInputMouse.Right then
if not Threat.tOptions.profile.bLocked or Threat:GetModule("Settings").wndMain:IsShown() then
Threat:GetModule("Settings"):Open(2)
end
end
end
function List:OnWindowMove()
local nLeft, nTop = self.wndMain:GetAnchorOffsets()
Threat.tOptions.profile.tList.tPosition.nX = nLeft
Threat.tOptions.profile.tList.tPosition.nY = nTop
end
function List:OnWindowSizeChanged(wndHandler, wndControl)
if wndControl ~= self.wndMain then return end
local nLeft, nTop, nRight, nBottom = self.wndMain:GetAnchorOffsets()
Threat.tOptions.profile.tList.tSize.nWidth = nRight - nLeft
Threat.tOptions.profile.tList.tSize.nHeight = nBottom - nTop
local nOldBarSlots = self.nBarSlots
self:SetBarSlots()
if self.bInPreview and nOldBarSlots ~= self.nBarSlots then
self:Preview()
end
end
--[[ Window updaters ]]--
function List:UpdatePosition()
if self.wndMain == nil then return end
local nLeft = Threat.tOptions.profile.tList.tPosition.nX
local nTop = Threat.tOptions.profile.tList.tPosition.nY
local nWidth = Threat.tOptions.profile.tList.tSize.nWidth
local nHeight = Threat.tOptions.profile.tList.tSize.nHeight
self.wndMain:SetAnchorOffsets(nLeft, nTop, nLeft + nWidth, nTop + nHeight)
end
function List:UpdateLockStatus()
if self.wndMain == nil then return end
self.wndMain:SetStyle("Moveable", not Threat.tOptions.profile.bLocked)
self.wndMain:SetStyle("Sizable", not Threat.tOptions.profile.bLocked)
self.wndMain:SetStyle("IgnoreMouse", Threat.tOptions.profile.bLocked)
end
--[[ Preview ]]--
function List:GetPreviewEntries()
local oPlayer = GameLib.GetPlayerUnit()
return {
{
nId = 0,
sName = GameLib.GetClassName(GameLib.CodeEnumClass.Warrior),
eClass = GameLib.CodeEnumClass.Warrior,
bPet = false,
nValue = 1000000
},
{
nId = oPlayer:GetId(),
sName = oPlayer:GetName(),
eClass = oPlayer:GetClassId(),
bPet = false,
nValue = 900000
},
{
nId = 0,
sName = GameLib.GetClassName(GameLib.CodeEnumClass.Engineer),
eClass = GameLib.CodeEnumClass.Engineer,
bPet = false,
nValue = 800000
},
{
nId = 0,
sName = GameLib.GetClassName(GameLib.CodeEnumClass.Esper),
eClass = GameLib.CodeEnumClass.Esper,
bPet = false,
nValue = 700000
},
{
nId = 0,
sName = GameLib.GetClassName(GameLib.CodeEnumClass.Medic),
eClass = GameLib.CodeEnumClass.Medic,
bPet = false,
nValue = 600000
},
{
nId = 0,
sName = GameLib.GetClassName(GameLib.CodeEnumClass.Stalker),
eClass = GameLib.CodeEnumClass.Stalker,
bPet = false,
nValue = 500000
},
{
nId = 0,
sName = GameLib.GetClassName(GameLib.CodeEnumClass.Spellslinger),
eClass = GameLib.CodeEnumClass.Spellslinger,
bPet = false,
nValue = 400000
},
{
nId = -1,
sName = "Pet",
eClass = nil,
bPet = true,
nValue = 300000
}
}
end
function List:Preview()
local nPlayerId = GameLib.GetPlayerUnit():GetId()
local tEntries = self:GetPreviewEntries()
self:CreateBars(#tEntries)
local nHighest = tEntries[1].nValue
local nBars = #self.wndList:GetChildren()
if nBars > 0 then
for nIndex, tEntry in pairs(tEntries) do
self:SetupBar(self.wndList:GetChildren()[nIndex], tEntry, nIndex == 1, nHighest, nPlayerId)
self:PreviewSetRoleColor(nIndex, tEntry)
if nBars == nIndex then break end
end
self.wndList:ArrangeChildrenVert()
end
end
function List:PreviewSetRoleColor(nIndex, tEntry)
if Threat.tOptions.profile.tList.nColorMode == 1 then
if nIndex == 1 then
self:PreviewSetColor(Threat.tOptions.profile.tList.tColors.tTank, nIndex)
elseif nIndex == 7 then
self:PreviewSetColor(Threat.tOptions.profile.tList.tColors.tHealer, nIndex)
elseif tEntry.nId == 0 then
self:PreviewSetColor(Threat.tOptions.profile.tList.tColors.tDamage, nIndex)
end
end
end
function List:PreviewSetColor(tColor, nIndex)
local Color = ApolloColor.new((tColor.nR / 255), (tColor.nG / 255), (tColor.nB / 255), (tColor.nA / 255))
self.wndList:GetChildren()[nIndex]:FindChild("Background"):SetBGColor(Color)
end
function List:PreviewColor()
local nPlayerId = GameLib.GetPlayerUnit():GetId()
local tEntries = self:GetPreviewEntries()
local nBars = #self.wndList:GetChildren()
if nBars > 0 then
for nIndex, tEntry in ipairs(tEntries) do
local wndBarBackground = self.wndList:GetChildren()[nIndex]:FindChild("Background")
local nR, nG, nB, nA = self:GetColorForEntry(tEntry, nIndex == 1, nPlayerId)
wndBarBackground:SetBGColor(ApolloColor.new(nR, nG, nB, nA))
self:PreviewSetRoleColor(nIndex, tEntry)
if nBars == nIndex then break end
end
end
end
function List:PreviewFullReload()
self.wndList:DestroyChildren()
self:SetBarSlots()
self:Preview()
end
| mit |
we20/ping | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
lichtl/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm0_1.lua | 17 | 1165 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: qm0 (warp player outside after they win fight)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0C);
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);
if (csid == 0x0C and option == 1) then
player:setPos(291.459,-42.088,-401.161,163,130);
end
end; | gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/spells/valor_minuet_iii.lua | 10 | 1567 | -----------------------------------------
-- Spell: Valor Minuet III
-- Grants Attack bonus to all allies.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(dsp.skill.SINGING) -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(dsp.slot.RANGED)
local power = 24
if (sLvl+iLvl > 200) then
power = power + math.floor((sLvl+iLvl-200) / 6)
end
if (power >= 96) then
power = 96
end
local iBoost = caster:getMod(dsp.mod.MINUET_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT)
if (iBoost > 0) then
power = power + iBoost*9
end
power = power + caster:getMerit(dsp.merit.MINUET_EFFECT)
if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then
power = power * 2
elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then
power = power * 1.5
end
caster:delStatusEffect(dsp.effect.MARCATO)
local duration = 120
duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1)
if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then
duration = duration * 2
end
if not (target:addBardSong(caster,dsp.effect.MINUET,power,0,duration,caster:getID(), 0, 3)) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
return dsp.effect.MINUET
end
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Northern_San_dOria/npcs/Vichuel.lua | 11 | 1281 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Vichuel
-- Only sells when San d'Oria controlls Fauregandi Region
-----------------------------------
local ID = require("scripts/zones/Northern_San_dOria/IDs")
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/npc_util")
require("scripts/globals/conquest")
require("scripts/globals/quests")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then
player:messageSpecial(ID.text.FLYER_REFUSED)
else
onHalloweenTrade(player, trade, npc)
end
end
function onTrigger(player,npc)
if GetRegionOwner(dsp.region.FAUREGANDI) ~= dsp.nation.SANDORIA then
player:showText(npc, ID.text.VICHUEL_CLOSED_DIALOG)
else
local stock =
{
4571, 90, -- Beaugreens
4363, 39, -- Faerie Apple
691, 54, -- Maple Log
}
player:showText(npc, ID.text.VICHUEL_OPEN_DIALOG)
dsp.shop.general(player, stock, SANDORIA)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
pandoc-scholar/pandoc-scholar | lua-filters/section-refs/section-refs.lua | 1 | 4012 | -- pandoc.utils.make_sections exists since pandoc 2.8
if PANDOC_VERSION == nil then -- if pandoc_version < 2.1
error("ERROR: pandoc >= 2.1 required for section-refs filter")
else
PANDOC_VERSION:must_be_at_least {2,8}
end
local utils = require 'pandoc.utils'
local run_json_filter = utils.run_json_filter
--- The document's metadata
local meta
-- Lowest level at which bibliographies should be generated.
local section_refs_level
-- original bibliography value
local orig_bibliography
-- Returns true iff a div is a section div.
local function is_section_div (div)
return div.t == 'Div'
and div.classes[1] == 'section'
and div.attributes.number
end
local function section_header (div)
local header = div.content and div.content[1]
local is_header = is_section_div(div)
and header
and header.t == 'Header'
return is_header and header or nil
end
local function adjust_refs_components (div)
local header = section_header(div)
if not header then
return div
end
local blocks = div.content
local bib_header = blocks:find_if(function (b)
return b.identifier == 'bibliography'
end)
local refs = blocks:find_if(function (b)
return b.identifier == 'refs'
end)
if bib_header then
bib_header.identifier = 'bibliography-' .. header.attributes.number
bib_header.level = header.level + 1
end
if refs and refs.identifier == 'refs' then
refs.identifier = 'refs-' .. header.attributes.number
end
return div
end
--- Create a bibliography for a given topic. This acts on all
-- section divs at or above `section_refs_level`
local function create_section_bibliography (div)
-- don't do anything if there is no bibliography
if not meta.bibliography and not meta.references then
return nil
end
local header = section_header(div)
-- Blocks for which a bibliography will be generated
local subsections
local blocks
if not header or section_refs_level < header.level then
-- Don't do anything for lower level sections.
return nil
elseif section_refs_level == header.level then
blocks = div.content
subsections = pandoc.List:new{}
else
blocks = div.content:filter(function (b)
return not is_section_div(b)
end)
subsections = div.content:filter(is_section_div)
end
local tmp_doc = pandoc.Pandoc(blocks, meta)
local filter_args = {FORMAT, '-q'} -- keep pandoc-citeproc quiet
local new_doc = run_json_filter(tmp_doc, 'pandoc-citeproc', filter_args)
div.content = new_doc.blocks .. subsections
return adjust_refs_components(div)
end
--- Remove remaining section divs
local function flatten_sections (div)
local header = section_header(div)
if not header then
return nil
else
header.identifier = div.identifier
header.attributes.number = nil
div.content[1] = header
return div.content
end
end
--- Filter to the references div and bibliography header added by
--- pandoc-citeproc.
local remove_pandoc_citeproc_results = {
Header = function (header)
return header.identifier == 'bibliography'
and {}
or nil
end,
Div = function (div)
return div.identifier == 'refs'
and {}
or nil
end
}
local function restore_bibliography (meta)
meta.bibliography = orig_bibliography
return meta
end
--- Setup the document for further processing by wrapping all
--- sections in Div elements.
function setup_document (doc)
-- save meta for other filter functions
meta = doc.meta
section_refs_level = tonumber(meta["section-refs-level"]) or 1
orig_bibliography = meta.bibliography
meta.bibliography = meta['section-refs-bibliography'] or meta.bibliography
local sections = utils.make_sections(true, nil, doc.blocks)
return pandoc.Pandoc(sections, doc.meta)
end
return {
-- remove result of previous pandoc-citeproc run (for backwards
-- compatibility)
remove_pandoc_citeproc_results,
{Pandoc = setup_document},
{Div = create_section_bibliography},
{Div = flatten_sections, Meta = restore_bibliography}
}
| gpl-2.0 |
scscgit/scsc_wildstar_addons | Interruptor/Libs/GeminiAddon.lua | 5 | 25272 | --- GeminiAddon-1.1
-- Formerly DaiAddon
-- Inspired by AceAddon
-- Modules and packages embeds are based heavily on AceAddon's functionally, so credit goes their authors.
--
-- Allows the addon to have modules
-- Allows for packages to be embedded (if supported) into the addon and it's modules
--
-- The core callbacks have been "renamed" for consumption that are used when creating an addon:
-- OnLoad -> OnInitialize
--
-- New callback:
-- OnEnable - Called when the character has been loaded and is in the world. Called after OnInitialize and after Restore would have occured
--
-- General flow should be:
-- OnInitialize -> OnEnable
local MAJOR, MINOR = "Gemini:Addon-1.1", 5
local APkg = Apollo.GetPackage(MAJOR)
if APkg and (APkg.nVersion or 0) >= MINOR then
return -- no upgrade is needed
end
local GeminiAddon = APkg and APkg.tPackage or {}
-- Upvalues
local error, type, tostring, select, pairs = error, type, tostring, select, pairs
local setmetatable, getmetatable, xpcall = setmetatable, getmetatable, xpcall
local assert, loadstring, rawset, next, unpack = assert, loadstring, rawset, next, unpack
local tconcat, tinsert, tremove, ostime = table.concat, table.insert, table.remove, os.time
local strformat = string.format
-- Wildstar APIs
local Apollo, ApolloTimer, GameLib = Apollo, ApolloTimer, GameLib
-- Package tables
GeminiAddon.Addons = GeminiAddon.Addons or {} -- addon collection
GeminiAddon.AddonStatus = GeminiAddon.AddonStatus or {} -- status of addons
GeminiAddon.Timers = GeminiAddon.Timers or {} -- Timers for OnEnable
local mtGenTable = { __index = function(tbl, key) tbl[key] = {} return tbl[key] end }
-- per addon lists
GeminiAddon.Embeds = GeminiAddon.Embeds or setmetatable({}, mtGenTable)
GeminiAddon.InitializeQueue = GeminiAddon.InitializeQueue or setmetatable({}, mtGenTable) -- addons that are new and not initialized
GeminiAddon.EnableQueue = GeminiAddon.EnableQueue or setmetatable({}, mtGenTable) -- addons awaiting to be enabled
-- Check if the player unit is available
local function IsPlayerInWorld()
return GameLib.GetPlayerUnit() ~= nil
end
local tLibError = Apollo.GetPackage("Gemini:LibError-1.0")
local fnErrorHandler = tLibError and tLibError.tPackage and tLibError.tPackage.Error or Print
-- xpcall safecall implementation
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, fnErrorHandler)
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, fnErrorHandler)
end
local function safecall(func, ...)
if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...)
end
end
local function AddonToString(self)
return self.Name
end
local Enable, Disable, Embed, GetName, SetEnabledState, AddonLog
local EmbedModule, EnableModule, DisableModule, NewModule, GetModule, SetDefaultModulePrototype, SetDefaultModuleState, SetDefaultModulePackages
-- delay the firing the OnEnable callback until after Character is in world
-- and OnRestore would have occured
local function DelayedEnable(oAddon)
local strName = oAddon:GetName()
if GameLib.GetPlayerUnit() == nil then
-- If the Player Unit doesn't exist we wait for the CharacterCreated event instead
GeminiAddon.Timers[strName] = nil
Apollo.RegisterEventHandler("CharacterCreated", "___OnDelayEnable", oAddon)
return
end
local tEnableQueue = GeminiAddon.EnableQueue[strName]
while #tEnableQueue > 0 do
local oAddonToEnable = tremove(tEnableQueue, 1)
GeminiAddon:EnableAddon(oAddonToEnable)
end
-- Cleanup
GeminiAddon.EnableQueue[strName] = nil
GeminiAddon.Timers[strName] = nil
Apollo.RemoveEventHandler("CharacterCreated", oAddon)
oAddon.___OnDelayEnable = nil
end
local function NewAddonProto(strInitAddon, oAddonOrName, oNilOrName)
local oAddon, strAddonName
-- get addon name
if type(oAddonOrName) == "table" then
oAddon = oAddonOrName
strAddonName = oNilOrName
else
strAddonName = oAddonOrName
end
oAddon = oAddon or {}
oAddon.Name = strAddonName
-- use existing metatable if exists
local addonmeta = {}
local oldmeta = getmetatable(oAddon)
if oldmeta then
for k,v in pairs(oldmeta) do addonmeta[k] = v end
end
addonmeta.__tostring = AddonToString
setmetatable(oAddon, addonmeta)
-- setup addon skeleton
GeminiAddon.Addons[strAddonName] = oAddon
oAddon.Modules = {}
oAddon.OrderedModules = {}
oAddon.DefaultModulePackages = {}
-- Embed any packages that are needed
Embed( oAddon )
-- Add to Queue of Addons to be Initialized during OnLoad
tinsert(GeminiAddon.InitializeQueue[strInitAddon], oAddon)
return oAddon
end
-- Create a new addon using GeminiAddon
-- The final addon object will be returned.
-- @paramsig [object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]
-- @param object Table to use as the base for the addon (optional)
-- @param strAddonName Name of the addon object to create
-- @param bOnConfigure Add a button to the options list and fire OnConfigure when clicked. Instead of issuing true, you can pass custom text for the button.
-- @param tDependencies List of dependencies for the addon
-- @param strPkgName List of packages to embed into the addon - requires the packages to be registered with Apollo.RegisterPackage and for the packages to support embedding
-- @usage
-- -- Create a simple addon
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", false)
--
-- -- Create a simple addon with a configure button with custom text
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", "Addon Options Button")
--
-- -- Create a simple addon with a configure button and a dependency on ChatLog / ChatLogEx
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", true, { "ChatLog", "ChatLogEx" })
--
-- -- Create an addon with a base object
-- local tAddonBase = { config = { ... some default settings ... }, ... }
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon(tAddonBase, "MyAddon", false)
--
-- -- Create an addon with a base object with a dependency on ChatLog / ChatLogEx
-- local tAddonBase = { config = { ... some default settings ... }, ... }
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon(tAddonBase, "MyAddon", false, { "ChatLog", "ChatLogEx" })
function GeminiAddon:NewAddon(oAddonOrName, ...)
local oAddon, strAddonName
local oNilOrName = nil
local i = 1
-- get addon name
if type(oAddonOrName) == "table" then
strAddonName = ...
oNilOrName = strAddonName
i = 2
else
strAddonName = oAddonOrName
end
if type(strAddonName) ~= "string" then
error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - string expected got '%s'."):format(type(strAddonName)), 2)
end
if self.Addons[strAddonName] then
error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - Addon '%s' already registered in GeminiAddon."):format(strAddonName), 2)
end
-- get configure state
local strConfigBtnName = select(i, ...)
i = i + 1
local bConfigure = (strConfigBtnName == true or type(strConfigBtnName) == "string")
if bConfigure then
strConfigBtnName = type(strConfigBtnName) == "boolean" and strAddonName or strConfigBtnName
else
strConfigBtnName = ""
end
-- get dependencies
local tDependencies
if select(i,...) and type(select(i, ...)) == "table" then
tDependencies = select(i, ...)
i = i + 1
else
tDependencies = {}
end
local oAddon = NewAddonProto(strAddonName, oAddonOrName, oNilOrName)
self:EmbedPackages(oAddon, select(i, ...))
-- Setup callbacks for the addon
-- Setup the OnLoad callback handler to initialize the addon
-- and delay enable the addon
oAddon.OnLoad = function(self)
local strName = self:GetName()
local tInitQueue = GeminiAddon.InitializeQueue[strName]
while #tInitQueue > 0 do
local oAddonToInit = tremove(tInitQueue, 1)
local retVal = GeminiAddon:InitializeAddon(oAddonToInit)
if retVal ~= nil then
Apollo.AddAddonErrorText(self, retVal)
return retVal
end
tinsert(GeminiAddon.EnableQueue[strName], oAddonToInit)
end
GeminiAddon.InitializeQueue[strName] = nil
self.___OnDelayEnable = function() DelayedEnable(self) end
-- Wait 0 seconds (hah?) this allows OnRestore to have occured
GeminiAddon.Timers[strName] = ApolloTimer.Create(0, false, "___OnDelayEnable",self)
end
-- Register with Apollo
Apollo.RegisterAddon(oAddon, bConfigure, strConfigBtnName, tDependencies)
return oAddon
end
-- Get the addon object by its name from the internal GeminiAddon addon registry
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @param strAddonName the addon name registered with GeminiAddon
-- @param bSilent return nil if addon is not found instead of throwing an error
-- @usage
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("MyAddon")
function GeminiAddon:GetAddon(strAddonName, bSilent)
if not bSilent and not self.Addons[strAddonName] then
error(("Usage: GetAddon(strAddonName): 'strAddonName' - Cannot find an GeminiAddon called '%s'."):format(tostring(strAddonName)), 2)
end
return self.Addons[strAddonName]
end
--- Enable the addon
-- Used internally when the player has entered the world
--
-- **Note:** do not call this manually
-- @param oAddon addon object to enable
function GeminiAddon:EnableAddon(oAddon)
if type(oAddon) == "string" then
oAddon = self:GetAddon(oAddon)
end
local strAddonName = AddonToString(oAddon)
if self.AddonStatus[strAddonName] or not oAddon.EnabledState then
return false
end
-- set status first before calling OnEnable. this allows for Disabling of the addon in OnEnable.
self.AddonStatus[strAddonName] = true
safecall(oAddon.OnEnable, oAddon)
if self.AddonStatus[strAddonName] then
-- embed packages
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
safecall(oPkg.OnEmbedEnable, oPkg, oAddon)
end
end
-- enable modules
local tModules = oAddon.OrderedModules
for i = 1, #tModules do
self:EnableAddon(tModules[i])
end
end
return self.AddonStatus[strAddonName]
end
function GeminiAddon:DisableAddon(oAddon)
if type(oAddon) == "string" then
oAddon = self:GetAddon(oAddon)
end
local strAddonName = AddonToString(oAddon)
if not self.AddonStatus[strAddonName] then
return false
end
-- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable.
self.AddonStatus[strAddonName] = false
safecall( oAddon.OnDisable, oAddon )
if not self.AddonStatus[strAddonName] then
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
safecall(oPkg.OnEmbedDisable, oPkg, oAddon)
end
end
local tModules = oAddon.OrderedModules
for i = 1, #tModules do
self:DisableAddon(tModules[i])
end
end
return not self.AddonStatus[strAddonName]
end
--- Initialize the addon after creation
-- Used internally when OnLoad is called for the addon
--
-- **Note:** do not call this manually
-- @param oAddon addon object to initialize
function GeminiAddon:InitializeAddon(oAddon)
local _, retVal = safecall(oAddon.OnInitialize, oAddon)
if retVal ~= nil then return retVal end
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
local _, retVal = safecall(oPkg.OnEmbedInitialize, oPkg, oAddon)
if retVal ~= nil then return retVal end
end
end
end
--- Embed packages into the specified addon
-- @paramsig oAddon[, strPkgName, ...]
-- @param oAddon The addon object to embed packages in
-- @param strPkgName List of packages to embed into the addon
function GeminiAddon:EmbedPackages(oAddon, ...)
for i = 1, select('#', ...) do
local strPkgName = select(i, ...)
self:EmbedPackage(oAddon, strPkgName, false, 4)
end
end
--- Embed a package into the specified addon
--
-- **Note:** This function is for internal use by :EmbedPackages
-- @paramsig strAddonName, strPkgName[, silent[, offset]]
-- @param oAddon addon object to embed the package in
-- @param strPkgName name of the package to embed
-- @param bSilent marks an embed to fail silently if the package doesn't exist (optional)
-- @param nOffset will push the error messages back to said offset, defaults to 2 (optional)
function GeminiAddon:EmbedPackage(oAddon, strPkgName, bSilent, nOffset)
local APkg = Apollo.GetPackage(strPkgName)
local oPkg = APkg and APkg.tPackage or nil
if not oPkg and not bSilent then
error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): 'strPkgName' - Cannot find a package instance of '%s'."):format(tostring(strPkgName)), nOffset or 2)
elseif oPkg and type(oPkg.Embed) == "function" then
oPkg:Embed(oAddon)
tinsert(self.Embeds[oAddon], strPkgName)
return true
elseif oPkg then
error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): Package '%s' is not Embed capable."):format(tostring(strPkgName)), nOffset 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 strModuleName[, bSilent]
-- @param strModuleName unique name of the module
-- @param bSilent if true, the module is optional, silently return nil if its not found (optional)
-- @usage
-- local MyModule = MyAddon:GetModule("MyModule")
function GetModule(self, strModuleName, bSilent)
if not self.Modules[strModuleName] and not bSilent then
error(("Usage: GetModule(strModuleName, bSilent): 'strModuleName' - Cannot find module '%s'."):format(tostring(strModuleName)), 2)
end
return self.Modules[strModuleName]
end
local function IsModuleTrue(self) return true end
--- Create a new module for the addon.
-- The new module can have its own embedded packages and/or use a module prototype to be mixed into the module.
-- @name //addon//:NewModule
-- @paramsig strName[, oPrototype|strPkgName[, strPkgName, ...]]
-- @param strName unique name of the module
-- @param oPrototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
-- @param strPkgName List of packages to embed into the module
-- @usage
-- -- Create a module with some embeded packages
-- local MyModule = MyAddon:NewModule("MyModule", "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0")
--
-- -- Create a module with a prototype
-- local oPrototype = { OnEnable = function(self) Print("OnEnable called!") end }
-- local MyModule = MyAddon:NewModule("MyModule", oPrototype, "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0")
function NewModule(self, strName, oPrototype, ...)
if type(strName) ~= "string" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - string expected got '%s'."):format(type(strName)), 2) end
if type(oPrototype) ~= "string" and type(oPrototype) ~= "table" and type(oPrototype) ~= "nil" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'oPrototype' - table (oPrototype), string (strPkgName) or nil expected got '%s'."):format(type(oPrototype)), 2) end
if self.Modules[strName] then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - Module '%s' already exists."):format(strName), 2) end
-- Go up the family tree to find the addon that started it all
local oCurrParent, oNextParent = self, self.Parent
while oNextParent do
oCurrParent = oNextParent
oNextParent = oCurrParent.Parent
end
local oModule = NewAddonProto(oCurrParent:GetName(), strformat("%s_%s", self:GetName() or tostring(self), strName))
oModule.IsModule = IsModuleTrue
oModule:SetEnabledState(self.DefaultModuleState)
oModule.ModuleName = strName
oModule.Parent = self
if type(oPrototype) == "string" then
GeminiAddon:EmbedPackages(oModule, oPrototype, ...)
else
GeminiAddon:EmbedPackages(oModule, ...)
end
GeminiAddon:EmbedPackages(oModule, unpack(self.DefaultModulePackages))
if not oPrototype or type(oPrototype) == "string" then
oPrototype = self.DefaultModulePrototype or nil
--self:_Log("Using Prototype type: " .. tostring(oPrototype))
end
if type(oPrototype) == "table" then
local mt = getmetatable(oModule)
mt.__index = oPrototype
setmetatable(oModule, mt)
end
safecall(self.OnModuleCreated, self, oModule)
self.Modules[strName] = oModule
tinsert(self.OrderedModules, oModule)
return oModule
end
--- returns the name of the addon or module without any prefix
-- @name //addon|module//:GetName
-- @paramsig
-- @usage
-- Print(MyAddon:GetName())
-- Print(MyAddon:GetModule("MyModule"):GetName())
function GetName(self)
return self.ModuleName or self.Name
end
-- Check if the addon is queued to be enabled
local function QueuedForInitialization(oAddon)
for strAddonName, tAddonList in pairs(GeminiAddon.EnableQueue) do
for nIndex = 1, #tAddonList do
if tAddonList[nIndex] == oAddon then
return true
end
end
end
return false
end
--- Enables the addon, if possible, returns true on success.
-- This internally calls GeminiAddon:EnableAddon(), thus dispatching the OnEnable callback
-- and enabling all modules on the addon (unless explicitly disabled)
-- :Enable() also sets the internal `enableState` variable to true.
-- @name //addon//:Enable
-- @paramsig
-- @usage
function Enable(self)
self:SetEnabledState(true)
if not QueuedForInitialization(self) then
return GeminiAddon:EnableAddon(self)
end
end
function Disable(self)
self:SetEnabledState(false)
return GeminiAddon: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
-- local MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
--
-- -- Enable MyModule using the short-hand
-- MyAddon:EnableModule("MyModule")
function EnableModule(self, strModuleName)
local oModule = self:GetModule(strModuleName)
return oModule: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
-- local MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Disable()
--
-- -- Disable MyModule using the short-hand
-- local MyAddon:DisableModule("MyModule")
function DisableModule(self, strModuleName)
local oModule = self:GetModule(strModuleName)
return oModule:Disable()
end
--- Set the default packages to be mixed into all modules created by this object.
-- Note that you can only change the default module packages before any module is created.
-- @name //addon//:SetDefaultModulePackages
-- @paramsig strPkgName[, strPkgName, ...]
-- @param strPkgName List of Packages to embed into the addon
-- @usage
-- -- Create the addon object
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon")
-- -- Configure default packages for modules
-- MyAddon:SetDefaultModulePackages("MyEmbeddablePkg-1.0")
-- -- Create a module
-- local MyModule = MyAddon:NewModule("MyModule")
function SetDefaultModulePackages(self, ...)
if next(self.Modules) then
error("Usage: SetDefaultModulePackages(...): cannot change the module defaults after a module has been registered.", 2)
end
self.DefaultModulePackages = {...}
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
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon")
-- -- Set the default state to "disabled"
-- MyAddon:SetDefaultModuleState(false)
-- -- Create a module and explicilty enable it
-- local MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
function SetDefaultModuleState(self, bState)
if next(self.Modules) then
error("Usage: SetDefaultModuleState(bState): cannot change the module defaults after a module has been registered.", 2)
end
self.DefaultModuleState = bState
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
-- local MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
-- -- should Print "OnEnable called!" now
-- @see NewModule
function SetDefaultModulePrototype(self, tPrototype)
if next(self.Modules) then
error("Usage: SetDefaultModulePrototype(tPrototype): cannot change the module defaults after a module has been registered.", 2)
end
if type(tPrototype) ~= "table" then
error(("Usage: SetDefaultModulePrototype(tPrototype): 'tPrototype' - table expected got '%s'."):format(type(tPrototype)), 2)
end
self.DefaultModulePrototype = tPrototype
end
--- Set the state of an addon or module
-- This should only be called before any enabling actually happened, e.g. in/before OnInitialize.
-- @name //addon|module//:SetEnabledState
-- @paramsig state
-- @param state the state of an addon or module (enabled = true, disabled = false)
function SetEnabledState(self, bState)
self.EnabledState = bState
end
--- Return an iterator of all modules associated to the addon.
-- @name //addon//:IterateModules
-- @paramsig
-- @usage
-- -- Enable all modules
-- for strModuleName, oModule in MyAddon:IterateModules() do
-- oModule: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(GeminiAddon.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 function IsModule(self) return false end
function AddonLog(self, t)
self._DebugLog = self._DebugLog or {}
tinsert(self._DebugLog, { what = t, when = ostime() })
end
local tMixins = {
NewModule = NewModule,
GetModule = GetModule,
Enable = Enable,
Disable = Disable,
EnableModule = EnableModule,
DisableModule = DisableModule,
IsEnabled = IsEnabled,
SetDefaultModulePackages = SetDefaultModulePackages,
SetDefaultModuleState = SetDefaultModuleState,
SetDefaultModulePrototype = SetDefaultModulePrototype,
SetEnabledState = SetEnabledState,
IterateModules = IterateModules,
IterateEmbeds = IterateEmbeds,
GetName = GetName,
-- _Log = AddonLog,
DefaultModuleState = true,
EnabledState = true,
IsModule = IsModule,
}
-- Embed( target )
-- target (object) - target GeminiAddon object to embed in
--
-- **Note:** This is for internal use only. Do not call manually
function Embed(target)
for k, v in pairs(tMixins) do
target[k] = v
end
end
--- Get an iterator over all registered addons.
-- @usage
-- -- Print a list of all registered GeminiAddons
-- for name, addon in GeminiAddon:IterateAddons() do
-- Print("Addon: " .. name)
-- end
function GeminiAddon: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 GeminiAddon:IterateAddonStatus() do
-- if status then
-- Print("EnabledAddon: " .. name)
-- end
-- end
function GeminiAddon:IterateAddonStatus() return pairs(self.AddonStatus) end
function GeminiAddon:OnLoad() end
function GeminiAddon:OnDependencyError(strDep, strError) return false end
Apollo.RegisterPackage(GeminiAddon, MAJOR, MINOR, {})
| mit |
arpanpal010/awesome | obvious/lib/widget/graph.lua | 1 | 1397 | -----------------------------------
-- Author: Uli Schlachter --
-- Copyright 2009 Uli Schlachter --
-----------------------------------
local beautiful = require("beautiful")
local awful = {
widget = require("awful.widget")
}
local setmetatable = setmetatable
module("obvious.lib.widget.graph")
function graph(layout, scale)
local theme = beautiful.get()
local color = theme.graph_fg_color or theme.widget_fg_color or theme.fg_normal
local back = theme.graph_bg_color or theme.widget_bg_color or theme.bg_normal
local border= theme.graph_border or theme.widget_border or theme.border_normal
local width = theme.graph_width or theme.widget_width
local widget = awful.widget.graph({ layout = layout })
widget:set_color(color)
widget:set_border_color(border)
widget:set_background_color(back)
if width then
widget:set_width(width)
end
if scale then
widget:set_scale(true)
end
return widget
end
function create(data, layout)
local scale = true
if data.max then
scale = false
end
local widget = graph(layout, scale)
widget.update = function(widget)
local max = widget.data.max or 1
local val = widget.data:get() or max
widget:add_value(val / max)
end
widget.data = data
return widget
end
setmetatable(_M, { __call = function (_, ...) return graph(...) end })
-- vim:ft=lua:ts=2:sw=2:sts=2:tw=80:fenc=utf-8:et
| mit |
RunAwayDSP/darkstar | scripts/globals/abilities/fighters_roll.lua | 12 | 2893 | -----------------------------------
-- Ability: Fighter's Roll
-- Improves "Double Attack" rate for party members within area of effect
-- Optimal Job: Warrior
-- Lucky Number: 5
-- Unlucky Number: 9
-- Level: 49
-- Phantom Roll +1 Value: 1
--
-- Die Roll |No WAR |With WAR
-- -------- -------- -----------
-- 1 |2% |8%
-- 2 |2% |8%
-- 3 |3% |9%
-- 4 |4% |10%
-- 5 |12% |18%
-- 6 |5% |11%
-- 7 |6% |12%
-- 8 |7% |13%
-- 9 |1% |7%
-- 10 |9% |15%
-- 11 |18% |24%
-- 12+ |-6% |-6%
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/ability")
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = dsp.effect.FIGHTERS_ROLL
ability:setRange(ability:getRange() + player:getMod(dsp.mod.ROLL_RANGE))
if (player:hasStatusEffect(effectID)) then
return dsp.msg.basic.ROLL_ALREADY_ACTIVE,0
elseif atMaxCorsairBusts(player) then
return dsp.msg.basic.CANNOT_PERFORM,0
else
return 0,0
end
end
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, dsp.effect.FIGHTERS_ROLL, dsp.job.WAR)
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(dsp.merit.WINNING_STREAK) + caster:getMod(dsp.mod.PHANTOM_DURATION)
local effectpowers = {2, 2, 3, 4, 12, 5, 6, 7, 1, 9, 18, 6}
local effectpower = effectpowers[total]
if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then
effectpower = effectpower + 6
end
-- Apply Additional Phantom Roll+ Buff
local phantomBase = 1 -- Base increment buff
local effectpower = effectpower + (phantomBase * phantombuffMultiple(caster))
-- Check if COR Main or Sub
if (caster:getMainJob() == dsp.job.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl())
elseif (caster:getSubJob() == dsp.job.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl())
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(dsp.merit.BUST_DURATION), dsp.effect.FIGHTERS_ROLL, effectpower, 0, duration, caster:getID(), total, dsp.mod.DOUBLE_ATTACK) == false) then
ability:setMsg(dsp.msg.basic.ROLL_MAIN_FAIL)
elseif total > 11 then
ability:setMsg(dsp.msg.basic.DOUBLEUP_BUST)
end
return total
end
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/spells/armys_paeon_iii.lua | 12 | 1374 | -----------------------------------------
-- Spell: Army's Paeon III
-- Gradually restores target's HP.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(dsp.skill.SINGING) -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(dsp.slot.RANGED)
local power = 3
if (sLvl+iLvl > 200) then
power = power + 1
end
local iBoost = caster:getMod(dsp.mod.PAEON_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT)
power = power + iBoost
if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then
power = power * 2
elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then
power = power * 1.5
end
caster:delStatusEffect(dsp.effect.MARCATO)
local duration = 120
duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1)
if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then
duration = duration * 2
end
if not (target:addBardSong(caster,dsp.effect.PAEON,power,0,duration,caster:getID(), 0, 3)) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
return dsp.effect.PAEON
end
| gpl-3.0 |
lichtl/darkstar | scripts/globals/spells/blind.lua | 20 | 1377 | -----------------------------------------
-- Spell: Blind
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
-- Pull base stats.
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_MND)); --blind uses caster INT vs target MND
-- Base power. May need more research.
local power = math.floor((dINT + 60) / 4);
if (power < 5) then
power = 5;
end
if (power > 20) then
power = 20;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
power = power * 2;
end
-- Duration, including resistance. Unconfirmed.
local duration = 120 * applyResistanceEffect(caster,spell,target,dINT,35,0,EFFECT_BLINDNESS);
if (duration >= 60) then --Do it!
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
if (target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
return EFFECT_BLINDNESS;
end;
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/QuBia_Arena/bcnms/die_by_the_sword.lua | 9 | 1062 | -----------------------------------
-- Die by the Sword
-- Qu'Bia Arena BCNM30, Sky Orb
-- !additem 1552
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
taiha/luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-app.lua | 22 | 15547 | cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
app_alarmreceiver = module:option(ListValue, "app_alarmreceiver", "Alarm Receiver Application", "")
app_alarmreceiver:value("yes", "Load")
app_alarmreceiver:value("no", "Do Not Load")
app_alarmreceiver:value("auto", "Load as Required")
app_alarmreceiver.rmempty = true
app_authenticate = module:option(ListValue, "app_authenticate", "Authentication Application", "")
app_authenticate:value("yes", "Load")
app_authenticate:value("no", "Do Not Load")
app_authenticate:value("auto", "Load as Required")
app_authenticate.rmempty = true
app_cdr = module:option(ListValue, "app_cdr", "Make sure asterisk doesn't save CDR", "")
app_cdr:value("yes", "Load")
app_cdr:value("no", "Do Not Load")
app_cdr:value("auto", "Load as Required")
app_cdr.rmempty = true
app_chanisavail = module:option(ListValue, "app_chanisavail", "Check if channel is available", "")
app_chanisavail:value("yes", "Load")
app_chanisavail:value("no", "Do Not Load")
app_chanisavail:value("auto", "Load as Required")
app_chanisavail.rmempty = true
app_chanspy = module:option(ListValue, "app_chanspy", "Listen in on any channel", "")
app_chanspy:value("yes", "Load")
app_chanspy:value("no", "Do Not Load")
app_chanspy:value("auto", "Load as Required")
app_chanspy.rmempty = true
app_controlplayback = module:option(ListValue, "app_controlplayback", "Control Playback Application", "")
app_controlplayback:value("yes", "Load")
app_controlplayback:value("no", "Do Not Load")
app_controlplayback:value("auto", "Load as Required")
app_controlplayback.rmempty = true
app_cut = module:option(ListValue, "app_cut", "Cuts up variables", "")
app_cut:value("yes", "Load")
app_cut:value("no", "Do Not Load")
app_cut:value("auto", "Load as Required")
app_cut.rmempty = true
app_db = module:option(ListValue, "app_db", "Database access functions", "")
app_db:value("yes", "Load")
app_db:value("no", "Do Not Load")
app_db:value("auto", "Load as Required")
app_db.rmempty = true
app_dial = module:option(ListValue, "app_dial", "Dialing Application", "")
app_dial:value("yes", "Load")
app_dial:value("no", "Do Not Load")
app_dial:value("auto", "Load as Required")
app_dial.rmempty = true
app_dictate = module:option(ListValue, "app_dictate", "Virtual Dictation Machine Application", "")
app_dictate:value("yes", "Load")
app_dictate:value("no", "Do Not Load")
app_dictate:value("auto", "Load as Required")
app_dictate.rmempty = true
app_directed_pickup = module:option(ListValue, "app_directed_pickup", "Directed Call Pickup Support", "")
app_directed_pickup:value("yes", "Load")
app_directed_pickup:value("no", "Do Not Load")
app_directed_pickup:value("auto", "Load as Required")
app_directed_pickup.rmempty = true
app_directory = module:option(ListValue, "app_directory", "Extension Directory", "")
app_directory:value("yes", "Load")
app_directory:value("no", "Do Not Load")
app_directory:value("auto", "Load as Required")
app_directory.rmempty = true
app_disa = module:option(ListValue, "app_disa", "DISA (Direct Inward System Access) Application", "")
app_disa:value("yes", "Load")
app_disa:value("no", "Do Not Load")
app_disa:value("auto", "Load as Required")
app_disa.rmempty = true
app_dumpchan = module:option(ListValue, "app_dumpchan", "Dump channel variables Application", "")
app_dumpchan:value("yes", "Load")
app_dumpchan:value("no", "Do Not Load")
app_dumpchan:value("auto", "Load as Required")
app_dumpchan.rmempty = true
app_echo = module:option(ListValue, "app_echo", "Simple Echo Application", "")
app_echo:value("yes", "Load")
app_echo:value("no", "Do Not Load")
app_echo:value("auto", "Load as Required")
app_echo.rmempty = true
app_enumlookup = module:option(ListValue, "app_enumlookup", "ENUM Lookup", "")
app_enumlookup:value("yes", "Load")
app_enumlookup:value("no", "Do Not Load")
app_enumlookup:value("auto", "Load as Required")
app_enumlookup.rmempty = true
app_eval = module:option(ListValue, "app_eval", "Reevaluates strings", "")
app_eval:value("yes", "Load")
app_eval:value("no", "Do Not Load")
app_eval:value("auto", "Load as Required")
app_eval.rmempty = true
app_exec = module:option(ListValue, "app_exec", "Executes applications", "")
app_exec:value("yes", "Load")
app_exec:value("no", "Do Not Load")
app_exec:value("auto", "Load as Required")
app_exec.rmempty = true
app_externalivr = module:option(ListValue, "app_externalivr", "External IVR application interface", "")
app_externalivr:value("yes", "Load")
app_externalivr:value("no", "Do Not Load")
app_externalivr:value("auto", "Load as Required")
app_externalivr.rmempty = true
app_forkcdr = module:option(ListValue, "app_forkcdr", "Fork The CDR into 2 separate entities", "")
app_forkcdr:value("yes", "Load")
app_forkcdr:value("no", "Do Not Load")
app_forkcdr:value("auto", "Load as Required")
app_forkcdr.rmempty = true
app_getcpeid = module:option(ListValue, "app_getcpeid", "Get ADSI CPE ID", "")
app_getcpeid:value("yes", "Load")
app_getcpeid:value("no", "Do Not Load")
app_getcpeid:value("auto", "Load as Required")
app_getcpeid.rmempty = true
app_groupcount = module:option(ListValue, "app_groupcount", "Group Management Routines", "")
app_groupcount:value("yes", "Load")
app_groupcount:value("no", "Do Not Load")
app_groupcount:value("auto", "Load as Required")
app_groupcount.rmempty = true
app_ices = module:option(ListValue, "app_ices", "Encode and Stream via icecast and ices", "")
app_ices:value("yes", "Load")
app_ices:value("no", "Do Not Load")
app_ices:value("auto", "Load as Required")
app_ices.rmempty = true
app_image = module:option(ListValue, "app_image", "Image Transmission Application", "")
app_image:value("yes", "Load")
app_image:value("no", "Do Not Load")
app_image:value("auto", "Load as Required")
app_image.rmempty = true
app_lookupblacklist = module:option(ListValue, "app_lookupblacklist", "Look up Caller*ID name/number from black", "")
app_lookupblacklist:value("yes", "Load")
app_lookupblacklist:value("no", "Do Not Load")
app_lookupblacklist:value("auto", "Load as Required")
app_lookupblacklist.rmempty = true
app_lookupcidname = module:option(ListValue, "app_lookupcidname", "Look up CallerID Name from local databas", "")
app_lookupcidname:value("yes", "Load")
app_lookupcidname:value("no", "Do Not Load")
app_lookupcidname:value("auto", "Load as Required")
app_lookupcidname.rmempty = true
app_macro = module:option(ListValue, "app_macro", "Extension Macros", "")
app_macro:value("yes", "Load")
app_macro:value("no", "Do Not Load")
app_macro:value("auto", "Load as Required")
app_macro.rmempty = true
app_math = module:option(ListValue, "app_math", "A simple math Application", "")
app_math:value("yes", "Load")
app_math:value("no", "Do Not Load")
app_math:value("auto", "Load as Required")
app_math.rmempty = true
app_md5 = module:option(ListValue, "app_md5", "MD5 checksum Application", "")
app_md5:value("yes", "Load")
app_md5:value("no", "Do Not Load")
app_md5:value("auto", "Load as Required")
app_md5.rmempty = true
app_milliwatt = module:option(ListValue, "app_milliwatt", "Digital Milliwatt (mu-law) Test Application", "")
app_milliwatt:value("yes", "Load")
app_milliwatt:value("no", "Do Not Load")
app_milliwatt:value("auto", "Load as Required")
app_milliwatt.rmempty = true
app_mixmonitor = module:option(ListValue, "app_mixmonitor", "Record a call and mix the audio during the recording", "")
app_mixmonitor:value("yes", "Load")
app_mixmonitor:value("no", "Do Not Load")
app_mixmonitor:value("auto", "Load as Required")
app_mixmonitor.rmempty = true
app_parkandannounce = module:option(ListValue, "app_parkandannounce", "Call Parking and Announce Application", "")
app_parkandannounce:value("yes", "Load")
app_parkandannounce:value("no", "Do Not Load")
app_parkandannounce:value("auto", "Load as Required")
app_parkandannounce.rmempty = true
app_playback = module:option(ListValue, "app_playback", "Trivial Playback Application", "")
app_playback:value("yes", "Load")
app_playback:value("no", "Do Not Load")
app_playback:value("auto", "Load as Required")
app_playback.rmempty = true
app_privacy = module:option(ListValue, "app_privacy", "Require phone number to be entered", "")
app_privacy:value("yes", "Load")
app_privacy:value("no", "Do Not Load")
app_privacy:value("auto", "Load as Required")
app_privacy.rmempty = true
app_queue = module:option(ListValue, "app_queue", "True Call Queueing", "")
app_queue:value("yes", "Load")
app_queue:value("no", "Do Not Load")
app_queue:value("auto", "Load as Required")
app_queue.rmempty = true
app_random = module:option(ListValue, "app_random", "Random goto", "")
app_random:value("yes", "Load")
app_random:value("no", "Do Not Load")
app_random:value("auto", "Load as Required")
app_random.rmempty = true
app_read = module:option(ListValue, "app_read", "Read Variable Application", "")
app_read:value("yes", "Load")
app_read:value("no", "Do Not Load")
app_read:value("auto", "Load as Required")
app_read.rmempty = true
app_readfile = module:option(ListValue, "app_readfile", "Read in a file", "")
app_readfile:value("yes", "Load")
app_readfile:value("no", "Do Not Load")
app_readfile:value("auto", "Load as Required")
app_readfile.rmempty = true
app_realtime = module:option(ListValue, "app_realtime", "Realtime Data Lookup/Rewrite", "")
app_realtime:value("yes", "Load")
app_realtime:value("no", "Do Not Load")
app_realtime:value("auto", "Load as Required")
app_realtime.rmempty = true
app_record = module:option(ListValue, "app_record", "Trivial Record Application", "")
app_record:value("yes", "Load")
app_record:value("no", "Do Not Load")
app_record:value("auto", "Load as Required")
app_record.rmempty = true
app_sayunixtime = module:option(ListValue, "app_sayunixtime", "Say time", "")
app_sayunixtime:value("yes", "Load")
app_sayunixtime:value("no", "Do Not Load")
app_sayunixtime:value("auto", "Load as Required")
app_sayunixtime.rmempty = true
app_senddtmf = module:option(ListValue, "app_senddtmf", "Send DTMF digits Application", "")
app_senddtmf:value("yes", "Load")
app_senddtmf:value("no", "Do Not Load")
app_senddtmf:value("auto", "Load as Required")
app_senddtmf.rmempty = true
app_sendtext = module:option(ListValue, "app_sendtext", "Send Text Applications", "")
app_sendtext:value("yes", "Load")
app_sendtext:value("no", "Do Not Load")
app_sendtext:value("auto", "Load as Required")
app_sendtext.rmempty = true
app_setcallerid = module:option(ListValue, "app_setcallerid", "Set CallerID Application", "")
app_setcallerid:value("yes", "Load")
app_setcallerid:value("no", "Do Not Load")
app_setcallerid:value("auto", "Load as Required")
app_setcallerid.rmempty = true
app_setcdruserfield = module:option(ListValue, "app_setcdruserfield", "CDR user field apps", "")
app_setcdruserfield:value("yes", "Load")
app_setcdruserfield:value("no", "Do Not Load")
app_setcdruserfield:value("auto", "Load as Required")
app_setcdruserfield.rmempty = true
app_setcidname = module:option(ListValue, "app_setcidname", "load => .so ; Set CallerID Name", "")
app_setcidname:value("yes", "Load")
app_setcidname:value("no", "Do Not Load")
app_setcidname:value("auto", "Load as Required")
app_setcidname.rmempty = true
app_setcidnum = module:option(ListValue, "app_setcidnum", "load => .so ; Set CallerID Number", "")
app_setcidnum:value("yes", "Load")
app_setcidnum:value("no", "Do Not Load")
app_setcidnum:value("auto", "Load as Required")
app_setcidnum.rmempty = true
app_setrdnis = module:option(ListValue, "app_setrdnis", "Set RDNIS Number", "")
app_setrdnis:value("yes", "Load")
app_setrdnis:value("no", "Do Not Load")
app_setrdnis:value("auto", "Load as Required")
app_setrdnis.rmempty = true
app_settransfercapability = module:option(ListValue, "app_settransfercapability", "Set ISDN Transfer Capability", "")
app_settransfercapability:value("yes", "Load")
app_settransfercapability:value("no", "Do Not Load")
app_settransfercapability:value("auto", "Load as Required")
app_settransfercapability.rmempty = true
app_sms = module:option(ListValue, "app_sms", "SMS/PSTN handler", "")
app_sms:value("yes", "Load")
app_sms:value("no", "Do Not Load")
app_sms:value("auto", "Load as Required")
app_sms.rmempty = true
app_softhangup = module:option(ListValue, "app_softhangup", "Hangs up the requested channel", "")
app_softhangup:value("yes", "Load")
app_softhangup:value("no", "Do Not Load")
app_softhangup:value("auto", "Load as Required")
app_softhangup.rmempty = true
app_stack = module:option(ListValue, "app_stack", "Stack Routines", "")
app_stack:value("yes", "Load")
app_stack:value("no", "Do Not Load")
app_stack:value("auto", "Load as Required")
app_stack.rmempty = true
app_system = module:option(ListValue, "app_system", "Generic System() application", "")
app_system:value("yes", "Load")
app_system:value("no", "Do Not Load")
app_system:value("auto", "Load as Required")
app_system.rmempty = true
app_talkdetect = module:option(ListValue, "app_talkdetect", "Playback with Talk Detection", "")
app_talkdetect:value("yes", "Load")
app_talkdetect:value("no", "Do Not Load")
app_talkdetect:value("auto", "Load as Required")
app_talkdetect.rmempty = true
app_test = module:option(ListValue, "app_test", "Interface Test Application", "")
app_test:value("yes", "Load")
app_test:value("no", "Do Not Load")
app_test:value("auto", "Load as Required")
app_test.rmempty = true
app_transfer = module:option(ListValue, "app_transfer", "Transfer", "")
app_transfer:value("yes", "Load")
app_transfer:value("no", "Do Not Load")
app_transfer:value("auto", "Load as Required")
app_transfer.rmempty = true
app_txtcidname = module:option(ListValue, "app_txtcidname", "TXTCIDName", "")
app_txtcidname:value("yes", "Load")
app_txtcidname:value("no", "Do Not Load")
app_txtcidname:value("auto", "Load as Required")
app_txtcidname.rmempty = true
app_url = module:option(ListValue, "app_url", "Send URL Applications", "")
app_url:value("yes", "Load")
app_url:value("no", "Do Not Load")
app_url:value("auto", "Load as Required")
app_url.rmempty = true
app_userevent = module:option(ListValue, "app_userevent", "Custom User Event Application", "")
app_userevent:value("yes", "Load")
app_userevent:value("no", "Do Not Load")
app_userevent:value("auto", "Load as Required")
app_userevent.rmempty = true
app_verbose = module:option(ListValue, "app_verbose", "Send verbose output", "")
app_verbose:value("yes", "Load")
app_verbose:value("no", "Do Not Load")
app_verbose:value("auto", "Load as Required")
app_verbose.rmempty = true
app_voicemail = module:option(ListValue, "app_voicemail", "Voicemail", "")
app_voicemail:value("yes", "Load")
app_voicemail:value("no", "Do Not Load")
app_voicemail:value("auto", "Load as Required")
app_voicemail.rmempty = true
app_waitforring = module:option(ListValue, "app_waitforring", "Waits until first ring after time", "")
app_waitforring:value("yes", "Load")
app_waitforring:value("no", "Do Not Load")
app_waitforring:value("auto", "Load as Required")
app_waitforring.rmempty = true
app_waitforsilence = module:option(ListValue, "app_waitforsilence", "Wait For Silence Application", "")
app_waitforsilence:value("yes", "Load")
app_waitforsilence:value("no", "Do Not Load")
app_waitforsilence:value("auto", "Load as Required")
app_waitforsilence.rmempty = true
app_while = module:option(ListValue, "app_while", "While Loops and Conditional Execution", "")
app_while:value("yes", "Load")
app_while:value("no", "Do Not Load")
app_while:value("auto", "Load as Required")
app_while.rmempty = true
return cbimap
| apache-2.0 |
scscgit/scsc_wildstar_addons | RaidCore/RaidCore_GUI.lua | 1 | 24117 | ----------------------------------------------------------------------------------------------------
-- Client Lua Script for RaidCore Addon on WildStar Game.
--
-- Copyright (C) 2015 RaidCore
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- Description:
--
-- TODO
--
----------------------------------------------------------------------------------------------------
local Apollo = require "Apollo"
local GameLib = require "GameLib"
local GeminiLocale = Apollo.GetPackage("Gemini:Locale-1.0").tPackage
local Log = Apollo.GetPackage("Log-1.0").tPackage
local RaidCore = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("RaidCore")
----------------------------------------------------------------------------------------------------
-- Copy of few objects to reduce the cpu load.
-- Because all local objects are faster.
----------------------------------------------------------------------------------------------------
local next, assert, error, ipairs = next, assert, error, ipairs
local GetGameTime = GameLib.GetGameTime
----------------------------------------------------------------------------------------------------
-- local data.
----------------------------------------------------------------------------------------------------
local ShowHideClass = {}
local _wndUploadAction
local _wndLogGrid
local _wndLogSize
local _wndLogErrorCount
local _wndLogEventsCount
local _bShowHidePanelActive
local _TestTimer = nil
----------------------------------------------------------------------------------------------------
-- Constants.
----------------------------------------------------------------------------------------------------
local COPY_TO_CLIPBOARD = GameLib.CodeEnumConfirmButtonType.CopyToClipboard
local SHOW_HIDE_PANEL_ENCOUNTER_DURATION = 0.60
local SHOW_HIDE_PANEL_ENCOUNTER_MOVE = 155
local SHOW_HIDE_PANEL_LOG_MOVE = 120
local SHOW_HIDE_PANEL_GENERAL_MOVE = 120
----------------------------------------------------------------------------------------------------
-- local functions.
----------------------------------------------------------------------------------------------------
local function OnMenuLeft_CheckUncheck(wndButton, bIsChecked)
local sButtonName = wndButton:GetName()
local wnd = bIsChecked and RaidCore.LeftMenu2wndBody[sButtonName] or RaidCore.wndBodyTarget:GetData()
if wnd then
wnd:Show(bIsChecked)
wnd = bIsChecked and wnd
end
RaidCore.wndBodyTarget:SetData(wnd)
end
local function CopyLog2Clipboard(tDumpLog)
local JSONPackage = Apollo.GetPackage("Lib:dkJSON-2.5").tPackage
local sJSONData = JSONPackage.encode(tDumpLog)
sJSONData = sJSONData:gsub("%],%[", "],\n [")
sJSONData = sJSONData:gsub("%[%[", "[\n [")
sJSONData = sJSONData:gsub("%]%]", "]\n]")
if sJSONData then
local JSONLen = sJSONData:len()
if JSONLen < 1000 then
_wndLogSize:SetText(("(%u B)"):format(JSONLen))
elseif JSONLen < (1000 * 1000) then
_wndLogSize:SetText(("(%.1f kB)"):format(JSONLen / 1000.0))
else
_wndLogSize:SetText(("(%.1f MB)"):format(JSONLen / (1000.0 * 1000.0)))
end
if JSONLen > 0 then
_wndUploadAction:SetActionData(COPY_TO_CLIPBOARD, sJSONData)
_wndUploadAction:Show(true)
end
end
end
local function ClearLogGrid()
-- Clear current Grid data.
_wndLogGrid:DeleteAll()
_wndLogErrorCount:SetText("0")
_wndLogEventsCount:SetText("0")
_wndLogSize:SetText("")
_wndUploadAction:Show(false)
end
local function FillLogGrid(tDumpLog)
local nErrorCount = 0
for _, tLog in ipairs(tDumpLog) do
local idx = _wndLogGrid:AddRow("")
_wndLogGrid:SetCellSortText(idx, 1, ("%08u"):format(idx))
_wndLogGrid:SetCellText(idx, 1, ("%.3f"):format(tLog[1]))
_wndLogGrid:SetCellText(idx, 2, tLog[2])
_wndLogGrid:SetCellText(idx, 3, tLog[3])
-- Increase error counter on error logged.
if tLog[2] == RaidCore.E.ERROR then
nErrorCount = nErrorCount + 1
end
end
_wndLogErrorCount:SetText(tostring(nErrorCount))
_wndLogEventsCount:SetText(tostring(#tDumpLog))
end
local function Split(str, sep)
assert(str)
sep = sep or "%s"
local r = {}
for match in string.gmatch(str, "([^"..sep.."]+)") do
table.insert(r, match)
end
return r
end
----------------------------------------------------------------------------------------------------
-- ShowHide Class manager.
----------------------------------------------------------------------------------------------------
function ShowHideClass:OnShowHideUpdate(nCurrentTime)
if not _bShowHidePanelActive then return end
local left, right
local nEncounterDelta = RaidCore.nShowHideEncounterPanelTime - nCurrentTime
local nLogDelta = RaidCore.nShowHideLogPanelTime - nCurrentTime
local nSettingsDelta = RaidCore.nShowHideSettingsPanelTime - nCurrentTime
nEncounterDelta = nEncounterDelta > 0 and nEncounterDelta or 0
nLogDelta = nLogDelta > 0 and nLogDelta or 0
nSettingsDelta = nSettingsDelta > 0 and nSettingsDelta or 0
-- Manage ENCOUNTER panels.
local nPourcentAction = 1 - nEncounterDelta / SHOW_HIDE_PANEL_ENCOUNTER_DURATION
-- Manage the encounter panel list.
if RaidCore.bIsEncounterPanelsToShow then
left = RaidCore.tEncounterListAnchorOffsets[1] - SHOW_HIDE_PANEL_ENCOUNTER_MOVE * nPourcentAction
left = left > -SHOW_HIDE_PANEL_ENCOUNTER_MOVE and left or -SHOW_HIDE_PANEL_ENCOUNTER_MOVE
right = RaidCore.tEncounterListAnchorOffsets[3] - SHOW_HIDE_PANEL_ENCOUNTER_MOVE * nPourcentAction
right = right > (200 - SHOW_HIDE_PANEL_ENCOUNTER_MOVE) and right or (200 - SHOW_HIDE_PANEL_ENCOUNTER_MOVE)
else
left = RaidCore.tEncounterListAnchorOffsets[1] + SHOW_HIDE_PANEL_ENCOUNTER_MOVE * nPourcentAction
left = left < 0 and left or 0
right = RaidCore.tEncounterListAnchorOffsets[3] + SHOW_HIDE_PANEL_ENCOUNTER_MOVE * nPourcentAction
right = right < 200 and right or 200
end
RaidCore.wndEncounterList:SetAnchorOffsets(left, RaidCore.tEncounterListAnchorOffsets[2], right, RaidCore.tEncounterListAnchorOffsets[4])
-- Manage the encounter panel target.
if RaidCore.bIsEncounterPanelsToShow then
left = RaidCore.tEncounterTargetAnchorOffsets[1] - SHOW_HIDE_PANEL_ENCOUNTER_MOVE * nPourcentAction
left = left > (205 - SHOW_HIDE_PANEL_ENCOUNTER_MOVE) and left or (205 - SHOW_HIDE_PANEL_ENCOUNTER_MOVE)
else
left = RaidCore.tEncounterTargetAnchorOffsets[1] + SHOW_HIDE_PANEL_ENCOUNTER_MOVE * nPourcentAction
left = left < 205 and left or 205
end
RaidCore.wndEncounterTarget:SetAnchorOffsets(left, RaidCore.tEncounterTargetAnchorOffsets[2], RaidCore.tEncounterTargetAnchorOffsets[3], RaidCore.tEncounterTargetAnchorOffsets[4])
-- Manage LOGS panels.
local nLogPourcentAction = 1 - nLogDelta / SHOW_HIDE_PANEL_ENCOUNTER_DURATION
-- Manage the log panel list.
if RaidCore.bIsLogsPanelsToShow then
left = RaidCore.tLogsListAnchorOffsets[1] - SHOW_HIDE_PANEL_LOG_MOVE * nLogPourcentAction
left = left > -SHOW_HIDE_PANEL_LOG_MOVE and left or -SHOW_HIDE_PANEL_LOG_MOVE
right = RaidCore.tLogsListAnchorOffsets[3] - SHOW_HIDE_PANEL_LOG_MOVE * nLogPourcentAction
right = right > (150 - SHOW_HIDE_PANEL_LOG_MOVE) and right or (150 - SHOW_HIDE_PANEL_LOG_MOVE)
else
left = RaidCore.tLogsListAnchorOffsets[1] + SHOW_HIDE_PANEL_LOG_MOVE * nLogPourcentAction
left = left < 0 and left or 0
right = RaidCore.tLogsListAnchorOffsets[3] + SHOW_HIDE_PANEL_LOG_MOVE * nLogPourcentAction
right = right < 150 and right or 150
end
RaidCore.wndLogSubMenu:SetAnchorOffsets(left, RaidCore.tLogsListAnchorOffsets[2], right, RaidCore.tLogsListAnchorOffsets[4])
-- Manage the log panel target.
if RaidCore.bIsLogsPanelsToShow then
left = RaidCore.tLogsTargetAnchorOffsets[1] - SHOW_HIDE_PANEL_LOG_MOVE * nLogPourcentAction
left = left > (155 - SHOW_HIDE_PANEL_LOG_MOVE) and left or (155 - SHOW_HIDE_PANEL_LOG_MOVE)
else
left = RaidCore.tLogsTargetAnchorOffsets[1] + SHOW_HIDE_PANEL_LOG_MOVE * nLogPourcentAction
left = left < 155 and left or 155
end
RaidCore.wndLogTarget:SetAnchorOffsets(left, RaidCore.tLogsTargetAnchorOffsets[2], RaidCore.tLogsTargetAnchorOffsets[3], RaidCore.tLogsTargetAnchorOffsets[4])
-- Manage SETTINGS panels.
local nSettingsPourcentAction = 1 - nSettingsDelta / SHOW_HIDE_PANEL_ENCOUNTER_DURATION
-- Manage the settings sub menu.
if RaidCore.bIsSettingsPanelsToShow then
left = RaidCore.tSettingsListAnchorOffsets[1] - SHOW_HIDE_PANEL_GENERAL_MOVE * nSettingsPourcentAction
left = left > -SHOW_HIDE_PANEL_GENERAL_MOVE and left or -SHOW_HIDE_PANEL_GENERAL_MOVE
right = RaidCore.tSettingsListAnchorOffsets[3] - SHOW_HIDE_PANEL_GENERAL_MOVE * nSettingsPourcentAction
right = right > (150 - SHOW_HIDE_PANEL_GENERAL_MOVE) and right or (150 - SHOW_HIDE_PANEL_GENERAL_MOVE)
else
left = RaidCore.tSettingsListAnchorOffsets[1] + SHOW_HIDE_PANEL_GENERAL_MOVE * nSettingsPourcentAction
left = left < 0 and left or 0
right = RaidCore.tSettingsListAnchorOffsets[3] + SHOW_HIDE_PANEL_GENERAL_MOVE * nSettingsPourcentAction
right = right < 150 and right or 150
end
RaidCore.wndSettingsSubMenu:SetAnchorOffsets(left, RaidCore.tSettingsListAnchorOffsets[2], right, RaidCore.tSettingsListAnchorOffsets[4])
-- Manage the settings panel target.
if RaidCore.bIsSettingsPanelsToShow then
left = RaidCore.tSettingsTargetAnchorOffsets[1] - SHOW_HIDE_PANEL_GENERAL_MOVE * nSettingsPourcentAction
left = left > (155 - SHOW_HIDE_PANEL_GENERAL_MOVE) and left or (155 - SHOW_HIDE_PANEL_GENERAL_MOVE)
else
left = RaidCore.tSettingsTargetAnchorOffsets[1] + SHOW_HIDE_PANEL_GENERAL_MOVE * nSettingsPourcentAction
left = left < 155 and left or 155
end
RaidCore.wndSettingsTarget:SetAnchorOffsets(left, RaidCore.tSettingsTargetAnchorOffsets[2], RaidCore.tSettingsTargetAnchorOffsets[3], RaidCore.tSettingsTargetAnchorOffsets[4])
if nEncounterDelta == 0 and nLogDelta == 0 and nSettingsDelta == 0 then
_bShowHidePanelActive = false
RaidCore:StopNextFrame()
end
end
function ShowHideClass:StartUpdate()
if not _bShowHidePanelActive then
_bShowHidePanelActive = true
RaidCore:StartNextFrame()
end
end
----------------------------------------------------------------------------------------------------
-- Public functions.
----------------------------------------------------------------------------------------------------
function RaidCore:OnGUINextFrame(nCurrentTime)
ShowHideClass:OnShowHideUpdate(nCurrentTime)
end
function RaidCore:GUI_init(sVersion)
self.wndMain = Apollo.LoadForm(self.xmlDoc, "ConfigMain", nil, self)
self.wndMain:FindChild("Tag"):SetText(sVersion)
self.wndMain:SetSizingMinimum(950, 500)
self.wndBodyTarget = self.wndMain:FindChild("BodyTarget")
self.LeftMenu2wndBody = {
General = Apollo.LoadForm(self.xmlDoc, "ConfigBody_Settings", self.wndBodyTarget, self),
Encounters = Apollo.LoadForm(self.xmlDoc, "ConfigBody_Encounters", self.wndBodyTarget, self),
Logs = Apollo.LoadForm(self.xmlDoc, "ConfigBody_Logs", self.wndBodyTarget, self),
About_Us = Apollo.LoadForm(self.xmlDoc, "ConfigBody_AboutUs", self.wndBodyTarget, self),
}
for _, wnd in next, self.LeftMenu2wndBody do
GeminiLocale:TranslateWindow(self.L, wnd)
end
self.wndEncounterTarget = self.LeftMenu2wndBody.Encounters:FindChild("Encounter_Target")
self.wndEncounterList = self.LeftMenu2wndBody.Encounters:FindChild("Encounter_List")
self.tEncounterListAnchorOffsets = { self.wndEncounterList:GetAnchorOffsets() }
self.tEncounterTargetAnchorOffsets = { self.wndEncounterTarget:GetAnchorOffsets() }
self.wndLogTarget = self.LeftMenu2wndBody.Logs:FindChild("Log_Target")
self.wndLogSubMenu = self.LeftMenu2wndBody.Logs:FindChild("Log_SubMenu")
self.tLogsListAnchorOffsets = { self.wndLogSubMenu:GetAnchorOffsets() }
self.tLogsTargetAnchorOffsets = { self.wndLogTarget:GetAnchorOffsets() }
self.wndSettingsSubMenu = self.LeftMenu2wndBody.General:FindChild("SettingsSubMenu")
self.wndSettingsTarget = self.LeftMenu2wndBody.General:FindChild("SettingsTarget")
self.tSettingsListAnchorOffsets = { self.wndSettingsSubMenu:GetAnchorOffsets() }
self.tSettingsTargetAnchorOffsets = { self.wndSettingsTarget:GetAnchorOffsets() }
self.wndEncounters = {
PrimeEvolutionaryOperant = Apollo.LoadForm(self.xmlDoc, "ConfigForm_CoreY83", self.wndEncounterTarget, self),
ExperimentX89 = Apollo.LoadForm(self.xmlDoc, "ConfigForm_ExperimentX89", self.wndEncounterTarget, self),
Kuralak = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Kuralak", self.wndEncounterTarget, self),
Prototypes = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Prototypes", self.wndEncounterTarget, self),
Phagemaw = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Phagemaw", self.wndEncounterTarget, self),
PhageCouncil = Apollo.LoadForm(self.xmlDoc, "ConfigForm_PhageCouncil", self.wndEncounterTarget, self),
Ohmna = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Ohmna", self.wndEncounterTarget, self),
Minibosses = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Minibosses", self.wndEncounterTarget, self),
SystemDaemons = Apollo.LoadForm(self.xmlDoc, "ConfigForm_SystemDaemons", self.wndEncounterTarget, self),
Gloomclaw = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Gloomclaw", self.wndEncounterTarget, self),
Maelstrom = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Maelstrom", self.wndEncounterTarget, self),
Lattice = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Lattice", self.wndEncounterTarget, self),
LimboInfomatrix = Apollo.LoadForm(self.xmlDoc, "ConfigForm_LimboInfomatrix", self.wndEncounterTarget, self),
AirEarth = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpAirEarth", self.wndEncounterTarget, self),
AirLife = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpAirLife", self.wndEncounterTarget, self),
AirWater = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpAirWater", self.wndEncounterTarget, self),
FireEarth = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpFireEarth", self.wndEncounterTarget, self),
FireLife = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpFireLife", self.wndEncounterTarget, self),
FireWater = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpFireWater", self.wndEncounterTarget, self),
LogicEarth = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpLogicEarth", self.wndEncounterTarget, self),
LogicLife = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpLogicLife", self.wndEncounterTarget, self),
LogicWater = Apollo.LoadForm(self.xmlDoc, "ConfigForm_EpLogicWater", self.wndEncounterTarget, self),
Avatus = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Avatus", self.wndEncounterTarget, self),
Shredder = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Shredder", self.wndEncounterTarget, self),
MinibossesRedmoon = Apollo.LoadForm(self.xmlDoc, "ConfigForm_MinibossesRedmoon", self.wndEncounterTarget, self),
Robomination = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Robomination", self.wndEncounterTarget, self),
Engineers = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Engineers", self.wndEncounterTarget, self),
Mordechai = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Mordechai", self.wndEncounterTarget, self),
Octog = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Octog", self.wndEncounterTarget, self),
Starmap = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Starmap", self.wndEncounterTarget, self),
Laveka = Apollo.LoadForm(self.xmlDoc, "ConfigForm_Laveka", self.wndEncounterTarget, self),
}
-- Initialize Left Menu in Main RaidCore window.
local wndGeneralButton = self.wndMain:FindChild("Static"):FindChild("General")
wndGeneralButton:SetCheck(true)
OnMenuLeft_CheckUncheck(wndGeneralButton, true)
-- Initialize the Show/Hide button in "encounter" body.
self.LeftMenu2wndBody.Encounters:FindChild("ShowHidePanel"):SetCheck(true)
self.nShowHideEncounterPanelTime = 0
-- Initialize the Show/Hide button in "log" body.
self.LeftMenu2wndBody.Logs:FindChild("ShowHidePanel"):SetCheck(true)
self.nShowHideLogPanelTime = 0
-- Initialize the Show/Hide button in "settings" body.
self.LeftMenu2wndBody.General:FindChild("ShowHidePanel"):SetCheck(true)
self.nShowHideSettingsPanelTime = 0
self.wndSettingsSubMenu:FindChild("Bars"):SetCheck(true)
self.wndSettingsTarget:SetData(self.wndSettingsTarget:FindChild("Bars"))
-- Initialize the "log" windows.
_wndUploadAction = self.LeftMenu2wndBody.Logs:FindChild("UploadAction")
_wndLogGrid = self.wndLogTarget:FindChild("Log_Grid")
_wndLogErrorCount = self.wndLogTarget:FindChild("ErrorsCount")
_wndLogEventsCount = self.wndLogTarget:FindChild("EventsCount")
_wndLogSize = self.wndLogTarget:FindChild("LogSize")
-- Registering to Windows Manager.
Apollo.RegisterEventHandler(RaidCore.E.EVENT_WINDOWS_MANAGEMENT_READY, "OnWindowManagementReady", self)
self:OnWindowManagementReady() --Already is ready
Apollo.RegisterEventHandler(RaidCore.E.EVENT_DISPLAY_RAIDCORE_WINDOW, "DisplayMainWindow", self)
self:AddToInterfaceMenuList()
end
function RaidCore:OnWindowManagementReady()
local param = { wnd = self.wndMain, strName = "RaidCore" }
Event_FireGenericEvent("WindowManagementRegister", param)
Event_FireGenericEvent("WindowManagementAdd", param)
end
function RaidCore:AddToInterfaceMenuList()
Event_FireGenericEvent("InterfaceMenuList_NewAddOn", "RaidCore", {RaidCore.E.EVENT_DISPLAY_RAIDCORE_WINDOW, "", "IconSprites:Icon_Windows_UI_CRB_FieldStudy_Playful"})
end
----------------------------------------------------------------------------------------------------
-- Public "form" functions.
----------------------------------------------------------------------------------------------------
function RaidCore:DisplayMainWindow()
self.wndMain:Invoke()
end
function RaidCore:OnClose()
self.wndMain:Close()
end
function RaidCore:OnMenuLeft_Check(wndHandler, wndControl, eMouseButton)
OnMenuLeft_CheckUncheck(wndControl, true)
end
function RaidCore:OnMenuLeft_Uncheck(wndHandler, wndControl, eMouseButton)
OnMenuLeft_CheckUncheck(wndControl, false)
end
function RaidCore:OnEncounterListShowHide(wndHandler, wndControl, eMouseButton)
local bState = wndControl:IsChecked()
self.tEncounterListAnchorOffsets = { self.wndEncounterList:GetAnchorOffsets() }
self.tEncounterTargetAnchorOffsets = { self.wndEncounterTarget:GetAnchorOffsets() }
self.bIsEncounterPanelsToShow = not bState
self.nShowHideEncounterPanelTime = GetGameTime() + SHOW_HIDE_PANEL_ENCOUNTER_DURATION
self:PlaySound("DoorFutur")
ShowHideClass:StartUpdate()
end
function RaidCore:OnEncounterCheck(wndHandler, wndControl, eMouseButton)
local wnd = self.wndEncounters[wndControl:GetName()]
if wnd then
wnd:Show(true)
end
self.wndEncounterTarget:SetData(wnd)
end
function RaidCore:OnEncounterUncheck(wndHandler, wndControl, eMouseButton)
local wnd = self.wndEncounterTarget:GetData()
if wnd then
wnd:Show(false)
end
self.wndEncounterTarget:SetData(nil)
end
function RaidCore:OnLogListShowHide(wndHandler, wndControl, eMouseButton)
self.tLogsListAnchorOffsets = { self.wndLogSubMenu:GetAnchorOffsets() }
self.tLogsTargetAnchorOffsets = { self.wndLogTarget:GetAnchorOffsets() }
self.bIsLogsPanelsToShow = not wndControl:IsChecked()
self.nShowHideLogPanelTime = GetGameTime() + SHOW_HIDE_PANEL_ENCOUNTER_DURATION
self:PlaySound("DoorFutur")
ShowHideClass:StartUpdate()
end
function RaidCore:OnLogLoadCurrentBuffer(wndHandler, wndControl, eMouseButton)
-- Clear current Grid data.
ClearLogGrid()
-- Retrieve current buffer.
local tDumpLog = Log:CurrentDump()
-- Update GUI
if tDumpLog and next(tDumpLog) then
FillLogGrid(tDumpLog)
CopyLog2Clipboard(tDumpLog)
end
end
function RaidCore:OnLogLoadPreviousBuffer(wndHandler, wndControl, eMouseButton)
-- Clear current Grid data.
ClearLogGrid()
-- Retrieve previous buffer.
local tDumpLog = Log:PreviousDump()
-- Update GUI
if tDumpLog and next(tDumpLog) then
FillLogGrid(tDumpLog)
CopyLog2Clipboard(tDumpLog)
end
end
function RaidCore:OnSettingsListShowHide(wndHandler, wndControl, eMouseButton)
self.tSettingsListAnchorOffsets = { self.wndSettingsSubMenu:GetAnchorOffsets() }
self.tSettingsTargetAnchorOffsets = { self.wndSettingsTarget:GetAnchorOffsets() }
self.bIsSettingsPanelsToShow = not wndControl:IsChecked()
self.nShowHideSettingsPanelTime = GetGameTime() + SHOW_HIDE_PANEL_ENCOUNTER_DURATION
self:PlaySound("DoorFutur")
ShowHideClass:StartUpdate()
end
function RaidCore:OnSettingsCheck(wndHandler, wndControl, eMouseButton)
local sTargetName = wndControl:GetName()
local wndTarget = self.wndSettingsTarget:FindChild(sTargetName)
if wndTarget then
wndTarget:Show(true)
self.wndSettingsTarget:SetData(wndTarget)
end
end
function RaidCore:OnSettingsUncheck(wndHandler, wndControl, eMouseButton)
local wndTarget = self.wndSettingsTarget:GetData()
if wndTarget then
wndTarget:Show(false)
end
end
-- When the Test button is pushed.
function RaidCore:OnTestScenarioButton(wndHandler, wndControl, eMouseButton)
local bIsChecked = wndControl:IsChecked()
if bIsChecked then
wndControl:SetText(self.L["Stop test scenario"])
self:OnStartTestScenario()
_TestTimer = self:ScheduleTimer(function(wndControlInner)
wndControlInner:SetCheck(false)
wndControlInner:SetText(self.L["Start test scenario"])
self:OnStopTestScenario()
end,
60, wndControl
)
else
self:CancelTimer(_TestTimer, true)
wndControl:SetText(self.L["Start test scenario"])
self:OnStopTestScenario()
end
end
-- When the Reset button is clicked.
function RaidCore:OnResetBarsButton(wndHandler, wndControl, eMouseButton)
self:BarsResetAnchors()
end
-- When the Move button is pushed.
function RaidCore:OnMoveBarsButton(wndHandler, wndControl, eMouseButton)
local bIsChecked = wndControl:IsChecked()
if bIsChecked then
wndControl:SetText(self.L["Lock Bars"])
self:BarsAnchorUnlock(true)
else
wndControl:SetText(self.L["Move Bars"])
self:BarsAnchorUnlock(false)
end
end
function RaidCore:OnWindowLoad(wndHandler, wndControl)
local a, b, c = unpack(Split(wndControl:GetName(), '_'))
local val = nil
if c then
val = self.db.profile[a][b][c]
elseif b then
val = self.db.profile[a][b]
elseif a then
val = self.db.profile[a]
end
if val == nil then
error((("Value not found in DB for keys: [%s][%s][%s]"):format(tostring(a), tostring(b), tostring(c))))
end
if wndControl.SetCheck then
wndControl:SetCheck(val)
end
if type(val) == "boolean" or a == "Encounters" then
wndControl:SetCheck(val)
elseif type(val) == "number" or type(val) == "string" then
wndControl:SetText(val)
if wndControl.SetValue and type(val) == "number" then
wndControl:SetValue(val)
end
end
end
function RaidCore:OnButtonCheckBoxSwitched(wndHandler, wndControl, eMouseButton)
local a, b, c = unpack(Split(wndControl:GetName(), '_'))
if c then
self.db.profile[a][b][c] = wndControl:IsChecked()
elseif b then
self.db.profile[a][b] = wndControl:IsChecked()
else
self.db.profile[a] = wndControl:IsChecked()
end
end
function RaidCore:OnEditBoxChanged(wndHandler, wndControl, eMouseButton)
local a, b, c = unpack(Split(wndControl:GetName(), '_'))
if c then
self.db.profile[a][b][c] = wndControl:GetText()
elseif b then
self.db.profile[a][b] = wndControl:GetText()
else
self.db.profile[a] = wndControl:GetText()
end
end
function RaidCore:OnGeneralSettingsSliderBarChanged(wndHandler, wndControl, nNewValue, fOldValue)
local sName = wndControl:GetName()
local a, b, c = unpack(Split(sName, '_'))
nNewValue = math.floor(nNewValue)
for _, wnd in next, wndControl:GetParent():GetParent():GetChildren() do
if wnd:GetName() == sName then
wnd:SetText(nNewValue)
break
end
end
if c then
self.db.profile[a][b][c] = nNewValue
elseif b then
self.db.profile[a][b] = nNewValue
else
self.db.profile[a] = nNewValue
end
end
| mit |
lichtl/darkstar | scripts/zones/Abyssea-Altepa/npcs/qm11.lua | 14 | 1541 | -----------------------------------
-- Zone: Abyssea-Altepa
-- NPC: qm11 (???)
-- Spawns Rani
-- @pos ? ? ? 218
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17670551) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(BROKEN_IRON_GIANT_SPIKE) and player:hasKeyItem(RUSTED_CHARIOT_GEAR)) then
player:startEvent(1020, BROKEN_IRON_GIANT_SPIKE, RUSTED_CHARIOT_GEAR); -- Ask if player wants to use KIs
else
player:startEvent(1021, BROKEN_IRON_GIANT_SPIKE, RUSTED_CHARIOT_GEAR); -- Do not ask, because player is missing at least 1.
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);
if (csid == 1020 and option == 1) then
SpawnMob(17670551):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(BROKEN_IRON_GIANT_SPIKE);
player:delKeyItem(RUSTED_CHARIOT_GEAR);
end
end;
| gpl-3.0 |
GPUOpen-Effects/ShadowFX | amd_lib/shared/d3d11/premake/premake5.lua | 1 | 2372 | dofile ("../../../../premake/amd_premake_util.lua")
workspace "AMD_LIB"
configurations { "Debug", "Release", "Release_MT" }
platforms { "Win32", "x64" }
location "../build"
filename ("AMD_LIB" .. _AMD_VS_SUFFIX)
startproject "AMD_LIB"
filter "platforms:Win32"
system "Windows"
architecture "x86"
filter "platforms:x64"
system "Windows"
architecture "x64"
project "AMD_LIB"
kind "StaticLib"
language "C++"
location "../build"
filename ("AMD_LIB" .. _AMD_VS_SUFFIX)
uuid "0D2AEA47-7909-69E3-8221-F4B9EE7FCF44"
targetdir "../lib"
objdir "../build/%{_AMD_LIBRARY_DIR_LAYOUT}"
warnings "Extra"
floatingpoint "Fast"
exceptionhandling "Off"
rtti "Off"
-- Specify WindowsTargetPlatformVersion here for VS2015
systemversion (_AMD_WIN_SDK_VERSION)
files { "../inc/**.h", "../src/**.h", "../src/**.cpp", "../src/**.inl", "../src/**.hlsl", "../../common/inc/*.h", "../../../ags_lib/inc/*.h" }
includedirs { "../inc", "../../common/inc", "../../../ags_lib/inc" }
filter "configurations:Debug"
defines { "WIN32", "_DEBUG", "_WINDOWS", "_LIB", "_WIN32_WINNT=0x0601" }
flags { "FatalWarnings" }
symbols "On"
characterset "Unicode"
-- add "d" to the end of the library name for debug builds
targetsuffix "d"
filter "configurations:Release"
defines { "WIN32", "NDEBUG", "_WINDOWS", "_LIB", "_WIN32_WINNT=0x0601" }
flags { "FatalWarnings" }
characterset "Unicode"
optimize "On"
filter "configurations:Release_MT"
defines { "WIN32", "NDEBUG", "_WINDOWS", "_LIB", "_WIN32_WINNT=0x0601" }
flags { "FatalWarnings" }
characterset "Unicode"
-- link against the static runtime to avoid introducing a dependency
-- on the particular version of Visual Studio used to build the DLLs
flags { "StaticRuntime" }
-- add "mt" to the end of the library name for Release_MT builds
targetsuffix "mt"
optimize "On"
filter "action:vs*"
-- specify exception handling model for Visual Studio to avoid
-- "'noexcept' used with no exception handling mode specified"
-- warning in vs2015
buildoptions { "/EHsc" }
filter "platforms:Win32"
targetname "amd_lib_x86%{_AMD_VS_SUFFIX}"
filter "platforms:x64"
targetname "amd_lib_x64%{_AMD_VS_SUFFIX}"
| mit |
lichtl/darkstar | scripts/zones/Temple_of_Uggalepih/npcs/Treasure_Coffer.lua | 13 | 4653 | -----------------------------------
-- Area: Temple of Uggalepih
-- NPC: Treasure Coffer
-- @zone 159
-- @pos -219 0 32
-----------------------------------
package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Temple_of_Uggalepih/TextIDs");
local TreasureType = "Coffer";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1049,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(1049,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
-- IMPORTANT ITEM: AF Keyitems, AF Items, & Map -----------
local mJob = player:getMainJob();
local zone = player:getZoneID();
local listAF = getAFbyZone(zone);
if (player:hasKeyItem(MAP_OF_THE_TEMPLE_OF_UGGALEPIH) == false) then
questItemNeeded = 3;
end
for nb = 1,#listAF,3 do
if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then
questItemNeeded = 2;
break
end
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 == 3) then
player:addKeyItem(MAP_OF_THE_TEMPLE_OF_UGGALEPIH);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_TEMPLE_OF_UGGALEPIH); -- Map of the Temple of Uggalepih (KI)
elseif (questItemNeeded == 2) then
for nb = 1,#listAF,3 do
if (mJob == listAF[nb]) then
player:addItem(listAF[nb + 2]);
player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]);
break
end
end
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]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
else
player:messageSpecial(CHEST_MIMIC);
spawnMimic(zone,npc,player);
UpdateTreasureSpawnPoint(npc:getID(), true);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1049);
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 |
RunAwayDSP/darkstar | scripts/globals/spells/frazzle.lua | 12 | 1626 | -----------------------------------------
-- Spell: Frazzle
-----------------------------------------
require("scripts/globals/magic")
require("scripts/globals/msg")
require("scripts/globals/status")
require("scripts/globals/utils")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local dMND = caster:getStat(dsp.mod.MND) - target:getStat(dsp.mod.MND)
-- Base magic evasion reduction is determend by enfeebling skill
-- Caps at -25 magic evasion at 125 skill
local basePotency = utils.clamp(math.floor(caster:getSkillLevel(dsp.skill.ENFEEBLING_MAGIC) / 5), 0, 25)
-- dMND is tacked on after
-- Min cap: 0 at 0 dMND
-- Max cap: 10 at 50 dMND
basePotency = basePotency + utils.clamp(math.floor(dMND / 5), 0, 10)
local power = calculatePotency(basePotency, spell:getSkillType(), caster, target)
local duration = calculateDuration(120, spell:getSkillType(), spell:getSpellGroup(), caster, target)
local params = {}
params.diff = dMND
params.skillType = dsp.skill.ENFEEBLING_MAGIC
params.bonus = 0
params.effect = dsp.effect.MAGIC_EVASION_DOWN
local resist = applyResistanceEffect(caster, target, spell, params)
if resist >= 0.5 then
if target:addStatusEffect(params.effect, power, 0, duration * resist) then
spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS)
else
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
else
spell:setMsg(dsp.msg.basic.MAGIC_RESIST)
end
return params.effect
end | gpl-3.0 |
april-org/parxe | test/generic_test.lua | 1 | 3841 | --[[
PARalel eXecution Engine (PARXE) for APRIL-ANN
Copyright (C) 2015 Francisco Zamora-Martinez
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
local px = require "parxe"
-- mapping a table of data
local f1 = px.map(function(x) return 2*x end, iterator.range(1024):table())
-- mapping a matrix
local f2 = px.map(function(x) return stats.amean(x,1) end, matrix(1024,20):linspace())
-- mapping a range of 1024 numbers
local f3 = px.map(function(x) return 2*x end, 1024)
local f3 = px.map(function(x) return 2*x end, f3)
-- mapping a range of 1024 in bunches
local f4 = px.map.bunch(function(obj)
local n,a,b = #obj,obj[1],obj[#obj]
local m = matrix(#obj,20):linspace((a-1)*20+1,b*20)
return stats.amean(m,2)
end, 1024)
-- mapping a matrix in bunches
local f5 = px.map.bunch(function(x) return stats.amean(x,2) end, matrix(1024,20):linspace())
local f5 = px.map(function(x) return 2*x end, f5)
--
print(table.concat(f1:get(), ","))
print(matrix.join(0,f2:get()))
print(table.concat(f3:get(), ","))
print(matrix.join(1,f4:get()))
print(matrix.join(1,f5:get()))
local f = px.reduce(function(a,x) return a+x end, iterator.range(1024):table(), 0)
local f = px.reduce.self_distributive(lambda'|a,b|a+b', f)
local r = f:get()
print(r)
local f = px.reduce.self_distributive(function(a,b) return a+b end, iterator.range(1024):table())
local r = f:get()
print(r)
local f1 = px.run(function() return matrix(1024):linspace():sum() end)
local f2 = px.run(function() return matrix(2048):linspace():sum() end)
local f = px.future.all{f1,f2}
f:wait()
pprint(f:get())
print(f1:get())
print(f2:get())
local f1 = px.run(function() return matrix(1024):linspace():sum() end)
local f2 = px.run(function() return matrix(2048):linspace():sum() end)
local f3 = px.future.conditioned(function(x) return x/2 end,
f1 + f2 + px.future.value(20))
px.scheduler:wait()
print(f1:get())
print(f2:get())
print(f3:get())
local f = px.map(function(x) return 2*x end, {1,2,3,4})
print(f)
f:wait_until_running()
print(f)
f:wait()
print(f)
pprint(f:get())
local g = px.run(function() return matrix(1024):linspace():sum() end)
local h = g:after(function(x,a) return a*x end, 2)
local i = px.future.conditioned(function(a,x) return a*x end, 3, g)
local f = px.future.conditioned(function(a,b,c) return a+b+c end, h, i, 20)
print(f:get())
local f1 = px.run(function() return matrix(1024):linspace():sum() end)
local f2 = px.run(function() return matrix(2048):linspace():sum() end)
local f3 = px.future.conditioned(function(f1,f2,x) return (f1+f2+x)/2 end,
f1, f2, 20)
print(f3:get())
print("Running bootstrap")
local rnd = random(567)
local errors = stats.dist.normal():sample(rnd,1000)
local boot_result = px.boot{
size=errors:size(), R=1000, seed=1234, verbose=true, k=2,
statistic = function(sample)
local s = errors:index(1, sample)
local var,mean = stats.var(s)
return mean,var
end
}
local boot_result = boot_result:index(1, boot_result:select(2,1):order())
local a,b = stats.boot.ci(boot_result, 0.95)
local m,p0,pn = stats.boot.percentile(boot_result, { 0.5, 0.0, 1.0 })
print(a,b,m,p0,pn)
| gpl-3.0 |
da03/OpenNMT | onmt/utils/ExtendedCmdLine.lua | 1 | 18667 | ---------------------------------------------------------------------------------
-- Local utility functions
---------------------------------------------------------------------------------
local function wrapIndent(text, size, pad)
text = pad .. text
local p = 0
while true do
local q = text:find(" ", size+p)
if not q then
return text
end
text = text:sub(1, q) .. "\n" ..pad .. text:sub(q+1, #text)
p = q+2+#pad
end
end
local function concatValues(t)
local isBoolean
local s = ''
for _, v in ipairs(t) do
if type(v) == 'boolean' then
isBoolean = true
else
if s ~= '' then
s = s .. ', '
end
s = s .. v
end
end
if isBoolean then
s = 'true, false, ' .. s
end
return s
end
---------------------------------------------------------------------------------
local ExtendedCmdLine, parent, path
-- the utils function can be run without torch
if torch then
ExtendedCmdLine, parent = torch.class('ExtendedCmdLine', 'torch.CmdLine')
path = require('pl.path')
else
ExtendedCmdLine = {}
end
--[[
Extended handling of command line options - provide validation methods, and utilities for handling options
at module level.
For end-user - provides '-h' for help, with possible '-md' variant for preparing MD ready help file.
Provides also possibility to read options from config file with '-config file' or save current options to
config file with '-save_config file'
Example:
cmd = onmt.utils.ExtendedCmdLine.new()
local options = {
{'-max_batch_size', 64 , 'Maximum batch size', {valid=onmt.utils.ExtendedCmdLine.isUInt()}}
}
cmd:setCmdLineOptions(options, 'Optimization')
local opt = cmd:parse(arg)
local optimArgs = cmd.getModuleOpts(opt, options)
Additional meta-fields:
* `valid`: validation method
* `enum`: enumeration list
* `structural`: if defined, mark a structural parameter - 0 means cannot change value, 1 means that it can change dynamically
* `init_only`: if true, mark a parameter that can only be set at init time
* `train_state`: if true, the option will be automatically reused when continuing a training
]]
function ExtendedCmdLine:__init(script)
self.script = script
parent.__init(self)
self:text('')
self:option('-h', false, 'This help.')
self:option('-md', false, 'Dump help in Markdown format.')
self:option('-config', '', 'Load options from this file.', {valid=ExtendedCmdLine.fileNullOrExists})
self:option('-save_config', '', 'Save options to this file.')
end
function ExtendedCmdLine:help(arg, md)
if arg then
if md then
io.write('`' .. self.script .. '` options:\n')
else
io.write('Usage: ')
io.write(arg[0] .. ' ' .. self.script .. ' ')
io.write('[options] ')
for i = 1, #self.arguments do
io.write('<' .. onmt.utils.String.stripHyphens(self.arguments[i].key) .. '>')
end
io.write('\n')
end
end
for _, option in ipairs(self.helplines) do
if type(option) ~= 'table' then
if md and option:len() > 0 then
io.write('## ')
end
io.write(option)
io.write('\n')
elseif not option.meta or not option.meta.deprecatedBy then
-- Argument type.
local argType = '<' .. option.type .. '>'
if option.type == 'boolean' then
if option.meta and option.meta.enum then
argType = argType .. '/<string>'
end
argType = '[' .. argType .. ']'
end
local argMeta = {}
-- Argument constraints.
if option.meta and not option.meta.argument and option.meta.required then
table.insert(argMeta, 'required')
end
if option.meta and option.meta.enum then
if md then
for k, v in pairs(option.meta.enum) do
option.meta.enum[k] = '`' .. tostring(v) .. '`'
end
end
table.insert(argMeta, 'accepted: ' .. concatValues(option.meta.enum))
end
if not option.meta or not option.meta.argument then
-- Default value.
local argDefault
if type(option.default) == 'table' then
argDefault = table.concat(option.default, ', ')
elseif option.default == '' then
argDefault = '\'\''
else
argDefault = tostring(option.default)
end
if not (option.meta and option.meta.required and argDefault == '\'\'') and
not (type(option.default == 'table') and argDefault == '') then
if md then
argDefault = '`' .. argDefault .. '`'
end
table.insert(argMeta, 'default: ' .. argDefault)
end
end
local optionPattern = option.key .. ' ' .. argType
if option.meta and option.meta.argument then
optionPattern = '<' .. option.key .. '>'
end
if md then
io.write('* `' .. optionPattern.. '`')
else
io.write(' ' .. optionPattern)
end
if #argMeta > 0 then
io.write(' ('.. table.concat(argMeta, '; ') .. ')')
end
local description = string.gsub(option.help, ' *\n *', ' ')
if md then
io.write('<br/>')
io.write(description)
else
io.write('\n')
io.write(wrapIndent(description, 60, ' '))
io.write('\n')
end
io.write('\n')
end
end
end
function ExtendedCmdLine:error(msg)
if not self.script then
error(msg)
else
io.stderr:write(self.script .. ': ' .. msg .. '\n')
io.stderr:write('Try \'' .. self.script .. ' -h\' for more information, or visit the online documentation at http://opennmt.net/OpenNMT/.\n')
os.exit(1)
end
end
function ExtendedCmdLine:argument(key, type, help, _meta_)
for _,v in ipairs(self.helplines) do
if v.key == key then
return
end
end
onmt.utils.Error.assert(not(self.options[key]) and not(self.arguments[key]), "Duplicate options/arguments: "..key)
parent.argument(self, key, help, type)
if not _meta_ then
_meta_ = {}
end
_meta_.argument = true
self.arguments[#self.arguments].meta = _meta_
self.options[key] = { meta=_meta_}
end
function ExtendedCmdLine:option(key, default, help, _meta_)
for _,v in ipairs(self.helplines) do
if v.key == key then
return
end
end
onmt.utils.Error.assert(not(self.options[key]) and not(self.arguments[key]), "Duplicate options/arguments: "..key)
parent.option(self, key, default, help)
-- check if option correctly defined - if default value does not match validation criterion then it is either
-- empty and in that case, is a required option, or is an error
if _meta_ and (
(_meta_.valid and not _meta_.valid(default)) or
(_meta_.enum and type(default) ~= 'table' and not onmt.utils.Table.hasValue(_meta_.enum, default))) then
onmt.utils.Error.assert(default=='',"Invalid option default definition: "..key.."="..default)
_meta_.required = true
end
if _meta_ and _meta_.enum and type(default) == 'table' then
for _,k in ipairs(default) do
onmt.utils.Error.assert(onmt.utils.Table.hasValue(_meta_.enum, k), "table option not compatible with enum: "..key)
end
end
self.options[key].meta = _meta_
end
--[[ Override options with option values set in file `filename`. ]]
function ExtendedCmdLine:loadConfig(filename, opt)
local file = onmt.utils.Error.assert(io.open(filename, 'r'))
for line in file:lines() do
-- Ignore empty or commented out lines.
if line:len() > 0 and string.sub(line, 1, 1) ~= '#' then
local field = onmt.utils.String.split(line, '=')
onmt.utils.Error.assert(#field == 2, 'badly formatted config file')
local key = onmt.utils.String.strip(field[1])
local val = onmt.utils.String.strip(field[2])
-- Rely on the command line parser.
local arg = { '-' .. key }
if val == '' then
table.insert(arg, '')
else
onmt.utils.Table.append(arg, onmt.utils.String.split(val, ' '))
end
self:__readOption__(opt, arg, 1)
opt._is_default[key] = nil
end
end
file:close()
return opt
end
function ExtendedCmdLine:logConfig(opt)
local keys = {}
for key in pairs(opt) do
table.insert(keys, key)
end
table.sort(keys)
_G.logger:debug('Options:')
for _, key in ipairs(keys) do
if key:sub(1, 1) ~= '_' then
local val = opt[key]
if type(val) == 'string' then
val = '\'' .. val .. '\''
elseif type(val) == 'table' then
val = table.concat(val, ' ')
else
val = tostring(val)
end
_G.logger:debug(' * ' .. key .. ' = ' .. tostring(val))
end
end
end
function ExtendedCmdLine:dumpConfig(opt, filename)
local file = onmt.utils.Error.assert(io.open(filename, 'w'), "Cannot open file '"..filename.."' for writing")
for key, val in pairs(opt) do
if key:sub(1, 1) ~= '_' then
if type(val) == 'table' then
val = table.concat(val, ' ')
else
val = tostring(val)
end
file:write(key .. ' = ' .. val .. '\n')
end
end
file:close()
end
--[[ Convert `val` string to the target type. ]]
function ExtendedCmdLine:convert(key, val, type, subtype, meta)
if not type or type == 'string' then
val = val
elseif type == 'table' then
local values = {}
val = onmt.utils.String.split(val, ' ')
for _, v in ipairs(val) do
onmt.utils.Table.append(values, onmt.utils.String.split(v, ','))
end
for i = 1, #values do
values[i] = self:convert(key, values[i], subtype)
end
val = values
elseif type == 'number' then
val = tonumber(val)
elseif type == 'boolean' then
if val == '0' or val == 'false' then
val = false
elseif val == '1' or val == 'true' then
val = true
else
-- boolean option can take 3rd values
if not (meta and meta.enum) then
self:error('invalid argument for boolean option ' .. key .. ' (should be 0, 1, false or true)')
end
end
else
self:error('unknown required option type ' .. type)
end
if val == nil then
self:error('invalid type for option ' .. key .. ' (should be ' .. type .. ')')
end
return val
end
function ExtendedCmdLine:__readArgument__(params, arg, i, nArgument)
local argument = self.arguments[nArgument]
local value = arg[i]
if nArgument > #self.arguments then
self:error('invalid argument: ' .. value)
end
if argument.type and type(value) ~= argument.type then
self:error('invalid argument type for argument ' .. argument.key .. ' (should be ' .. argument.type .. ')')
end
params[argument.key] = value
return 1
end
function ExtendedCmdLine:__readOption__(params, arg, i)
local key = arg[i]
local option = self.options[key]
if not option then
self:error('unknown option ' .. key)
end
local multiValues = (option.type == 'table')
local argumentType
if not multiValues then
argumentType = option.type
elseif #option.default > 0 then
argumentType = type(option.default[1])
end
local values = {}
local numArguments = 0
-- browse through parameters till next potential option (starting with -Letter)
while arg[i + 1] and string.find(arg[i+1],'-%a')~=1 do
local value = self:convert(key, arg[i + 1], option.type, argumentType, option.meta)
if type(value) == 'table' then
onmt.utils.Table.append(values, value)
else
table.insert(values, value)
end
i = i + 1
numArguments = numArguments + 1
if not multiValues then
break
end
end
local optionName = onmt.utils.String.stripHyphens(key)
if #values == 0 then
if argumentType == 'boolean' then
params[optionName] = not option.default
else
self:error('missing argument(s) for option ' .. key)
end
elseif multiValues then
params[optionName] = values
elseif #values > 1 then
self:error('option ' .. key .. ' expects 1 argument but ' .. #values .. ' were given')
else
params[optionName] = values[1]
end
return numArguments + 1
end
function ExtendedCmdLine:parse(arg)
local i = 1
-- set default value
local params = { _is_default={}, _structural={}, _init_only={}, _train_state={} }
for option,v in pairs(self.options) do
local soption = onmt.utils.String.stripHyphens(option)
params[soption] = v.default
params._is_default[soption] = true
end
local nArgument = 0
local doHelp = false
local doMd = false
local readConfig
local saveConfig
local cmdlineOptions = {}
while i <= #arg do
if arg[i] == '-help' or arg[i] == '-h' or arg[i] == '--help' then
doHelp = true
i = i + 1
elseif arg[i] == '-md' then
doMd = true
i = i + 1
elseif arg[i] == '-config' then
readConfig = arg[i + 1]
i = i + 2
elseif arg[i] == '-save_config' then
saveConfig = arg[i + 1]
i = i + 2
else
local sopt = onmt.utils.String.stripHyphens(arg[i])
params._is_default[sopt] = nil
if arg[i]:sub(1,1) == '-' then
if cmdlineOptions[arg[i]] then
self:error('duplicate cmdline option: '..arg[i])
end
cmdlineOptions[arg[i]] = true
i = i + self:__readOption__(params, arg, i)
else
nArgument = nArgument + 1
i = i + self:__readArgument__(params, arg, i, nArgument)
end
end
end
if doHelp then
self:help(arg, doMd)
os.exit(0)
end
if nArgument ~= #self.arguments then
self:error('not enough arguments ')
end
if readConfig then
params = self:loadConfig(readConfig, params)
end
if saveConfig then
self:dumpConfig(params, saveConfig)
end
for k, v in pairs(params) do
if k:sub(1, 1) ~= '_' then
local K = k
if not self.options[k] and self.options['-' .. k] then
K = '-' .. k
end
local meta = self.options[K].meta
if meta then
-- check option validity
local isValid = true
local reason = nil
if not params._is_default[k] and meta.deprecatedBy then
local newOption = meta.deprecatedBy[1]
local newValue = meta.deprecatedBy[2]
io.stderr:write('DEPRECATION WARNING: option \'-' .. k .. '\' is replaced by \'-' .. newOption .. ' ' .. newValue .. '\'.\n')
params[newOption] = newValue
end
if meta.depends then
isValid, reason = meta.depends(params)
if not isValid then
local msg = 'invalid dependency for option -'..k
if reason then
msg = msg .. ': ' .. reason
end
self:error(msg)
end
end
if meta.valid then
isValid, reason = meta.valid(v)
end
if not isValid then
local msg = 'invalid argument for option -' .. k
if reason then
msg = msg .. ': ' .. reason
end
self:error(msg)
end
if meta.enum and type(self.options[K].default) ~= 'table' and not onmt.utils.Table.hasValue(meta.enum, v) then
self:error('option -' .. k.. ' is not in accepted values: ' .. concatValues(meta.enum))
end
if meta.enum and type(self.options[K].default) == 'table' then
for _, v1 in ipairs(v) do
if not onmt.utils.Table.hasValue(meta.enum, v1) then
self:error('option -' .. k.. ' is not in accepted values: ' .. concatValues(meta.enum))
end
end
end
if meta.structural then
params._structural[k] = meta.structural
end
if meta.init_only then
params._init_only[k] = meta.init_only
end
if meta.train_state then
params._train_state[k] = meta.train_state
end
end
end
end
return params
end
function ExtendedCmdLine:setCmdLineOptions(moduleOptions, group)
if group and group ~= self.prevGroup then
self:text('')
self:text(group .. ' options')
self:text('')
self.prevGroup = group
end
for i = 1, #moduleOptions do
if moduleOptions[i][1]:sub(1,1) == '-' then
self:option(table.unpack(moduleOptions[i]))
else
self:argument(table.unpack(moduleOptions[i]))
end
end
end
function ExtendedCmdLine.getModuleOpts(args, moduleOptions)
local moduleArgs = {}
for i = 1, #moduleOptions do
local optname = moduleOptions[i][1]
if optname:sub(1, 1) == '-' then
optname = optname:sub(2)
end
moduleArgs[optname] = args[optname]
end
return moduleArgs
end
function ExtendedCmdLine.getArgument(args, optName)
for i = 1, #args do
if args[i] == optName and i < #args then
return args[i + 1]
end
end
return nil
end
---------------------------------------------------------------------------------
-- Validators
---------------------------------------------------------------------------------
local function buildRangeError(prefix, minValue, maxValue)
local err = 'the ' .. prefix .. ' must be'
if minValue then
err = err .. ' greater than ' .. minValue
end
if maxValue then
if minValue then
err = err .. ' and'
end
err = err .. ' lower than ' .. maxValue
end
return err
end
-- Check if is integer between minValue and maxValue.
function ExtendedCmdLine.isInt(minValue, maxValue)
return function(v)
return (math.floor(v) == v and
(not minValue or v >= minValue) and
(not maxValue or v <= maxValue)),
buildRangeError('integer', minValue, maxValue)
end
end
-- Check if is positive integer.
function ExtendedCmdLine.isUInt(maxValue)
return ExtendedCmdLine.isInt(0, maxValue)
end
-- Check if value between minValue and maxValue.
function ExtendedCmdLine.isFloat(minValue, maxValue)
return function(v)
return (type(v) == 'number' and
(not minValue or v >= minValue) and
(not maxValue or v <= maxValue)),
buildRangeError('number', minValue, maxValue)
end
end
-- Check if non empty.
function ExtendedCmdLine.nonEmpty(v)
return v and v ~= '', 'the argument must not be empty'
end
-- Check if the corresponding file exists.
function ExtendedCmdLine.fileExists(v)
return path.exists(v), 'the file must exist'
end
-- Check non set or if the corresponding file exists.
function ExtendedCmdLine.fileNullOrExists(v)
return v == '' or ExtendedCmdLine.fileExists(v), 'if set, the file must exist'
end
-- Check it is a directory and some file exists
function ExtendedCmdLine.dirStructure(files)
return function(v)
for _,f in ipairs(files) do
if not path.exists(v.."/"..f) then
return false, 'the directory must exist'
end
end
return true
end
end
return ExtendedCmdLine
| mit |
ld-test/loop | lua/loop/serial/FileStream.lua | 8 | 1828 | --------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP Class Library --
-- Release: 2.3 beta --
-- Title : Stream that Serializes and Restores Values from Files --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
local assert = assert
local table = require "table"
local oo = require "loop.simple"
local Serializer = require "loop.serial.Serializer"
module"loop.serial.FileStream"
oo.class(_M, Serializer)
buffersize = 1024
function write(self, ...)
self.file:write(...)
end
function put(self, ...)
self:serialize(...)
self.file:write("\0")
end
function get(self)
local lines = {}
local line
repeat
line = self.remains or self.file:read(self.buffersize)
self.remains = nil
if line and line:find("%z") then
line, self.remains = line:match("^([^%z]*)%z(.*)$")
end
lines[#lines+1] = line
until not line or self.remains
return assert(self:load("return "..table.concat(lines)))()
end
| mit |
google-code/bitfighter | exe/scripts/robot_helper_functions.lua | 1 | 4670 | -------------------------------------------------------------------------------
--
-- Bitfighter - A multiplayer vector graphics space game
-- Based on Zap demo released for Torque Network Library by GarageGames.com
--
-- Copyright (C) 2008-2009 Chris Eykamp
-- Other code copyright as noted
--
-- 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 (and fun!),
-- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- These functions will be included with every robot automatically.
-- Do not tinker with these unless you are sure you know what you are doing!!
-- And even then, be careful!
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--
-- Create a reference to our bot
--
bot = LuaRobot(Robot)
--
-- Main function run when robot starts, before getName(). By default does nothing. Override in bot scripts.
--
function _main()
if _declared("main") and type(main) == "function" then
main()
end
end
--
-- Default robot name, can and should be overridden by user robots, but we need to have something...
--
function getName()
return("FancyNancy")
end
--
-- Wrap getFiringSolution with some code that helps C++ sort out what type of item
-- we're handing it
--
function getFiringSolution(item)
if(item == nil) then
return nil
end
local itemtype = item:getClassID()
if(itemtype == nil) then
return nil
end
return bot:getFiringSolution(itemtype, item)
end
--
-- Convenience function: find closest item in a list of items
-- Will return nil if items has 0 elements
-- If teamIndx is specified, will only include items on team
--
function findClosest(items, teamIndx)
local closest = nil
local minDist = 999999999
local loc = bot:getLoc()
for indx, item in ipairs(items) do -- Iterate over our list
--logprint(tostring(teamIndx)..","..item:getTeamIndx())
if teamIndx == nil or item:getTeamIndx() == teamIndx then
-- Use distSquared because it is less computationally expensive
-- and works great for comparing distances
local d = loc:distSquared(item:getLoc()) -- Dist btwn robot and TestItem
if d < minDist then -- Is it the closest yet?
closest = item
minDist = d
end
end
end
return closest
end
--
-- Convenience function... let user use logprint directly, without referencing luaUtil
--
function logprint(msg)
luaUtil:logprint("Robot", tostring(msg))
end
--
-- And another
--
function subscribe(event)
bot:subscribe(event)
end
--
-- This will be called every tick... update timer, then call robot's onTick() method if it exists
--
function _onTick(self, deltaT)
Timer:_tick(deltaT) -- Really should only be called once for all bots
if _declared("onTick") and type(onTick) == "function" then
onTick(self, deltaT)
end
-- TODO: Here for compatibility with older bots. Remove this in a later release
if _declared("getMove") and type(getMove) == "function" then
getMove(self, deltaT)
end
end
--
-- Let the log know that this file was processed correctly
--
logprint("Loaded robot helper functions...")
| gpl-2.0 |
lichtl/darkstar | scripts/zones/Southern_San_dOria/npcs/Andecia.lua | 13 | 3192 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Andecia
-- Starts and Finishes Quest: Grave Concerns
-- @zone 230
-- @pos 167 0 45
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,GRAVE_CONCERNS) == QUEST_ACCEPTED) then
if (trade:hasItemQty(547, 1) and trade:getItemCount() == 1 and player:getVar("OfferingWaterOK") == 1) then
player:startEvent(0x0270);
end
end
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Tomb = player:getQuestStatus(SANDORIA,GRAVE_CONCERNS);
WellWater = player:hasItem(567); -- Well Water
Waterskin = player:hasItem(547); -- Tomb Waterskin
if (Tomb == QUEST_AVAILABLE) then
player:startEvent(0x021d);
elseif (Tomb == QUEST_ACCEPTED and WellWater == false and player:getVar("OfferingWaterOK") == 0) then
player:startEvent(0x026e);
elseif (Tomb == QUEST_ACCEPTED and Waterskin == true and player:getVar("OfferingWaterOK") == 0) then
player:startEvent(0x026f);
elseif (Tomb == QUEST_COMPLETED) then
player:startEvent(0x022e);
else
player:startEvent(0x021c);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x021d and option == 0) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,567); -- Well Water
else
player:addQuest(SANDORIA,GRAVE_CONCERNS);
player:setVar("graveConcernsVar",0);
player:addItem(567);
player:messageSpecial(ITEM_OBTAINED,567); -- Well Water
end
elseif (csid == 0x0270) then
player:tradeComplete();
player:setVar("OfferingWaterOK",0);
player:addTitle(ROYAL_GRAVE_KEEPER);
player:addGil(GIL_RATE*560);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*560)
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,GRAVE_CONCERNS);
end
end; | gpl-3.0 |
OctoEnigma/shiny-octo-system | gamemodes/darkrp/entities/weapons/unarrest_stick/shared.lua | 2 | 3057 | AddCSLuaFile()
if CLIENT then
SWEP.PrintName = "Unarrest Baton"
SWEP.Slot = 1
SWEP.SlotPos = 3
end
DEFINE_BASECLASS("stick_base")
SWEP.Instructions = "Left click to unarrest\nRight click to switch batons"
SWEP.IsDarkRPUnarrestStick = true
SWEP.Spawnable = true
SWEP.Category = "DarkRP (Utility)"
SWEP.StickColor = Color(0, 255, 0)
DarkRP.hookStub{
name = "canUnarrest",
description = "Whether someone can unarrest another player.",
parameters = {
{
name = "unarrester",
description = "The player trying to unarrest someone.",
type = "Player"
},
{
name = "unarrestee",
description = "The player being unarrested.",
type = "Player"
}
},
returns = {
{
name = "canUnarrest",
description = "A yes or no as to whether the player can unarrest the other player.",
type = "boolean"
},
{
name = "message",
description = "The message that is shown when they can't unarrest the player.",
type = "string"
}
},
realm = "Server"
}
-- Default for canUnarrest hook
local hookCanUnarrest = {canUnarrest = fp{fn.Id, true}}
function SWEP:Deploy()
self.Switched = true
return BaseClass.Deploy(self)
end
function SWEP:PrimaryAttack()
BaseClass.PrimaryAttack(self)
if CLIENT then return end
self:GetOwner():LagCompensation(true)
local trace = util.QuickTrace(self:GetOwner():EyePos(), self:GetOwner():GetAimVector() * 90, {self:GetOwner()})
self:GetOwner():LagCompensation(false)
if IsValid(trace.Entity) and trace.Entity.onUnArrestStickUsed then
trace.Entity:onUnArrestStickUsed(self:GetOwner())
return
end
local ent = self:GetOwner():getEyeSightHitEntity(nil, nil, function(p) return p ~= self:GetOwner() and p:IsPlayer() and p:Alive() end)
if not ent then return end
if not IsValid(ent) or not ent:IsPlayer() or (self:GetOwner():EyePos():DistToSqr(ent:GetPos()) > self.stickRange * self.stickRange) or not ent:getDarkRPVar("Arrested") then
return
end
local canUnarrest, message = hook.Call("canUnarrest", hookCanUnarrest, self:GetOwner(), ent)
if not canUnarrest then
if message then DarkRP.notify(self:GetOwner(), 1, 5, message) end
return
end
ent:unArrest(self:GetOwner())
DarkRP.notify(ent, 0, 4, DarkRP.getPhrase("youre_unarrested_by", self:GetOwner():Nick()))
if self:GetOwner().SteamName then
DarkRP.log(self:GetOwner():Nick() .. " (" .. self:GetOwner():SteamID() .. ") unarrested " .. ent:Nick(), Color(0, 255, 255))
end
end
function SWEP:startDarkRPCommand(usrcmd)
if game.SinglePlayer() and CLIENT then return end
if usrcmd:KeyDown(IN_ATTACK2) then
if not self.Switched and self:GetOwner():HasWeapon("arrest_stick") then
usrcmd:SelectWeapon(self:GetOwner():GetWeapon("arrest_stick"))
end
else
self.Switched = false
end
end
| mit |
lichtl/darkstar | scripts/zones/Northern_San_dOria/npcs/Cauzeriste.lua | 14 | 1241 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Cauzeriste
-- Guild Merchant NPC: Woodworking Guild
-- @pos -175.946 3.999 280.301 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(513,6,21,0)) then
player:showText(npc,CAUZERISTE_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
MightyPirates/OC-LuaJ | luaj-test/src/test/resources/lua5.2.1-tests/errors.lua | 9 | 10405 | print("testing errors")
local debug = require"debug"
-- avoid problems with 'strict' module (which may generate other error messages)
local mt = getmetatable(_G) or {}
local oldmm = mt.__index
mt.__index = nil
function doit (s)
local f, msg = load(s)
if f == nil then return msg end
local cond, msg = pcall(f)
return (not cond) and msg
end
function checkmessage (prog, msg)
local m = doit(prog)
assert(string.find(m, msg, 1, true))
end
function checksyntax (prog, extra, token, line)
local msg = doit(prog)
if not string.find(token, "^<%a") and not string.find(token, "^char%(")
then token = "'"..token.."'" end
token = string.gsub(token, "(%p)", "%%%1")
local pt = string.format([[^%%[string ".*"%%]:%d: .- near %s$]],
line, token)
assert(string.find(msg, pt))
assert(string.find(msg, msg, 1, true))
end
-- test error message with no extra info
assert(doit("error('hi', 0)") == 'hi')
-- test error message with no info
assert(doit("error()") == nil)
-- test common errors/errors that crashed in the past
if not _no32 then
assert(doit("table.unpack({}, 1, n=2^30)"))
end
assert(doit("a=math.sin()"))
assert(not doit("tostring(1)") and doit("tostring()"))
assert(doit"tonumber()")
assert(doit"repeat until 1; a")
assert(doit"return;;")
assert(doit"assert(false)")
assert(doit"assert(nil)")
assert(doit("function a (... , ...) end"))
assert(doit("function a (, ...) end"))
assert(doit("local t={}; t = t[#t] + 1"))
checksyntax([[
local a = {4
]], "'}' expected (to close '{' at line 1)", "<eof>", 3)
-- tests for better error messages
checkmessage("a=1; bbbb=2; a=math.sin(3)+bbbb(3)", "global 'bbbb'")
checkmessage("a=1; local a,bbbb=2,3; a = math.sin(1) and bbbb(3)",
"local 'bbbb'")
checkmessage("a={}; do local a=1 end a:bbbb(3)", "method 'bbbb'")
checkmessage("local a={}; a.bbbb(3)", "field 'bbbb'")
assert(not string.find(doit"a={13}; local bbbb=1; a[bbbb](3)", "'bbbb'"))
checkmessage("a={13}; local bbbb=1; a[bbbb](3)", "number")
checkmessage("a=(1)..{}", "a table value")
aaa = nil
checkmessage("aaa.bbb:ddd(9)", "global 'aaa'")
checkmessage("local aaa={bbb=1}; aaa.bbb:ddd(9)", "field 'bbb'")
checkmessage("local aaa={bbb={}}; aaa.bbb:ddd(9)", "method 'ddd'")
checkmessage("local a,b,c; (function () a = b+1 end)()", "upvalue 'b'")
assert(not doit"local aaa={bbb={ddd=next}}; aaa.bbb:ddd(nil)")
checkmessage("local _ENV = {x={}}; a = a + 1", "global 'a'")
checkmessage("b=1; local aaa='a'; x=aaa+b", "local 'aaa'")
checkmessage("aaa={}; x=3/aaa", "global 'aaa'")
checkmessage("aaa='2'; b=nil;x=aaa*b", "global 'b'")
checkmessage("aaa={}; x=-aaa", "global 'aaa'")
assert(not string.find(doit"aaa={}; x=(aaa or aaa)+(aaa and aaa)", "'aaa'"))
assert(not string.find(doit"aaa={}; (aaa or aaa)()", "'aaa'"))
checkmessage("print(print < 10)", "function")
checkmessage("print(print < print)", "two function")
-- passing light userdata instead of full userdata
_G.D = debug
checkmessage([[
-- create light udata
local x = D.upvalueid(function () return debug end, 1)
D.setuservalue(x, {})
]], "light userdata")
_G.D = nil
-- global functions
checkmessage("(io.write or print){}", "io.write")
checkmessage("(collectgarbage or print){}", "collectgarbage")
-- tests for field accesses after RK limit
local t = {}
for i = 1, 1000 do
t[i] = "a = x" .. i
end
local s = table.concat(t, "; ")
t = nil
checkmessage(s.."; a = bbb + 1", "global 'bbb'")
checkmessage("local _ENV=_ENV;"..s.."; a = bbb + 1", "global 'bbb'")
checkmessage(s.."; local t = {}; a = t.bbb + 1", "field 'bbb'")
checkmessage(s.."; local t = {}; t:bbb()", "method 'bbb'")
checkmessage([[aaa=9
repeat until 3==3
local x=math.sin(math.cos(3))
if math.sin(1) == x then return math.sin(1) end -- tail call
local a,b = 1, {
{x='a'..'b'..'c', y='b', z=x},
{1,2,3,4,5} or 3+3<=3+3,
3+1>3+1,
{d = x and aaa[x or y]}}
]], "global 'aaa'")
checkmessage([[
local x,y = {},1
if math.sin(1) == 0 then return 3 end -- return
x.a()]], "field 'a'")
checkmessage([[
prefix = nil
insert = nil
while 1 do
local a
if nil then break end
insert(prefix, a)
end]], "global 'insert'")
checkmessage([[ -- tail call
return math.sin("a")
]], "'sin'")
checkmessage([[collectgarbage("nooption")]], "invalid option")
checkmessage([[x = print .. "a"]], "concatenate")
checkmessage("getmetatable(io.stdin).__gc()", "no value")
checkmessage([[
local Var
local function main()
NoSuchName (function() Var=0 end)
end
main()
]], "global 'NoSuchName'")
print'+'
a = {}; setmetatable(a, {__index = string})
checkmessage("a:sub()", "bad self")
checkmessage("string.sub('a', {})", "#2")
checkmessage("('a'):sub{}", "#1")
checkmessage("table.sort({1,2,3}, table.sort)", "'table.sort'")
-- next message may be 'setmetatable' or '_G.setmetatable'
checkmessage("string.gsub('s', 's', setmetatable)", "setmetatable'")
-- tests for errors in coroutines
function f (n)
local c = coroutine.create(f)
local a,b = coroutine.resume(c)
return b
end
assert(string.find(f(), "C stack overflow"))
checkmessage("coroutine.yield()", "outside a coroutine")
f1 = function () table.sort({1,2,3}, coroutine.yield) end
f = coroutine.wrap(function () return pcall(f1) end)
assert(string.find(select(2, f()), "yield across"))
-- testing size of 'source' info; size of buffer for that info is
-- LUA_IDSIZE, declared as 60 in luaconf. Get one position for '\0'.
idsize = 60 - 1
local function checksize (source)
-- syntax error
local _, msg = load("x", source)
msg = string.match(msg, "^([^:]*):") -- get source (1st part before ':')
assert(msg:len() <= idsize)
end
for i = 60 - 10, 60 + 10 do -- check border cases around 60
checksize("@" .. string.rep("x", i)) -- file names
checksize(string.rep("x", i - 10)) -- string sources
checksize("=" .. string.rep("x", i)) -- exact sources
end
-- testing line error
local function lineerror (s, l)
local err,msg = pcall(load(s))
local line = string.match(msg, ":(%d+):")
assert((line and line+0) == l)
end
lineerror("local a\n for i=1,'a' do \n print(i) \n end", 2)
lineerror("\n local a \n for k,v in 3 \n do \n print(k) \n end", 3)
lineerror("\n\n for k,v in \n 3 \n do \n print(k) \n end", 4)
lineerror("function a.x.y ()\na=a+1\nend", 1)
lineerror("a = \na\n+\n{}", 3)
lineerror("a = \n3\n+\n(\n4\n/\nprint)", 6)
lineerror("a = \nprint\n+\n(\n4\n/\n7)", 3)
lineerror("a\n=\n-\n\nprint\n;", 3)
lineerror([[
a
(
23)
]], 1)
lineerror([[
local a = {x = 13}
a
.
x
(
23
)
]], 2)
lineerror([[
local a = {x = 13}
a
.
x
(
23 + a
)
]], 6)
local p = [[
function g() f() end
function f(x) error('a', X) end
g()
]]
X=3;lineerror((p), 3)
X=0;lineerror((p), nil)
X=1;lineerror((p), 2)
X=2;lineerror((p), 1)
if not _soft then
-- several tests that exaust the Lua stack
C = 0
local l = debug.getinfo(1, "l").currentline; function y () C=C+1; y() end
local function checkstackmessage (m)
return (string.find(m, "^.-:%d+: stack overflow"))
end
-- repeated stack overflows (to check stack recovery)
assert(checkstackmessage(doit('y()')))
print('+')
assert(checkstackmessage(doit('y()')))
print('+')
assert(checkstackmessage(doit('y()')))
print('+')
-- error lines in stack overflow
C = 0
local l1
local function g(x)
l1 = debug.getinfo(x, "l").currentline; y()
end
local _, stackmsg = xpcall(g, debug.traceback, 1)
print('+')
local stack = {}
for line in string.gmatch(stackmsg, "[^\n]*") do
local curr = string.match(line, ":(%d+):")
if curr then table.insert(stack, tonumber(curr)) end
end
local i=1
while stack[i] ~= l1 do
assert(stack[i] == l)
i = i+1
end
assert(i > 15)
-- error in error handling
local res, msg = xpcall(error, error)
assert(not res and type(msg) == 'string')
print('+')
local function f (x)
if x==0 then error('a\n')
else
local aux = function () return f(x-1) end
local a,b = xpcall(aux, aux)
return a,b
end
end
f(3)
local function loop (x,y,z) return 1 + loop(x, y, z) end
local res, msg = xpcall(loop, function (m)
assert(string.find(m, "stack overflow"))
local res, msg = pcall(loop)
assert(string.find(msg, "error handling"))
assert(math.sin(0) == 0)
return 15
end)
assert(msg == 15)
res, msg = pcall(function ()
for i = 999900, 1000000, 1 do table.unpack({}, 1, i) end
end)
assert(string.find(msg, "too many results"))
end
-- non string messages
function f() error{msg='x'} end
res, msg = xpcall(f, function (r) return {msg=r.msg..'y'} end)
assert(msg.msg == 'xy')
-- xpcall with arguments
a, b, c = xpcall(string.find, error, "alo", "al")
assert(a and b == 1 and c == 2)
a, b, c = xpcall(string.find, function (x) return {} end, true, "al")
assert(not a and type(b) == "table" and c == nil)
print('+')
checksyntax("syntax error", "", "error", 1)
checksyntax("1.000", "", "1.000", 1)
checksyntax("[[a]]", "", "[[a]]", 1)
checksyntax("'aa'", "", "'aa'", 1)
-- test 255 as first char in a chunk
checksyntax("\255a = 1", "", "char(255)", 1)
doit('I = load("a=9+"); a=3')
assert(a==3 and I == nil)
print('+')
lim = 1000
if _soft then lim = 100 end
for i=1,lim do
doit('a = ')
doit('a = 4+nil')
end
-- testing syntax limits
local function testrep (init, rep)
local s = "local a; "..init .. string.rep(rep, 400)
local a,b = load(s)
assert(not a and string.find(b, "levels"))
end
testrep("a=", "{")
testrep("a=", "(")
testrep("", "a(")
testrep("", "do ")
testrep("", "while a do ")
testrep("", "if a then else ")
testrep("", "function foo () ")
testrep("a=", "a..")
testrep("a=", "a^")
local s = ("a,"):rep(200).."a=nil"
local a,b = load(s)
assert(not a and string.find(b, "levels"))
-- testing other limits
-- upvalues
local lim = 127
local s = "local function fooA ()\n local "
for j = 1,lim do
s = s.."a"..j..", "
end
s = s.."b,c\n"
s = s.."local function fooB ()\n local "
for j = 1,lim do
s = s.."b"..j..", "
end
s = s.."b\n"
s = s.."function fooC () return b+c"
local c = 1+2
for j = 1,lim do
s = s.."+a"..j.."+b"..j
c = c + 2
end
s = s.."\nend end end"
local a,b = load(s)
assert(c > 255 and string.find(b, "too many upvalues") and
string.find(b, "line 5"))
-- local variables
s = "\nfunction foo ()\n local "
for j = 1,300 do
s = s.."a"..j..", "
end
s = s.."b\n"
local a,b = load(s)
assert(string.find(b, "line 2"))
mt.__index = oldmm
print('OK')
| mit |
RunAwayDSP/darkstar | scripts/zones/Metalworks/npcs/Alois.lua | 9 | 1624 | -----------------------------------
-- Area: Metalworks
-- NPC: Alois
-- Involved in Missions: Wading Beasts
-- !pos 96 -20 14 237
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(BASTOK) == dsp.mission.id.bastok.WADING_BEASTS and trade:hasItemQty(4362,1) and trade:getItemCount() == 1) then -- Trade Lizard Egg
if (player:hasCompletedMission(BASTOK,dsp.mission.id.bastok.WADING_BEASTS) == false) then
player:startEvent(372);
else
player:startEvent(373);
end
end
end;
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) == dsp.mission.id.bastok.THE_SALT_OF_THE_EARTH and player:getCharVar("BASTOK91") == 0) then
player:startEvent(773);
elseif (player:getCharVar("BASTOK91") == 1) then
player:startEvent(774);
elseif (player:getCharVar("BASTOK91") == 3) then
player:startEvent(775);
elseif (player:getCharVar("BASTOK91") == 4) then
player:startEvent(776);
else
player:startEvent(370);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 372 or csid == 373) then
finishMissionTimeline(player,1,csid,option);
elseif (csid == 773) then
player:setCharVar("BASTOK91",1);
elseif (csid == 776) then
player:setCharVar("BASTOK91",0);
player:completeMission(BASTOK,dsp.mission.id.bastok.THE_SALT_OF_THE_EARTH);
player:addRankPoints(1500);
player:setCharVar("OptionalcsCornelia",1);
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle1.lua | 28 | 1049 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
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 |
lichtl/darkstar | scripts/zones/Bhaflau_Thickets/mobs/Sea_Puk.lua | 12 | 1367 | -----------------------------------
-- Area: Bhaflau Thickets
-- MOB: Sea Puk
-- Note: Place holder Nis Puk
-----------------------------------
require("scripts/zones/Bhaflau_Thickets/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
-- Get Sea Puk ID and check if it is a PH of NP
local mobID = mob:getID();
-- Check if Sea Puk is within the Nis_Puk_PH table
if (Nis_Puk_PH[mobID] ~= nil) then
-- printf("%u is a PH",mobID);
-- Get NP's previous ToD
local NP_ToD = GetServerVariable("[POP]Nis_Puk");
-- Check if NP window is open, and there is not an NP popped already(ACTION_NONE = 0)
if (NP_ToD <= os.time(t) and GetMobAction(Nis_Puk) == 0) then
-- printf("NP window open");
-- Give Sea Puk 5 percent chance to pop NP
if (math.random(1,20) >= 1) then
-- printf("NP will pop");
UpdateNMSpawnPoint(Nis_Puk);
GetMobByID(Nis_Puk):setRespawnTime(GetMobRespawnTime(mobID));
SetServerVariable("[PH]Nis_Puk", mobID);
DeterMob(mobID, true);
end
end
end
end; | gpl-3.0 |
scscgit/scsc_wildstar_addons | Wingman/Wingman.lua | 1 | 5464 | -----------------------------------------------------------------------------------------------
-- Client Lua Script for Wingman
-- Copyright (c) NCsoft. All rights reserved
-----------------------------------------------------------------------------------------------
require "Window"
require "GroupLib"
require "ChatSystemLib"
-----------------------------------------------------------------------------------------------
-- Wingman Module Definition
-----------------------------------------------------------------------------------------------
local Wingman = {}
-----------------------------------------------------------------------------------------------
-- Constants
-----------------------------------------------------------------------------------------------
-- e.g. local kiExampleVariableMax = 999
-----------------------------------------------------------------------------------------------
-- Initialization
-----------------------------------------------------------------------------------------------
function Wingman:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
-- initialize variables here
return o
end
function Wingman:Init()
local bHasConfigureFunction = false
local strConfigureButtonText = ""
local tDependencies = {
-- "UnitOrPackageName",
}
Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies)
end
-----------------------------------------------------------------------------------------------
-- Wingman OnLoad
-----------------------------------------------------------------------------------------------
function Wingman:OnLoad()
-- load our form file
self.xmlDoc = XmlDoc.CreateFromFile("Wingman.xml")
self.xmlDoc:RegisterCallback("OnDocLoaded", self)
end
-----------------------------------------------------------------------------------------------
-- Wingman OnDocLoaded
-----------------------------------------------------------------------------------------------
function Wingman:OnDocLoaded()
if self.xmlDoc ~= nil and self.xmlDoc:IsLoaded() then
self.wndMain = Apollo.LoadForm(self.xmlDoc, "WingmanForm", nil, self)
self.wndMain:Show(false)
self.wndMain = nil
self.xmlDoc = nil
-- if the xmlDoc is no longer needed, you should set it to nil
-- self.xmlDoc = nil
-- Register handlers for events, slash commands and timer, etc.
-- e.g. Apollo.RegisterEventHandler("KeyDown", "OnKeyDown", self)
Apollo.RegisterSlashCommand("wingman", "OnWingman", self)
-- Do additional Addon initialization here
end
end
-----------------------------------------------------------------------------------------------
-- Wingman Functions
-----------------------------------------------------------------------------------------------
-- Define general functions here
-- on SlashCommand "/wingman"
function Wingman:OnWingman()
self.fuckupsList = {}
self:GroupDeserter()
local chGroup = ""
-- 0 is solo, 1-4 is party
if GroupLib.GetMemberCount() == 0 then Print("You Do Not Have Deserter... You should open your eyes.") return end
local idType = ChatSystemLib.ChatChannel_Party
if GroupLib.GetMemberCount() > 0 then idType = ChatSystemLib.ChatChannel_Warparty end
for _,chId in pairs( ChatSystemLib.GetChannels() ) do
if chId:GetType() == ChatSystemLib.ChatChannel_Party then
chGroup = chId
end
end
chGroup:Send("[Wingman Alert] -- People Cockblocking :: [ "..#self.fuckupsList.." ]")
if #self.fuckupsList == 0 then return end
local strFuckUpsDeserter = ""
local pos = 1
for _,v in pairs( self.fuckupsList ) do
if pos == 1 then
strFuckUpsDeserter = v
pos = 2
else
strFuckUpsDeserter = strFuckUpsDeserter .. ", " .. v
end
end
chGroup:Send("Can't Triforce [ " .. strFuckUpsDeserter .. " ]")
chGroup:Send("---[ End of List ]---")
-- Check Deserter
-- Instance
-- ExistingQueue
end
function Wingman:GroupDeserter()
local nMemberCount = GroupLib.GetMemberCount()
if nMemberCount == 0 then
local player = GameLib.GetPlayerUnit()
local memberInfo = player:GetBuffs()
local tHarm = memberInfo.arHarmful
if #tHarm == 0 then return end -- zero harms
for _,v in pairs (tHarm) do
if v.splEffect:GetId() == 45444 then
local sUserName = player:GetName()
table.insert(self.fuckupsList, sUserName)
end
end
return
end
for i=1,nMemberCount do
local player = GroupLib.GetUnitForGroupMember(i)
local memberInfo = player:GetBuffs()
local tHarm = memberInfo.arHarmful
if #tHarm == 0 then return end -- zero harms
for _,v in pairs (tHarm) do
if v.splEffect:GetId() == 45444 then
local sUserName = player:GetName()
table.insert(self.fuckupsList, sUserName)
end
end
end
end
function Wingman:GroupInstance()
local playerZoneMap = memberInfo.GetCurrentZoneMap().id
local badKitteh = { 69 } -- Walatiki Temple ID = 69
local nMemberCount = GroupLib.GetMemberCount()
if nMemberCount == 0 then return end
--[[
id 69
strFolder PvPSmashandGrab
strName Walatiki Temple
ContinentId 40
]]
table.insert(sUserName, self.fuckupsList)
end
function Wingman:GroupQueues()
table.insert(sUserName, self.fuckupsList)
end
-----------------------------------------------------------------------------------------------
-- Wingman Instance
-----------------------------------------------------------------------------------------------
local WingmanInst = Wingman:new()
WingmanInst:Init()
| mit |
OctoEnigma/shiny-octo-system | gamemodes/darkrp/gamemode/modules/fpp/pp/server/settings.lua | 3 | 38987 | FPP = FPP or {}
util.AddNetworkString("FPP_Groups")
util.AddNetworkString("FPP_GroupMembers")
util.AddNetworkString("FPP_RestrictedToolList")
util.AddNetworkString("FPP_BlockedModels")
FPP.Blocked = FPP.Blocked or {}
FPP.Blocked.Physgun1 = FPP.Blocked.Physgun1 or {}
FPP.Blocked.Spawning1 = FPP.Blocked.Spawning1 or {}
FPP.Blocked.Gravgun1 = FPP.Blocked.Gravgun1 or {}
FPP.Blocked.Toolgun1 = FPP.Blocked.Toolgun1 or {}
FPP.Blocked.PlayerUse1 = FPP.Blocked.PlayerUse1 or {}
FPP.Blocked.EntityDamage1 = FPP.Blocked.EntityDamage1 or {}
FPP.BlockedModels = FPP.BlockedModels or {}
FPP.RestrictedTools = FPP.RestrictedTools or {}
FPP.RestrictedToolsPlayers = FPP.RestrictedToolsPlayers or {}
FPP.Groups = FPP.Groups or {}
FPP.GroupMembers = FPP.GroupMembers or {}
function FPP.Notify(ply, text, bool)
if ply:EntIndex() == 0 then
ServerLog(text)
return
end
umsg.Start("FPP_Notify", ply)
umsg.String(text)
umsg.Bool(bool)
umsg.End()
ply:PrintMessage(HUD_PRINTCONSOLE, text)
end
function FPP.NotifyAll(text, bool)
umsg.Start("FPP_Notify")
umsg.String(text)
umsg.Bool(bool)
umsg.End()
for _,ply in pairs(player.GetAll()) do
ply:PrintMessage(HUD_PRINTCONSOLE, text)
end
end
local function getSettingsChangedEntities(settingsType, setting)
local plys, entities = {}, {}
local blockedString = string.sub(settingsType, 5, 5) .. string.lower(string.sub(settingsType, 6))
blockedString = blockedString == "Playeruse1" and "PlayerUse1" or blockedString -- dirty hack for stupid naming system.
blockedString = blockedString == "Entitydamage1" and "EntityDamage1" or blockedString -- dirty hack for stupid naming system.
if setting == "adminall" then
for k,v in pairs(ents.GetAll()) do
local owner = v:CPPIGetOwner()
if IsValid(owner) then table.insert(entities, v) end
end
for k,v in pairs(player.GetAll()) do
v.FPP_Privileges = v.FPP_Privileges or {}
if v.FPP_Privileges.FPP_TouchOtherPlayersProps then table.insert(plys, v) end
end
return plys, entities
elseif setting == "worldprops" or setting == "adminworldprops" then
for k,v in pairs(ents.GetAll()) do
if not IsValid(v) then continue end
if FPP.Blocked[blockedString][string.lower(v:GetClass())] then continue end
local owner = v:CPPIGetOwner()
if not IsValid(owner) then table.insert(entities, v) end
end
for k,v in pairs(player.GetAll()) do
v.FPP_Privileges = v.FPP_Privileges or {}
if v.FPP_Privileges.FPP_TouchOtherPlayersProps then table.insert(plys, v) end
end
return setting == "adminworldprops" and plys or player.GetAll(), entities
elseif setting == "canblocked" or setting == "admincanblocked" then
for k,v in pairs(ents.GetAll()) do
if not IsValid(v) then continue end
if not FPP.Blocked[blockedString][string.lower(v:GetClass())] then continue end
table.insert(entities, v)
end
for k,v in pairs(player.GetAll()) do
v.FPP_Privileges = v.FPP_Privileges or {}
if v.FPP_Privileges.FPP_TouchOtherPlayersProps then table.insert(plys, v) end
end
return setting == "admincanblocked" and plys or player.GetAll(), entities
elseif setting == "iswhitelist" then
return player.GetAll(), ents.GetAll()
end
end
util.AddNetworkString("FPP_Settings")
local function SendSettings(ply)
net.Start("FPP_Settings")
FPP.ForAllSettings(function(k, s, v)
net.WriteDouble(v)
end)
net.Send(ply)
end
util.AddNetworkString("FPP_Settings_Update")
local function updateFPPSetting(kind, setting, value)
local skipKind, skipSetting = 0, 0
FPP.Settings[kind][setting] = value
local finalSkipKind
FPP.ForAllSettings(function(k, s)
skipKind = skipKind + 1
if k ~= kind then return true end
finalSkipKind = skipKind - skipSetting
skipSetting = skipSetting + 1
if s ~= setting then return end
return true
end)
net.Start("FPP_Settings_Update")
net.WriteUInt(finalSkipKind, 8)
net.WriteUInt(skipSetting, 8)
net.WriteDouble(value)
net.Broadcast()
end
local function runIfAccess(priv, f)
return function(ply, cmd, args)
CAMI.PlayerHasAccess(ply, priv, function(allowed, _)
if allowed then return f(ply, cmd, args) end
FPP.Notify(ply, string.format("You need the '%s' privilege in order to be able to use this command", priv), false)
end)
end
end
local function FPP_SetSetting(ply, cmd, args)
if not args[1] or not args[3] or not FPP.Settings[args[1]] then FPP.Notify(ply, "Argument(s) invalid", false) return end
if not FPP.Settings[args[1]][args[2]] then FPP.Notify(ply, "Argument invalid",false) return end
updateFPPSetting(args[1], args[2], tonumber(args[3]))
MySQLite.queryValue("SELECT var FROM " .. args[1] .. " WHERE var = " .. sql.SQLStr(args[2]) .. ";", function(data)
if not data then
MySQLite.query("INSERT INTO " .. args[1] .. " VALUES(" .. sql.SQLStr(args[2]) .. ", " .. args[3] .. ");")
elseif tonumber(data) ~= args[3] then
MySQLite.query("UPDATE " .. args[1] .. " SET setting = " .. args[3] .. " WHERE var = " .. sql.SQLStr(args[2]) .. ";")
end
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " set " .. string.lower(string.gsub(args[1], "FPP_", "")) .. " " .. args[2] .. " to " .. tostring(args[3]), tobool(tonumber(args[3])))
end)
FPP.calculatePlayerPrivilege("FPP_TouchOtherPlayersProps", function()
local plys, entities = getSettingsChangedEntities(args[1], args[2])
if not plys or not entities or #plys == 0 or #entities == 0 then return end
FPP.recalculateCanTouch(plys, entities)
end)
end
concommand.Add("FPP_setting", runIfAccess("FPP_Settings", FPP_SetSetting))
local function AddBlocked(ply, cmd, args)
if not args[1] or not args[2] or not FPP.Blocked[args[1]] then FPP.Notify(ply, "Argument(s) invalid", false) return end
args[2] = string.lower(args[2])
if FPP.Blocked[args[1]][args[2]] then return end
FPP.Blocked[args[1]][args[2]] = true
MySQLite.query(string.format("INSERT INTO FPP_BLOCKED1 (var, setting) VALUES(%s, %s);", sql.SQLStr(args[1]), sql.SQLStr(args[2])))
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " added " .. args[2] .. " to the " .. args[1] .. " black/whitelist", true)
FPP.recalculateCanTouch(player.GetAll(), ents.FindByClass(args[2]))
end
concommand.Add("FPP_AddBlocked", runIfAccess("FPP_Settings", AddBlocked))
-- Models can differ between server and client. Famous example being:
-- models/props_phx/cannonball_solid.mdl <-- serverside
-- models/props_phx/cannonball.mdl <-- clientside
-- Similar problems occur with effects
local function getIntendedBlockedModels(model, ent)
model = string.Replace(string.lower(model), "\\", "/")
if not IsValid(ent) then return {model} end
if ent:GetClass() == "prop_effect" then return {ent.AttachedEntity:GetModel()} end
if model ~= ent:GetModel() then return {model, ent:GetModel()} end
return {model}
end
local function AddBlockedModel(ply, cmd, args)
if not args[1] then FPP.Notify(ply, "Argument(s) invalid", false) return end
local models = getIntendedBlockedModels(args[1], tonumber(args[2]) and Entity(args[2]) or nil)
for k, model in pairs(models) do
if FPP.BlockedModels[model] then FPP.Notify(ply, string.format([["%s" is already in the black/whitelist]], model), false) continue end
FPP.BlockedModels[model] = true
MySQLite.query("REPLACE INTO FPP_BLOCKEDMODELS1 VALUES(" .. sql.SQLStr(model) .. ");")
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " added " .. model .. " to the blocked models black/whitelist", true)
end
end
concommand.Add("FPP_AddBlockedModel", runIfAccess("FPP_Settings", AddBlockedModel))
local function RemoveBlocked(ply, cmd, args)
if not args[1] or not args[2] or not FPP.Blocked[args[1]] then FPP.Notify(ply, "Argument(s) invalid", false) return end
FPP.Blocked[args[1]][args[2]] = nil
MySQLite.query("DELETE FROM FPP_BLOCKED1 WHERE var = " .. sql.SQLStr(args[1]) .. " AND setting = " .. sql.SQLStr(args[2]) .. ";")
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " removed " .. args[2] .. " from the " .. args[1] .. " black/whitelist", false)
FPP.recalculateCanTouch(player.GetAll(), ents.FindByClass(args[2]))
end
concommand.Add("FPP_RemoveBlocked", runIfAccess("FPP_Settings", RemoveBlocked))
local function RemoveBlockedModel(ply, cmd, args)
if not args[1] then FPP.Notify(ply, "Argument(s) invalid", false) return end
local models = getIntendedBlockedModels(args[1], tonumber(args[2]) and Entity(args[2]) or nil)
for k, model in pairs(models) do
FPP.BlockedModels[model] = nil
MySQLite.query("DELETE FROM FPP_BLOCKEDMODELS1 WHERE model = " .. sql.SQLStr(model) .. ";")
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " removed " .. model .. " from the blocked models black/whitelist", false)
end
end
concommand.Add("FPP_RemoveBlockedModel", runIfAccess("FPP_Settings", RemoveBlockedModel))
local allowedShares = {
SharePhysgun1 = true,
ShareGravgun1 = true,
SharePlayerUse1 = true,
ShareEntityDamage1 = true,
ShareToolgun1 = true
}
local function ShareProp(ply, cmd, args)
if not args[1] or not IsValid(Entity(args[1])) or not args[2] then FPP.Notify(ply, "Argument(s) invalid", false) return end
local ent = Entity(args[1])
if ent:CPPIGetOwner() ~= ply then
FPP.Notify(ply, "You do not have the right to share this entity.", false)
return
end
if not tonumber(args[2]) or not IsValid(Player(tonumber(args[2]))) then -- This is for sharing prop per utility
if not allowedShares[args[2]] then
FPP.Notify(ply, "Argument(s) invalid", false)
return
end
ent[args[2]] = tobool(args[3])
else -- This is for sharing prop per player
local target = Player(tonumber(args[2]))
local toggle = tobool(args[3])
-- Make the table if it isn't there
if not ent.AllowedPlayers and toggle then
ent.AllowedPlayers = {target}
else
if toggle and not table.HasValue(ent.AllowedPlayers, target) then
table.insert(ent.AllowedPlayers, target)
FPP.Notify(target, ply:Nick() .. " shared an entity with you!", true)
elseif not toggle then
for k, v in pairs(ent.AllowedPlayers) do
if v == target then
table.remove(ent.AllowedPlayers, k)
FPP.Notify(target, ply:Nick() .. " unshared an entity with you!", false)
end
end
end
end
end
FPP.recalculateCanTouch(player.GetAll(), {ent})
end
concommand.Add("FPP_ShareProp", ShareProp)
local function RetrieveSettings()
MySQLite.begin()
for k in pairs(FPP.Settings) do
MySQLite.queueQuery("SELECT setting, var FROM " .. k .. ";", function(data)
if not data then return end
for _, value in pairs(data) do
if FPP.Settings[k][value.var] == nil then
-- Likely an old setting that has since been removed from FPP.
-- This setting however still exists in the DB. Time to remove it.
MySQLite.query("DELETE FROM " .. k .. " WHERE var = " .. sql.SQLStr(value.var) .. ";")
continue
end
FPP.Settings[k][value.var] = tonumber(value.setting)
end
end)
end
MySQLite.commit(function()
SendSettings(player.GetAll())
end)
end
local defaultBlocked = {
Physgun1 = {
["func_breakable_surf"] = true,
["func_brush"] = true,
["func_button"] = true,
["func_door"] = true,
["prop_door_rotating"] = true,
["func_door_rotating"] = true
},
Spawning1 = {
["func_breakable_surf"] = true,
["player"] = true,
["func_door"] = true,
["prop_door_rotating"] = true,
["func_door_rotating"] = true,
["ent_explosivegrenade"] = true,
["ent_mad_grenade"] = true,
["ent_flashgrenade"] = true,
["gmod_wire_field_device"] = true
},
Gravgun1 = {["func_breakable_surf"] = true, ["vehicle_"] = true},
Toolgun1 = {
["func_breakable_surf"] = true,
["func_button"] = true,
["player"] = true,
["func_door"] = true,
["prop_door_rotating"] = true,
["func_door_rotating"] = true
},
PlayerUse1 = {},
EntityDamage1 = {}
}
-- Fills the FPP blocked table with default things that are to be blocked
function FPP.FillDefaultBlocked()
local count = 0
MySQLite.begin()
-- All values that are to be inserted
local allValues = {}
for k,v in pairs(defaultBlocked) do
for a,b in pairs(v) do
FPP.Blocked[k][a] = true
count = count + 1
if not MySQLite.isMySQL() then
MySQLite.query("REPLACE INTO FPP_BLOCKED1 VALUES(" .. count .. ", " .. sql.SQLStr(k) .. ", " .. sql.SQLStr(a) .. ");")
else
table.insert(allValues, string.format("(%i, %s, %s)", count, sql.SQLStr(k), sql.SQLStr(a)))
end
end
end
-- Run it all in a single query if using MySQL.
if MySQLite.isMySQL() then
MySQLite.query(string.format("INSERT IGNORE INTO FPP_BLOCKED1 VALUES %s", table.concat(allValues, ",")))
end
MySQLite.commit()
end
local function RetrieveBlocked()
MySQLite.query("SELECT * FROM FPP_BLOCKED1;", function(data)
if type(data) == "table" then
for k,v in pairs(data) do
if not FPP.Blocked[v.var] then
ErrorNoHalt((v.var or "(nil var)") .. " blocked type does not exist! (Setting: " .. (v.setting or "") .. ")")
continue
end
FPP.Blocked[v.var][string.lower(v.setting)] = true
end
else
-- Give third party addons 5 seconds to add default blocked items
timer.Simple(5, FPP.FillDefaultBlocked)
end
end)
end
/*---------------------------------------------------------------------------
Default blocked entities
Only save in the database on first start
---------------------------------------------------------------------------*/
function FPP.AddDefaultBlocked(types, classname)
classname = string.lower(classname)
if type(types) == "string" then
defaultBlocked[types] = defaultBlocked[types] or {}
defaultBlocked[types][classname] = true
return
end
for k,v in pairs(types) do
defaultBlocked[v] = defaultBlocked[v] or {}
defaultBlocked[v][classname] = true
end
end
local function RetrieveBlockedModels()
FPP.BlockedModels = FPP.BlockedModels or {}
-- Sometimes when the database retrieval is corrupt,
-- only parts of the table will be retrieved
-- This is a workaround
if not MySQLite.isMySQL() then
local count = MySQLite.queryValue("SELECT COUNT(*) FROM FPP_BLOCKEDMODELS1;") or 0
if tonumber(count) == 0 then
FPP.AddDefaultBlockedModels() -- Load the default blocked models on first run
end
-- Select with offsets of a thousand.
-- That's about the maximum it can receive properly at once
for i = 0, count, 1000 do
MySQLite.query("SELECT * FROM FPP_BLOCKEDMODELS1 LIMIT 1000 OFFSET " .. i .. ";", function(data)
for k, v in pairs(data or {}) do
FPP.BlockedModels[v.model] = true
end
end)
end
return
end
-- Retrieve the data normally from MySQL
MySQLite.query("SELECT * FROM FPP_BLOCKEDMODELS1;", function(data)
if not data or #data == 0 then
FPP.AddDefaultBlockedModels() -- Load the default blocked models on first run
end
for k,v in pairs(data or {}) do
if not v.model then continue end
FPP.BlockedModels[v.model] = true
end
end)
end
local function RetrieveRestrictedTools()
MySQLite.query("SELECT * FROM FPP_TOOLADMINONLY;", function(data)
if type(data) == "table" then
for k,v in pairs(data) do
FPP.RestrictedTools[v.toolname] = {}
FPP.RestrictedTools[v.toolname]["admin"] = tonumber(v.adminonly)
end
end
end)
MySQLite.query("SELECT * FROM FPP_TOOLRESTRICTPERSON1;", function(perplayerData)
if type(perplayerData) ~= "table" then return end
for k,v in pairs(perplayerData) do
FPP.RestrictedToolsPlayers[v.toolname] = FPP.RestrictedToolsPlayers[v.toolname] or {}
FPP.RestrictedToolsPlayers[v.toolname][v.steamid] = tobool(v.allow)
end
end)
MySQLite.query("SELECT * FROM FPP_TOOLTEAMRESTRICT;", function(data)
if not data then return end
for k,v in pairs(data) do
FPP.RestrictedTools[v.toolname] = FPP.RestrictedTools[v.toolname] or {}
FPP.RestrictedTools[v.toolname]["team"] = FPP.RestrictedTools[v.toolname]["team"] or {}
table.insert(FPP.RestrictedTools[v.toolname]["team"], tonumber(v.team))
end
end)
end
local function RetrieveGroups()
MySQLite.query("SELECT * FROM FPP_GROUPS3;", function(data)
if type(data) ~= "table" then
MySQLite.query("REPLACE INTO FPP_GROUPS3 VALUES('default', 1);")
FPP.Groups["default"] = {}
FPP.Groups["default"].tools = {}
FPP.Groups["default"].allowdefault = true
return
end -- if there are no groups then there isn't much to load
for k,v in pairs(data) do
FPP.Groups[v.groupname] = {}
FPP.Groups[v.groupname].tools = {}
FPP.Groups[v.groupname].allowdefault = tobool(v.allowdefault)
end
MySQLite.query("SELECT * FROM FPP_GROUPTOOL;", function(grouptooldata)
if not grouptooldata then return end
for k,v in pairs(grouptooldata) do
FPP.Groups[v.groupname] = FPP.Groups[v.groupname] or {}
FPP.Groups[v.groupname].tools = FPP.Groups[v.groupname].tools or {}
table.insert(FPP.Groups[v.groupname].tools, v.tool)
end
end)
MySQLite.query("SELECT * FROM FPP_GROUPMEMBERS1;", function(members)
if type(members) ~= "table" then return end
for _,v in pairs(members) do
FPP.GroupMembers[v.steamid] = v.groupname
end
end)
end)
end
hook.Add("PlayerInitialSpawn", "FPP_SendSettings", SendSettings)
local function AddGroup(ply, cmd, args)
if not args[1] then FPP.Notify(ply, "Invalid argument(s)", false) return end-- Args: 1 = name, optional: 2 = allowdefault
local name = string.lower(args[1])
local allowdefault = tonumber(args[2]) or 1
if FPP.Groups[name] then
FPP.Notify(ply, "Group already exists", false)
return
end
FPP.Groups[name] = {}
FPP.Groups[name].allowdefault = tobool(allowdefault)
FPP.Groups[name].tools = {}
MySQLite.query("REPLACE INTO FPP_GROUPS3 VALUES(" .. sql.SQLStr(name) .. ", " .. sql.SQLStr(allowdefault) .. ");")
FPP.Notify(ply, "Group added successfully", true)
end
concommand.Add("FPP_AddGroup", runIfAccess("FPP_Settings", AddGroup))
hook.Add("InitPostEntity", "FPP_Load_FAdmin", function()
if FAdmin then
for k,v in pairs(FAdmin.Access.Groups) do
if not FPP.Groups[k] then AddGroup(Entity(0), "", {k, 1}) end
end
end
end)
local function RemoveGroup(ply, cmd, args)
if not args[1] then FPP.Notify(ply, "Invalid argument(s)", false) return end-- Args: 1 = name
local name = string.lower(args[1])
if not FPP.Groups[name] then
FPP.Notify(ply, "Group does not exists", false)
return
end
if name == "default" then
FPP.Notify(ply, "Can not remove default group", false)
return
end
FPP.Groups[name] = nil
MySQLite.query("DELETE FROM FPP_GROUPS3 WHERE groupname = " .. sql.SQLStr(name) .. ";")
MySQLite.query("DELETE FROM FPP_GROUPTOOL WHERE groupname = " .. sql.SQLStr(name) .. ";")
for k,v in pairs(FPP.GroupMembers) do
if v == name then
FPP.GroupMembers[k] = nil -- Set group to standard if group is removed
end
end
FPP.Notify(ply, "Group removed successfully", true)
end
concommand.Add("FPP_RemoveGroup", runIfAccess("FPP_Settings", RemoveGroup))
local function GroupChangeAllowDefault(ply, cmd, args)
if not args[2] then FPP.Notify(ply, "Invalid argument(s)", false) return end-- Args: 1 = groupname, 2 = new value 1/0
local name = string.lower(args[1])
local newval = tonumber(args[2])
if not FPP.Groups[name] then
FPP.Notify(ply, "Group does not exists", false)
return
end
FPP.Groups[name].allowdefault = tobool(newval)
MySQLite.query("UPDATE FPP_GROUPS3 SET allowdefault = " .. sql.SQLStr(newval) .. " WHERE groupname = " .. sql.SQLStr(name) .. ";")
FPP.Notify(ply, "Group status changed successfully", true)
end
concommand.Add("FPP_ChangeGroupStatus", runIfAccess("FPP_Settings", GroupChangeAllowDefault))
local function GroupAddTool(ply, cmd, args)
if not args[2] then FPP.Notify(ply, "Invalid argument(s)", false) return end-- Args: 1 = groupname, 2 = tool
local name = args[1]
local tool = string.lower(args[2])
if not FPP.Groups[name] then
FPP.Notify(ply, "Group does not exists", false)
return
end
FPP.Groups[name].tools = FPP.Groups[name].tools or {}
if table.HasValue(FPP.Groups[name].tools, tool) then
FPP.Notify(ply, "Tool is already in group!", false)
return
end
table.insert(FPP.Groups[name].tools, tool)
MySQLite.query("REPLACE INTO FPP_GROUPTOOL VALUES(" .. sql.SQLStr(name) .. ", " .. sql.SQLStr(tool) .. ");")
FPP.Notify(ply, "Tool added successfully", true)
end
concommand.Add("FPP_AddGroupTool", runIfAccess("FPP_Settings", GroupAddTool))
local function GroupRemoveTool(ply, cmd, args)
if not args[2] then FPP.Notify(ply, "Invalid argument(s)", false) return end-- Args: 1 = groupname, 2 = tool
local name = args[1]
local tool = string.lower(args[2])
if not FPP.Groups[name] then
FPP.Notify(ply, "Group does not exists", false)
return
end
if not table.HasValue(FPP.Groups[name].tools, tool) then
FPP.Notify(ply, "Tool does not exist in group!", false)
return
end
for k,v in pairs(FPP.Groups[name].tools) do
if v == tool then
table.remove(FPP.Groups[name].tools, k)
end
end
MySQLite.query("DELETE FROM FPP_GROUPTOOL WHERE groupname = " .. sql.SQLStr(name) .. " AND tool = " .. sql.SQLStr(tool) .. ";")
FPP.Notify(ply, "Tool removed successfully", true)
end
concommand.Add("FPP_RemoveGroupTool", runIfAccess("FPP_Settings", GroupRemoveTool))
local function PlayerSetGroup(ply, cmd, args)
if not args[2] then FPP.Notify(ply, "Invalid argument(s)", false) return end-- Args: 1 = player, 2 = group
local name = args[1]
local group = string.lower(args[2])
if IsValid(Player(tonumber(name) or 0)) then name = Player(tonumber(name)):SteamID()
elseif not string.find(name, "STEAM") and name ~= "UNKNOWN" then FPP.Notify(ply, "Invalid argument(s)", false) return end
if not FPP.Groups[group] and (not FAdmin or not FAdmin.Access.Groups[group]) then
FPP.Notify(ply, "Group does not exists", false)
return
end
if group ~= "default" then
MySQLite.query("REPLACE INTO FPP_GROUPMEMBERS1 VALUES(" .. sql.SQLStr(name) .. ", " .. sql.SQLStr(group) .. ");")
FPP.GroupMembers[name] = group
else
FPP.GroupMembers[name] = nil
MySQLite.query("DELETE FROM FPP_GROUPMEMBERS1 WHERE steamid = " .. sql.SQLStr(name) .. ";")
end
FPP.Notify(ply, "Player group successfully set", true)
end
concommand.Add("FPP_SetPlayerGroup", runIfAccess("FPP_Settings", PlayerSetGroup))
local function SendGroupData(ply, cmd, args)
net.Start("FPP_Groups")
net.WriteTable(FPP.Groups)
net.Send(ply)
end
concommand.Add("FPP_SendGroups", runIfAccess("FPP_Settings", SendGroupData))
local function SendGroupMemberData(ply, cmd, args)
net.Start("FPP_GroupMembers")
net.WriteTable(FPP.GroupMembers)
net.Send(ply)
end
concommand.Add("FPP_SendGroupMembers", runIfAccess("FPP_Settings", SendGroupMemberData))
local function SendBlocked(ply, cmd, args)
if not args[1] or not FPP.Blocked[args[1]] then return end
ply.FPPUmsg1 = ply.FPPUmsg1 or {}
ply.FPPUmsg1[args[1]] = ply.FPPUmsg1[args[1]] or 0
if ply.FPPUmsg1[args[1]] > CurTime() - 5 then return end
ply.FPPUmsg1[args[1]] = CurTime()
for k,v in pairs(FPP.Blocked[args[1]]) do
umsg.Start("FPP_blockedlist", ply)
umsg.String(args[1])
umsg.String(k)
umsg.End()
end
end
concommand.Add("FPP_sendblocked", SendBlocked)
local function SendBlockedModels(ply, cmd, args)
ply.FPPUmsg2 = ply.FPPUmsg2 or 0
if ply.FPPUmsg2 > CurTime() - 10 then return end
ply.FPPUmsg2 = CurTime()
local models = {}
for k,v in pairs(FPP.BlockedModels) do table.insert(models, k) end
local data = util.Compress(table.concat(models, "\0"))
net.Start("FPP_BlockedModels")
net.WriteData(data, #data)
net.Send(ply)
end
concommand.Add("FPP_sendblockedmodels", SendBlockedModels)
local function SendRestrictedTools(ply, cmd, args)
ply.FPPUmsg3 = ply.FPPUmsg3 or 0
if ply.FPPUmsg3 > CurTime() - 5 then return end
ply.FPPUmsg3 = CurTime()
if not args[1] then return end
net.Start("FPP_RestrictedToolList")
net.WriteString(args[1]) -- tool name
net.WriteUInt(FPP.RestrictedTools[args[1]] and FPP.RestrictedTools[args[1]].admin or 0, 2) -- user, admin or superadmin
local teams = FPP.RestrictedTools[args[1]] and FPP.RestrictedTools[args[1]].team or {}
net.WriteUInt(#teams, 10)
for _, t in pairs(teams) do
net.WriteUInt(t, 10)
end
net.Send(ply)
end
concommand.Add("FPP_SendRestrictTool", SendRestrictedTools)
-- Fallback owner, will own entities after disconnect
local function setFallbackOwner(ply, fallback)
ply.FPPFallbackOwner = fallback:SteamID()
end
local function changeFallbackOwner(ply, _, args)
local fallback = tonumber(args[1]) and Player(tonumber(args[1]))
if tonumber(args[1]) == -1 then
ply.FPPFallbackOwner = nil
FPP.Notify(ply, "Fallback owner set", true)
return
end
if not IsValid(fallback) or not fallback:IsPlayer() or fallback == ply then FPP.Notify(ply, "Player invalid", false) return end
setFallbackOwner(ply, fallback)
FPP.Notify(ply, "Fallback owner set", true)
end
concommand.Add("FPP_FallbackOwner", changeFallbackOwner)
--Buddies!
local function changeBuddies(ply, buddy, settings)
if not IsValid(ply) then return end
ply.Buddies = ply.Buddies or {}
ply.Buddies[buddy] = settings
local CPPIBuddies = {}
for k,v in pairs(ply.Buddies) do if table.HasValue(v, true) then table.insert(CPPIBuddies, k) end end
-- Also run at player spawn because clients send their buddies through this command
hook.Run("CPPIFriendsChanged", ply, CPPIBuddies)
-- Update the prop protection
local affectedProps = {}
for k,v in pairs(ents.GetAll()) do
local owner = v:CPPIGetOwner()
if owner ~= ply then continue end
table.insert(affectedProps, v)
end
FPP.recalculateCanTouch({buddy}, affectedProps)
FPP.RecalculateConstrainedEntities({buddy}, affectedProps)
end
local function SetBuddy(ply, cmd, args)
if not args[6] then FPP.Notify(ply, "Argument(s) invalid", false) return end
local buddy = tonumber(args[1]) and Player(tonumber(args[1]))
if not IsValid(buddy) then FPP.Notify(ply, "Player invalid", false) return end
for k,v in pairs(args) do args[k] = tonumber(v) end
local settings = {Physgun = tobool(args[2]), Gravgun = tobool(args[3]), Toolgun = tobool(args[4]), PlayerUse = tobool(args[5]), EntityDamage = tobool(args[6])}
-- Antispam measure
timer.Create("FPP_BuddiesUpdate" .. ply:UserID() .. ", " .. buddy:UserID(), 1, 1, function() changeBuddies(ply, buddy, settings) end)
end
concommand.Add("FPP_SetBuddy", SetBuddy)
local function CleanupDisconnected(ply, cmd, args)
if not args[1] then FPP.Notify(ply, "Invalid argument", false) return end
if args[1] == "disconnected" then
for k,v in pairs(ents.GetAll()) do
local Owner = v:CPPIGetOwner()
if Owner and not IsValid(Owner) then
v:Remove()
end
end
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " removed all disconnected players' props", true)
return
elseif not tonumber(args[1]) or not IsValid(Player(tonumber(args[1]))) then
FPP.Notify(ply, "Invalid player", false)
return
end
for k,v in pairs(ents.GetAll()) do
local Owner = v:CPPIGetOwner()
if Owner == Player(args[1]) and not v:IsWeapon() then
v:Remove()
end
end
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " removed " .. Player(args[1]):Nick() .. "'s entities", true)
end
concommand.Add("FPP_Cleanup", runIfAccess("FPP_Cleanup", CleanupDisconnected))
local function SetToolRestrict(ply, cmd, args)
if not args[3] then FPP.Notify(ply, "Invalid argument(s)", false) return end--FPP_restricttool <toolname> <type(admin/team)> <toggle(1/0)>
local toolname = args[1]
local RestrictWho = tonumber(args[2]) or args[2]-- "team" or "admin"
local teamtoggle = tonumber(args[4]) --this argument only exists when restricting a tool for a team
FPP.RestrictedTools[toolname] = FPP.RestrictedTools[toolname] or {}
if RestrictWho == "admin" then
FPP.RestrictedTools[toolname].admin = args[3] --weapons.Get("gmod_tool").Tool
--Save to database!
MySQLite.query("REPLACE INTO FPP_TOOLADMINONLY VALUES(" .. sql.SQLStr(toolname) .. ", " .. sql.SQLStr(args[3]) .. ");")
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " changed the admin status of " .. toolname , true)
elseif RestrictWho == "team" then
FPP.RestrictedTools[toolname]["team"] = FPP.RestrictedTools[toolname]["team"] or {}
if teamtoggle == 0 then
for k,v in pairs(FPP.RestrictedTools[toolname]["team"]) do
if v == tonumber(args[3]) then
table.remove(FPP.RestrictedTools[toolname]["team"], k)
break
end
end
elseif not table.HasValue(FPP.RestrictedTools[toolname]["team"], tonumber(args[3])) and teamtoggle == 1 then
table.insert(FPP.RestrictedTools[toolname]["team"], tonumber(args[3]))
end--Remove from the table if it's in there AND it's 0 otherwise do nothing
if tobool(teamtoggle) then -- if the team restrict is enabled
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " restricted " .. toolname .. " to certain teams", true)
MySQLite.query("REPLACE INTO FPP_TOOLTEAMRESTRICT VALUES(" .. sql.SQLStr(toolname) .. ", " .. tonumber(args[3]) .. ");")
else -- otherwise if the restriction for the team is being removed
FPP.NotifyAll(((ply.Nick and ply:Nick()) or "Console") .. " removed teamrestrictions from " .. toolname, true)
MySQLite.query("DELETE FROM FPP_TOOLTEAMRESTRICT WHERE toolname = " .. sql.SQLStr(toolname) .. " AND team = " .. tonumber(args[3]))
end
end
end
concommand.Add("FPP_restricttool", runIfAccess("FPP_Settings", SetToolRestrict))
local function RestrictToolPerson(ply, cmd, args)
if not args[3] then FPP.Notify(ply, "Invalid argument(s)", false) return end--FPP_restricttoolperson <toolname> <userid> <disallow, allow, remove(0,1,2)>
local toolname = args[1]
local target = Player(tonumber(args[2]))
local access = tonumber(args[3])
if not target:IsValid() then FPP.Notify(ply, "Invalid argument(s)", false) return end
if access < 0 or access > 2 then FPP.Notify(ply, "Invalid argument(s)", false) return end
FPP.RestrictedToolsPlayers[toolname] = FPP.RestrictedToolsPlayers[toolname] or {}
-- Disallow, even if other people can use it
if access == 0 or access == 1 then
FPP.RestrictedToolsPlayers[toolname][target:SteamID()] = access == 1
MySQLite.query("REPLACE INTO FPP_TOOLRESTRICTPERSON1 VALUES(" .. sql.SQLStr(toolname) .. ", " .. sql.SQLStr(target:SteamID()) .. ", " .. access .. ");")
elseif access == 2 then
-- reset tool status(make him like everyone else)
FPP.RestrictedToolsPlayers[toolname][target:SteamID()] = nil
MySQLite.query("DELETE FROM FPP_TOOLRESTRICTPERSON1 WHERE toolname = " .. sql.SQLStr(toolname) .. " AND steamid = " .. sql.SQLStr(target:SteamID()) .. ";")
end
FPP.Notify(ply, "Tool restrictions set successfully", true)
end
concommand.Add("FPP_restricttoolplayer", runIfAccess("FPP_Settings", RestrictToolPerson))
local function resetAllSetting(ply)
MySQLite.begin()
MySQLite.queueQuery("DELETE FROM FPP_PHYSGUN1")
MySQLite.queueQuery("DELETE FROM FPP_GRAVGUN1")
MySQLite.queueQuery("DELETE FROM FPP_TOOLGUN1")
MySQLite.queueQuery("DELETE FROM FPP_PLAYERUSE1")
MySQLite.queueQuery("DELETE FROM FPP_ENTITYDAMAGE1")
MySQLite.queueQuery("DELETE FROM FPP_GLOBALSETTINGS1")
MySQLite.queueQuery("DELETE FROM FPP_ANTISPAM1")
MySQLite.queueQuery("DELETE FROM FPP_BLOCKMODELSETTINGS1")
MySQLite.commit(function()
FPP.Settings = nil
include("fpp/sh_settings.lua")
SendSettings(player.GetAll())
if not IsValid(ply) then return end
FPP.Notify(ply, "Settings successfully reset.", true)
end)
end
concommand.Add("FPP_ResetAllSettings", runIfAccess("FPP_Settings", resetAllSetting))
local function resetBlockedModels(ply)
FPP.BlockedModels = {}
MySQLite.query("DELETE FROM FPP_BLOCKEDMODELS1", FPP.AddDefaultBlockedModels)
FPP.Notify(ply, "Settings successfully reset.", true)
end
concommand.Add("FPP_ResetBlockedModels", runIfAccess("FPP_Settings", resetBlockedModels))
local function refreshPrivatePlayerSettings(ply)
timer.Remove("FPP_RefreshPrivatePlayerSettings" .. ply:EntIndex())
timer.Create("FPP_RefreshPrivatePlayerSettings" .. ply:EntIndex(), 4, 1, function() FPP.recalculateCanTouch({ply}, ents.GetAll()) end)
end
concommand.Add("_FPP_RefreshPrivatePlayerSettings", refreshPrivatePlayerSettings)
/*---------------------------------------------------------------------------
Load all FPP settings
---------------------------------------------------------------------------*/
function FPP.Init(callback)
MySQLite.begin()
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_BLOCKED1(id INTEGER NOT NULL, var VARCHAR(40) NOT NULL, setting VARCHAR(100) NOT NULL, PRIMARY KEY(id));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_PHYSGUN1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_GRAVGUN1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_TOOLGUN1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_PLAYERUSE1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_ENTITYDAMAGE1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_GLOBALSETTINGS1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_BLOCKMODELSETTINGS1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_ANTISPAM1(var VARCHAR(40) NOT NULL, setting INTEGER NOT NULL, PRIMARY KEY(var));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_TOOLADMINONLY(toolname VARCHAR(40) NOT NULL, adminonly INTEGER NOT NULL, PRIMARY KEY(toolname));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_TOOLTEAMRESTRICT(toolname VARCHAR(40) NOT NULL, team INTEGER NOT NULL, PRIMARY KEY(toolname, team));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_TOOLRESTRICTPERSON1(toolname VARCHAR(40) NOT NULL, steamid VARCHAR(40) NOT NULL, allow INTEGER NOT NULL, PRIMARY KEY(steamid, toolname));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_GROUPS3(groupname VARCHAR(40) NOT NULL, allowdefault INTEGER NOT NULL, PRIMARY KEY(groupname));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_GROUPTOOL(groupname VARCHAR(40) NOT NULL, tool VARCHAR(45) NOT NULL, PRIMARY KEY(groupname, tool));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_GROUPMEMBERS1(steamid VARCHAR(40) NOT NULL, groupname VARCHAR(40) NOT NULL, PRIMARY KEY(steamid));")
MySQLite.queueQuery("CREATE TABLE IF NOT EXISTS FPP_BLOCKEDMODELS1(model VARCHAR(140) NOT NULL PRIMARY KEY);")
if MySQLite.isMySQL() then
MySQLite.queueQuery("ALTER TABLE FPP_BLOCKED1 CHANGE id id INTEGER AUTO_INCREMENT;")
end
MySQLite.commit(function()
RetrieveBlocked()
RetrieveBlockedModels()
RetrieveRestrictedTools()
RetrieveGroups()
RetrieveSettings()
-- Callback when FPP is done creating the tables
if callback then callback() end
end)
end
local assbackup = ASS_RegisterPlugin -- Suddenly after witing this code, ASS spamprotection and propprotection broke. I have no clue why. I guess you should use FPP then
if assbackup then
function ASS_RegisterPlugin(plugin, ...)
if plugin.Name == "Sandbox Spam Protection" or plugin.Name == "Sandbox Prop Protection" then
return
end
return assbackup(plugin, ...)
end
end
| mit |
lichtl/darkstar | scripts/zones/Konschtat_Highlands/mobs/Highlander_Lizard.lua | 19 | 1385 | -----------------------------------
-- Area: Konschtat Highlands
-- NM: Highlander Lizard
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/fieldsofvalor");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
-- Higher TP Gain per melee hit than normal lizards.
-- It is definitly NOT regain.
mob:addMod(MOD_STORETP, 25); -- May need adjustment.
-- Hits especially hard for his level, even by NM standards.
mob:addMod(MOD_ATT, 50); -- May need adjustment along with cmbDmgMult in mob_pools.sql
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
-- I think he still counts the FoV pages? Most NM's do not though.
checkRegime(player,mob,20,2);
checkRegime(player,mob,82,2);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random(1200,1800)); -- 20~30 min repop
end;
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/items/high_breath_mantle.lua | 12 | 1077 | -----------------------------------------
-- ID: 15487
-- Item: High Breath Mantle
-- Item Effect: HP+38 / Enmity+5
-----------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
-----------------------------------------
function onItemCheck(target)
local effect = target:getStatusEffect(dsp.effect.ENCHANTMENT)
if (effect ~= nil) then
if (effect:getSubType() == 15487) then
target:delStatusEffect(dsp.effect.ENCHANTMENT)
end
end
return 0
end
function onItemUse(target)
if (target:hasStatusEffect(dsp.effect.ENCHANTMENT) == true) then
target:delStatusEffect(dsp.effect.ENCHANTMENT)
target:addStatusEffect(dsp.effect.ENCHANTMENT,0,0,1800,15487)
else
target:addStatusEffect(dsp.effect.ENCHANTMENT,0,0,1800,15487)
end
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 38)
target:addMod(dsp.mod.ENMITY, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 38)
target:delMod(dsp.mod.ENMITY, 5)
end | gpl-3.0 |
lichtl/darkstar | scripts/globals/weaponskills/chant_du_cygne.lua | 26 | 1307 | -----------------------------------
-- Chant du Cygne
-- Sword weapon skill
-- Skill level: EMPYREAN
-- Delivers a three-hit attack. Chance of params.critical varies with TP.
-- Will stack with Sneak Attack.
-- Element: None
-- Modifiers: DEX:60%
-- 100%TP 200%TP 300%TP
-- ALL 2.25
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 3;
params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25;
params.str_wsc = 0.0; params.dex_wsc = 0.6; 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.1; params.crit200 = 0.3; params.crit300 = 0.5;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.dex_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Lufaise_Meadows/mobs/Padfoot.lua | 13 | 2699 | -----------------------------------
-- Area: Lufaise Meadows
-- MOB: Padfoot
-- @pos 260.445 -1.761 -27.862 24 (True Copy) 16875578
-- @pos 412.447 -0.057 -200.161 24 (Fake Copies) 16875615
-- @pos -378.950 -15.742 144.215 24 || 16875703
-- @pos -43.689 0.487 -328.028 24 || 16875552
-- @pos -141.523 -15.529 91.709 24 \/ 16875748
-- TODO: the "true" Padfoot should not always be the same one at same pos every spawn cycle.
-----------------------------------
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
local PadfootCloneSpawn =
{
16875615,
16875703,
16875748,
16875552
}
if (mob:getID() == 16875578) then
local random = math.random(#PadfootCloneSpawn);
-- pick random padfoot to spawn as
local myPadfoot = PadfootCloneSpawn[random];
local i = 1;
while i <= (#PadfootCloneSpawn) do
local padfoot = PadfootCloneSpawn[i]
UpdateNMSpawnPoint(padfoot);
if padfoot == myPadfoot then
local position = GetMobByID(padfoot):getSpawnPos();
mob:setPos(position.x, position.y, position.z);
local otherMob = GetMobByID(myPadfoot);
SpawnMob(myPadfoot);
position = mob:getSpawnPos()
otherMob:setPos(position.x, position.y, position.z);
else
SpawnMob(padfoot);
end
i = i + 1;
end
-- TODO: Add Treasure Hunter
if (math.random((1),(100)) <= 27) then -- Hardcoded "this or this item" drop rate until implemented.
SetDropRate(4478,14782,1000); -- Astral Earring
SetDropRate(4478,14676,0);
else
SetDropRate(4478,14782,0);
SetDropRate(4478,14676,1000); -- Assailants Ring
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- OnMobDespawn
-----------------------------------
function onMobDespawn(mob)
local PadfootClone =
{
16875615,
16875703,
16875748,
16875552
}
if (mob:getID() == 16875578) then
local i = 1;
while i <= (#PadfootClone) do
if (GetMobAction(PadfootClone[i]) ~= 0) then
DespawnMob(PadfootClone[i]);
end
i = i + 1;
end
UpdateNMSpawnPoint(16875578);
GetMobByID(16875578):setRespawnTime(math.random(75600,86400)); -- 21-24 hours
end
end;
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Cloister_of_Flames/bcnms/trial-size_trial_by_fire.lua | 26 | 2164 | -----------------------------------
-- Area: Cloister of Flames
-- BCNM: Trial-size Trial by Fire
-- @pos -721 0 -598 207
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Cloister_of_Flames/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
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
elseif (leavecode == 4) then
player:setVar("TrialSizeFire_date",tonumber(os.date("%j"))); -- If you loose, you need to wait 1 real day
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:hasSpell(298) == false) then
player:addSpell(298); -- Ifrit
player:messageSpecial(IFRIT_UNLOCKED,0,0,0);
end
if (player:hasItem(4181) == false) then
player:addItem(4181);
player:messageSpecial(ITEM_OBTAINED,4181); -- Scroll of instant warp
end
player:setVar("TrialSizeFire_date", 0);
player:addFame(KAZHAM,30);
player:completeQuest(OUTLANDS,TRIAL_SIZE_TRIAL_BY_FIRE);
end
end; | gpl-3.0 |
yariplus/love-demos | love-slider/main.lua | 1 | 1230 | require "game"
g = {}
g.entities = {}
g.State = require "states/state"
g.statePlay = require "states/statePlay"
g.stateMenu = require "states/stateMenu"
require "load"
function love.update(dt)
game.tick = game.tick + 1
game.state:update(dt)
if game.matching then
if game.matching + 40 < game.tick then
game.match()
end
end
end
function love.draw()
love.graphics.clear()
love.graphics.setColor(255, 255, 255)
love.graphics.draw(assets.SpriteBatches.cards)
game.state:draw()
end
function love.mousepressed(x, y, button)
for i=1,#game.cards do
game.cards[i]:click(x, y, button)
end
if game.positions[1][1].number == 1 and
game.positions[2][1].number == 2 and
game.positions[3][1].number == 3 and
game.positions[4][1].number == 4 and
game.positions[1][2].number == 5 and
game.positions[2][2].number == 6 and
game.positions[3][2].number == 7 and
game.positions[4][2].number == 8 and
game.positions[1][3].number == 9 and
game.positions[2][3].number == 10 and
game.positions[3][3].number == 11 and
game.positions[4][3].number == 12 and
game.positions[1][4].number == 13 and
game.positions[2][4].number == 14 and
game.positions[3][4].number == 15 then
state.won = true
end
end
| cc0-1.0 |
lichtl/darkstar | scripts/globals/items/bowl_of_witch_stew.lua | 18 | 1449 | -----------------------------------------
-- ID: 4344
-- Item: witch_stew
-- Food Effect: 4hours, All Races
-----------------------------------------
-- Magic Points 45
-- Strength -1
-- Mind 4
-- MP Recovered While Healing 4
-- Enmity -4
-----------------------------------------
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,14400,4344);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 45);
target:addMod(MOD_STR, -1);
target:addMod(MOD_MND, 4);
target:addMod(MOD_MPHEAL, 4);
target:addMod(MOD_ENMITY, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 45);
target:delMod(MOD_STR, -1);
target:delMod(MOD_MND, 4);
target:delMod(MOD_MPHEAL, 4);
target:delMod(MOD_ENMITY, -4);
end;
| gpl-3.0 |
appwilldev/moochine | lualibs/ltp/template.lua | 3 | 5946 | --
-- Copyright 2007-2008 Savarese Software Research Corporation.
--
-- 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.savarese.com/software/ApacheLicense-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local ltp = require('ltp.util')
local function compile_template_to_table(result, data, start_lua, end_lua)
local LF, CR, EQ = 10, 13, 61
local i1, i2, i3
i3 = 1
repeat
i2, i1 = data:find(start_lua, i3, true)
if i2 then
if i3 < i2 then
table.insert(result, "table.insert(output,")
table.insert(result, string.format('%q', data:sub(i3, i2 - 1)))
table.insert(result, ");")
end
i1 = i1 + 2
i2, i3 = data:find(end_lua, i1, true)
if i2 then
if data:byte(i1-1) == EQ then
table.insert(result, "table.insert(output,")
table.insert(result, data:sub(i1, i2 - 1))
table.insert(result, ");")
i3 = i3 + 1
else
table.insert(result, data:sub(i1, i2 - 1))
i3 = i3 + 1
if data:byte(i3) == LF then
i3 = i3 + 1
elseif data:byte(i3) == CR and data:byte(i3+1) == LF then
i3 = i3 + 2
end
end
end
elseif i3 <= #data then
table.insert(result, "table.insert(output,")
table.insert(result, string.format('%q', data:sub(i3)))
table.insert(result, ");")
end
until not i2
return result
end
local function compile_template_as_function(data, start_lua, end_lua)
local result = { "return function(output) " }
table.insert(compile_template_to_table(result, data, start_lua, end_lua),
"end")
return table.concat(result)
end
local function compile_template_as_chunk(data, start_lua, end_lua)
local result = { "local output = ... " }
return
table.concat(compile_template_to_table(result, data, start_lua, end_lua))
end
local function compile_template(data, start_lua, end_lua)
return table.concat(compile_template_to_table({ }, data, start_lua, end_lua))
end
local function load_template(data, start_lua, end_lua)
return assert(loadstring(compile_template_as_chunk(data, start_lua, end_lua),
"=(load)"))
end
local function execute_template(template, environment, output)
setfenv(template, environment)(output)
end
local function basic_environment(merge_global, environment)
if not environment then
environment = { }
end
if merge_global then
ltp.merge_index(environment, _G)
else
environment.table = table
end
return environment
end
local function load_environment(env_files, merge_global)
local environment = nil
if env_files and #env_files > 0 then
for i = 1,#env_files,1 do
local efun = assert(loadfile(env_files[i]))
if i > 1 then
environment = ltp.merge_table(setfenv(efun, environment)(), environment)
else
environment = basic_environment(merge_global, efun())
end
end
else
environment = basic_environment(merge_global)
end
return environment
end
local function read_template(template)
return ((template == "-" and io.stdin:read("*a")) or ltp.read_all(template))
end
local function render_template(template_data, start_lua, end_lua, environment)
local rfun = load_template(template_data, start_lua, end_lua)
local output = { }
execute_template(rfun, environment, output)
return table.concat(output)
end
local function execute_env_code(env_code, environment)
for i = 1,#env_code do
local fun, emsg = loadstring(env_code[i])
if fun then
setfenv(fun, environment)()
else
error("error loading " .. env_code[i] .. "\n" .. emsg)
end
end
end
local function render(outfile, num_passes, template, merge_global,
env_files, start_lua, end_lua, env_code)
local data = assert(read_template(template), "error reading " .. template)
local environment = load_environment(env_files, merge_global)
execute_env_code(env_code, environment)
if num_passes > 0 then
for i = 1,num_passes do
data = render_template(data, start_lua, end_lua, environment)
end
else
-- Prevent an infinite loop by capping expansion to 100 times.
num_passes = 1
repeat
data = render_template(data, start_lua, end_lua, environment)
num_passes = num_passes + 1
until data:find(start_lua, 1, true) == nil or num_passes >= 100
end
outfile:write(data);
end
local function compile_as_function(outfile, template, start_lua, end_lua)
local data = read_template(template)
outfile:write(compile_template_as_function(data, start_lua, end_lua))
end
local function compile(outfile, template, start_lua, end_lua)
local data = read_template(template)
outfile:write(compile_template(data, start_lua, end_lua))
end
return ltp.merge_table(
{
compile_template_to_table = compile_template_to_table,
compile_template_as_chunk = compile_template_as_chunk,
compile_template_as_function = compile_template_as_function,
compile_template = compile_template,
load_template = load_template,
execute_template = execute_template,
basic_environment = basic_environment,
load_environment = load_environment,
render_template = render_template,
execute_env_code = execute_env_code,
render = render,
compile_as_function = compile_as_function,
compile = compile
},
ltp
)
| apache-2.0 |
Mudlet-cn/mudlet | src/old_mudlet-lua/lua/Other.lua | 6 | 16089 | ----------------------------------------------------------------------------------
--- Mudlet Unsorted Stuff
----------------------------------------------------------------------------------
-- Extending default libraries makes Babelfish happy.
setmetatable( _G, {
["__call"] = function(func, ...)
if type(func) == "function" then
return func(...)
else
local h = metatable(func).__call
if h then
return h(func, ...)
elseif _G[type(func)][func] then
_G[type(func)][func](...)
end
end
end,
})
--- Mudlet's support for ATCP. This is primarily available on IRE-based MUDs, but Mudlets impelementation is generic enough
--- such that any it should work on others. <br/><br/>
---
--- The latest ATCP data is stored in the atcp table. Whenever new data arrives, the previous is overwritten. An event is also
--- raised for each ATCP message that arrives. To find out the available messages available in the atcp table and the event names,
--- you can use display(atcp). <br/><br/>
---
--- Note that while the typical message comes in the format of Module.Submodule, ie Char.Vitals or Room.Exits, in Mudlet the dot is
--- removed - so it becomes CharVitals and RoomExits. Here's an example:
--- <pre>
--- room_number = tonumber(atcp.RoomNum)
--- echo(room_number)
--- </pre>
---
--- Triggering on ATCP events: <br/>
--- If you'd like to trigger on ATCP messages, then you need to create scripts to attach handlers to the ATCP messages.
--- The ATCP handler names follow the same format as the atcp table - RoomNum, RoomExits, CharVitals and so on. <br/><br/>
---
--- While the concept of handlers for events is to be explained elsewhere in the manual, the quick rundown is this - place
--- the event name you'd like your script to listen to into the Add User Defined Event Handler: field and press the + button
--- to register it. Next, because scripts in Mudlet can have multiple functions, you need to tell Mudlet which function
--- should it call for you when your handler receives a message. You do that by setting the Script name: to the function
--- name in the script you'd like to be called. <br/><br/>
---
--- For example, if you'd like to listen to the RoomExits event and have it call the process_exits() function -
--- register RoomExits as the event handler, make the script name be process_exits, and use this in the script:
--- <pre>
--- function process_exits(event, args)
--- echo("Called event: " .. event .. "\nWith args: " .. args)
--- end
--- </pre>
---
--- Feel free to experiment with this to achieve the desired results. A ATCP demo package is also available on the forums
--- for using event handlers and parsing its messages into Lua datastructures. <br/>
---
--- @release Mudlet 1.0.6
---
--- @see sendATCP
---
--- @class function
--- @name atcp
atcp = {}
--- <b><u>TODO</u></b> Table walklist.
---
--- @class function
--- @name walklist
walklist = {}
--- <b><u>TODO</u></b> Variable walkdelay.
---
--- @class function
--- @name walkdelay
walkdelay = 0
--- <b><u>TODO</u></b> Table SavedVariables.
---
--- @class function
--- @name SavedVariables
SavedVariables = {}
--- Sends a list of commands to the MUD. You can use this to send some things at once instead of having
--- to use multiple send() commands one after another.
---
--- @param ... list of commands
--- @param echoTheValue optional boolean flag (default value is true) which determine if value should
--- be echoed back on client.
---
--- @usage Use sendAll instead of multiple send commands.
--- <pre>
--- sendAll("stand", "wield shield", "say ha!")
--- </pre>
--- Instead of calling:
--- <pre>
--- send ("stand")
--- send ("wield shield")
--- send ("say ha!")
--- </pre>
--- @usage Use sendAll and do not echo sent commnad on the main window.
--- <pre>
--- sendAll("stand", "wield shield", "say ha!", false)
--- </pre>
---
--- @see send
function sendAll(...)
local args = {...}
local echo = true
if type(args[#args]) == 'boolean' then
echo = table.remove(args, #args)
end
for i, v in ipairs(args) do
if type(v) == 'string' then send(v, echo) end
end
end
--- Creates a group of a given type that will persist through sessions.
---
--- @param name name of the teim
--- @param itemtype type of the item - can be trigger, alias, or timer
---
--- @usage
--- <pre>
--- --create a new trigger group
--- permGroup("Combat triggers", "trigger")
--- </pre>
--- @usage
--- <pre>
--- --create a new alias group only if one doesn't exist already
--- if exists("Defensive aliases", "alias") == 0 then
--- permGroup("Defensive aliases", "alias")
--- end
--- </pre>
function permGroup(name, itemtype)
assert(type(name) == "string", "permGroup: need a name for the new thing")
local t = {
timer = function(name)
return (permTimer(name, "", 0, "") == -1) and false or true
end,
trigger = function(name)
return (permSubstringTrigger(name, "", {""}, "") == -1) and false or true
end,
alias = function(name)
return (permAlias(name, "", "", "") == -1) and false or true
end
}
assert(t[itemtype], "permGroup: "..tostring(itemtype).." isn't a valid type")
return t[itemtype](name)
end
--- Checks to see if a given file or folder exists. If it exists, it'll return the Lua true boolean value, otherwise false.
---
--- @usage
--- <pre>
--- if io.exists("/home/user/Desktop") then
--- echo("This folder exists!")
--- else
--- echo("This folder doesn't exist.")
--- end
---
--- if io.exists("/home/user/Desktop/file.txt") then
--- echo("This file exists!")
--- else
--- echo("This file doesn't exist.")
--- end
--- </pre>
---
--- @return true or false
function io.exists(fileOfFolderName)
local f = io.open(fileOfFolderName)
if f then
io.close(f)
return true
end
return false
end
--- Implementation of boolean exclusive or.
---
--- @usage All following will return false.
--- <pre>
--- xor(false, false)
--- xor(true, true)
--- </pre>
---
--- @return true or false
function xor(a, b)
if (a and (not b)) or (b and (not a)) then
return true
else
return false
end
end
--- Determine operating system.
---
--- @usage
--- <pre>
--- if "linux" == getOS() then
--- echo("We are using GNU/Linux!")
--- end
--- </pre>
---
--- @return "linux", "mac" or "windows" string
function getOS()
if string.char(getMudletHomeDir():byte()) == "/" then
if string.find(os.getenv("HOME"), "home") == 2 then
return "linux"
else
return "mac"
end
else
return "windows"
end
end
--- This function flags a variable to be saved by Mudlet's variable persistence system.
--- Variables are automatically unpacked into the global namespace when the profile is loaded.
--- They are saved to "SavedVariables.lua" when the profile is closed or saved.
---
--- @usage remember("varName")
---
--- @see loadVars
function remember(varName)
if not _saveTable then
_saveTable = {}
end
_saveTable[varName] = _G[varName]
end
--- This function should be primarily used by Mudlet. It loads saved settings in from the Mudlet home directory
--- and unpacks them into the global namespace.
---
--- @see remember
function loadVars()
if string.char(getMudletHomeDir():byte()) == "/" then _sep = "/" else _sep = "\\" end
local l_SettingsFile = getMudletHomeDir() .. _sep .. "SavedVariables.lua"
local lt_VariableHolder = {}
if (io.exists(l_SettingsFile)) then
table.load(l_SettingsFile, lt_VariableHolder)
for k,v in pairs(lt_VariableHolder) do
_G[k] = v
end
end
end
--- This function should primarily be used by Mudlet. It saves the contents of _saveTable into a file for persistence.
---
--- @see loadVars
function saveVars()
if string.char(getMudletHomeDir():byte()) == "/" then _sep = "/" else _sep = "\\" end
local l_SettingsFile = getMudletHomeDir() .. _sep .. "SavedVariables.lua"
for k,_ in pairs(_saveTable) do
remember(k)
end
table.save(l_SettingsFile, _saveTable)
end
--- The below functions (table.save, table.load) can be used to save individual Lua tables to disc and load
--- them again at a later time e.g. make a database, collect statistical information etc.
--- These functions are also used by Mudlet to load & save the entire Lua session variables. <br/><br/>
---
--- Original code written by CHILLCODE™ on https://board.ptokax.ch, distributed under the same terms as Lua itself. <br/><br/>
---
--- Notes: <br/>
--- Userdata and indices of these are not saved <br/>
--- Functions are saved via string.dump, so make sure it has no upvalues <br/>
--- References are saved <br/>
---
--- @usage Saves the globals table (minus some lua enviroment stuffs) into a file (only Mudlet should use this).
--- <pre>
--- table.save(file)
--- </pre>
--- @usage Saves the given table into the given file.
--- <pre>
--- table.save(file, table)
--- </pre>
---
--- @see table.load
function table.save( sfile, t )
assert(type(sfile) == "string", "table.save requires a file path to save to")
local tables = {}
table.insert( tables, t )
local lookup = { [t] = 1 }
local file = io.open( sfile, "w" )
file:write( "return {" )
for i,v in ipairs( tables ) do
table.pickle( v, file, tables, lookup )
end
file:write( "}" )
file:close()
end
--- <b><u>TODO</u></b> table.pickle( t, file, tables, lookup )
function table.pickle( t, file, tables, lookup )
file:write( "{" )
for i,v in pairs( t ) do
-- escape functions
if type( v ) ~= "function" and type( v ) ~= "userdata" and (i ~= "string" and i ~= "xpcall" and i ~= "package" and i ~= "os" and i ~= "io" and i ~= "math" and i ~= "debug" and i ~= "coroutine" and i ~= "_G" and i ~= "_VERSION" and i ~= "table") then
-- handle index
if type( i ) == "table" then
if not lookup[i] then
table.insert( tables, i )
lookup[i] = table.maxn( tables )
end
file:write( "[{"..lookup[i].."}] = " )
else
local index = ( type( i ) == "string" and "[ "..string.enclose( i, 50 ).." ]" ) or string.format( "[%d]", i )
file:write( index.." = " )
end
-- handle value
if type( v ) == "table" then
if not lookup[v] then
table.insert( tables, v )
lookup[v] = table.maxn( tables )
end
file:write( "{"..lookup[v].."}," )
else
local value = ( type( v ) == "string" and string.enclose( v, 50 ) ) or tostring( v )
file:write( value.."," )
end
end
end
file:write( "},\n" )
end
--- Restores a Lua table from a data file that has been saved with table.save().
---
--- @usage Loads a serialized file into the globals table (only Mudlet should use this).
--- <pre>
--- table.load(file)
--- </pre>
--- @usage Loads a serialized file into the given table.
--- <pre>
--- table.load(file, table)
--- </pre>
---
--- @see table.save
function table.load( sfile, loadinto )
assert(type(sfile) == "string", "table.load requires a file path to load")
local tables = dofile( sfile )
if tables then
if loadinto ~= nil and type(loadinto) == "table" then
table.unpickle( tables[1], tables, loadinto )
else
table.unpickle( tables[1], tables, _G )
end
end
end
--- <b><u>TODO</u></b> table.unpickle( t, tables, tcopy, pickled )
function table.unpickle( t, tables, tcopy, pickled )
pickled = pickled or {}
pickled[t] = tcopy
for i,v in pairs( t ) do
local i2 = i
if type( i ) == "table" then
local pointer = tables[ i[1] ]
if pickled[pointer] then
i2 = pickled[pointer]
else
i2 = {}
table.unpickle( pointer, tables, i2, pickled )
end
end
local v2 = v
if type( v ) == "table" then
local pointer = tables[ v[1] ]
if pickled[pointer] then
v2 = pickled[pointer]
else
v2 = {}
table.unpickle( pointer, tables, v2, pickled )
end
end
tcopy[i2] = v2
end
end
--- <b><u>TODO</u></b> speedwalktimer()
function speedwalktimer()
send(walklist[1])
table.remove(walklist, 1)
if #walklist>0 then
tempTimer(walkdelay, [[speedwalktimer()]])
end
end
--- <b><u>TODO</u></b> speedwalk(dirString, backwards, delay)
function speedwalk(dirString, backwards, delay)
local dirString = dirString:lower()
walklist = {}
walkdelay = delay
local reversedir = {
n = "s",
en = "sw",
e = "w",
es = "nw",
s = "n",
ws = "ne",
w = "e",
wn = "se",
u = "d",
d = "u",
ni = "out",
tuo = "in"
}
if not backwards then
for count, direction in string.gmatch(dirString, "([0-9]*)([neswudio][ewnu]?t?)") do
count = (count == "" and 1 or count)
for i=1, count do
if delay then walklist[#walklist+1] = direction
else send(direction)
end
end
end
else
for direction, count in string.gmatch(dirString:reverse(), "(t?[ewnu]?[neswudio])([0-9]*)") do
count = (count == "" and 1 or count)
for i=1, count do
if delay then walklist[#walklist+1] = reversedir[direction]
else send(reversedir[direction])
end
end
end
end
if walkdelay then
speedwalktimer()
end
end
--- <b><u>TODO</u></b> _comp(a, b)
function _comp(a, b)
if type(a) ~= type(b) then return false end
if type(a) == 'table' then
for k, v in pairs(a) do
if not b[k] then return false end
if not _comp(v, b[k]) then return false end
end
else
if a ~= b then return false end
end
return true
end
--- <b><u>TODO</u></b> phpTable(...) - abuse to: http://richard.warburton.it
function phpTable(...)
local newTable, keys, values = {}, {}, {}
newTable.pairs = function(self) -- pairs iterator
local count = 0
return function()
count = count + 1
return keys[count], values[keys[count]]
end
end
setmetatable(newTable, {
__newindex = function(self, key, value)
if not self[key] then table.insert(keys, key)
elseif value == nil then -- Handle item delete
local count = 1
while keys[count] ~= key do count = count + 1 end
table.remove(keys, count)
end
values[key] = value -- replace/create
end,
__index=function(self, key) return values[key] end,
isPhpTable = true,
})
local args = {...}
for x=1, #args do
for k, v in pairs(args[x]) do newTable[k] = v end
end
return newTable
end
--- <b><u>TODO</u></b> getColorWildcard(color)
function getColorWildcard(color)
local color = tonumber(color)
local startc
local endc
local results = {}
for i = 1, string.len(line) do
selectSection(i, 1)
if isAnsiFgColor(color) then
if not startc then if i == 1 then startc = 1 else startc = i + 1 end
else endc = i + 1
if i == line:len() then results[#results + 1] = line:sub(startc, endc) end
end
elseif startc then
results[#results + 1] = line:sub(startc, endc)
startc = nil
end
end
return results[1] and results or false
end
do
local oldsetExit = setExit
local exitmap = {
n = 1,
ne = 2,
nw = 3,
e = 4,
w = 5,
s = 6,
se = 7,
sw = 8,
u = 9,
d = 10,
["in"] = 11,
out = 12
}
function setExit(from, to, direction)
if type(direction) == "string" and not exitmap[direction] then return false end
return oldsetExit(from, to, type(direction) == "string" and exitmap[direction] or direction)
end
end
do
local oldlockExit = lockExit
local oldhasExitLock = hasExitLock
local exitmap = {
n = 1,
north = 1,
ne = 2,
northeast = 2,
nw = 3,
northwest = 3,
e = 4,
east = 4,
w = 5,
west = 5,
s = 6,
south = 6,
se = 7,
southeast = 7,
sw = 8,
southwest = 8,
u = 9,
up = 9,
d = 10,
down = 10,
["in"] = 11,
out = 12
}
function lockExit(from, direction, status)
if type(direction) == "string" and not exitmap[direction] then return false end
return oldlockExit(from, type(direction) == "string" and exitmap[direction] or direction, status)
end
function hasExitLock(from, direction)
if type(direction) == "string" and not exitmap[direction] then return false end
return oldhasExitLock(from, type(direction) == "string" and exitmap[direction] or direction)
end
end
function print(...)
local t, echo, tostring = {...}, echo, tostring
for i = 1, #t do
echo((tostring(t[i]) or '?').." ")
end
echo("\n")
end
| gpl-2.0 |
RunAwayDSP/darkstar | scripts/zones/Bastok_Markets/npcs/Cleades.lua | 9 | 3556 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Cleades
-- Type: Mission Giver
-- !pos -358 -10 -168 235
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
local ID = require("scripts/zones/Bastok_Markets/IDs");
-----------------------------------
function onTrade(player,npc,trade)
local CurrentMission = player:getCurrentMission(BASTOK);
local Count = trade:getItemCount();
if (CurrentMission ~= dsp.mission.id.bastok.NONE) then
if (CurrentMission == dsp.mission.id.bastok.FETICHISM and player:hasCompletedMission(BASTOK,dsp.mission.id.bastok.FETICHISM) == false and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then
player:startEvent(1008); -- Finish Mission "Fetichism" (First Time)
elseif (CurrentMission == dsp.mission.id.bastok.FETICHISM and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then
player:startEvent(1005); -- Finish Mission "Fetichism" (Repeat)
elseif (CurrentMission == dsp.mission.id.bastok.TO_THE_FORSAKEN_MINES and player:hasCompletedMission(BASTOK,dsp.mission.id.bastok.TO_THE_FORSAKEN_MINES) == false and trade:hasItemQty(563,1) and Count == 1) then
player:startEvent(1010); -- Finish Mission "To the forsaken mines" (First Time)
elseif (CurrentMission == dsp.mission.id.bastok.TO_THE_FORSAKEN_MINES and trade:hasItemQty(563,1) and Count == 1) then
player:startEvent(1006); -- Finish Mission "To the forsaken mines" (Repeat)
end
end
end;
function onTrigger(player,npc)
if (player:getNation() ~= dsp.nation.BASTOK) then
player:startEvent(1003); -- For non-Bastokian
else
local CurrentMission = player:getCurrentMission(BASTOK);
local cs, p, offset = getMissionOffset(player,1,CurrentMission,player:getCharVar("MissionStatus"));
if (cs ~= 0 or offset ~= 0 or ((CurrentMission == dsp.mission.id.bastok.THE_ZERUHN_REPORT or
CurrentMission == dsp.mission.id.bastok.RETURN_OF_THE_TALEKEEPER) and offset == 0)) then
if (CurrentMission <= dsp.mission.id.bastok.XARCABARD_LAND_OF_TRUTHS and cs == 0) then
player:showText(npc,ID.text.ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 1~5)
elseif (CurrentMission > dsp.mission.id.bastok.XARCABARD_LAND_OF_TRUTHS and cs == 0) then
player:showText(npc,ID.text.EXTENDED_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 6~10)
else
player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]);
end
elseif (player:getRank() == 1 and player:hasCompletedMission(BASTOK,dsp.mission.id.bastok.THE_ZERUHN_REPORT) == false) then
player:startEvent(1000); -- Start First Mission "The Zeruhn Report"
elseif (CurrentMission ~= dsp.mission.id.bastok.NONE) then
player:startEvent(1002); -- Have mission already activated
else
local flagMission, repeatMission = getMissionMask(player);
player:startEvent(1001,flagMission,0,0,0,0,repeatMission); -- Mission List
end
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
finishMissionTimeline(player,1,csid,option);
end; | gpl-3.0 |
taiha/luci | applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua | 68 | 7091 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local ip = require "luci.ip"
local fs = require "nixio.fs"
if arg[1] then
mp = Map("olsrd", translate("OLSR - Plugins"))
p = mp:section(TypedSection, "LoadPlugin", translate("Plugin configuration"))
p:depends("library", arg[1])
p.anonymous = true
ign = p:option(Flag, "ignore", translate("Enable"))
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
lib = p:option(DummyValue, "library", translate("Library"))
lib.default = arg[1]
local function Range(x,y)
local t = {}
for i = x, y do t[#t+1] = i end
return t
end
local function Cidr2IpMask(val)
if val then
for i = 1, #val do
local cidr = ip.IPv4(val[i]) or ip.IPv6(val[i])
if cidr then
val[i] = cidr:network():string() .. " " .. cidr:mask():string()
end
end
return val
end
end
local function IpMask2Cidr(val)
if val then
for i = 1, #val do
local ip, mask = val[i]:gmatch("([^%s]+)%s+([^%s]+)")()
local cidr
if ip and mask and ip:match(":") then
cidr = ip.IPv6(ip, mask)
elseif ip and mask then
cidr = ip.IPv4(ip, mask)
end
if cidr then
val[i] = cidr:string()
end
end
return val
end
end
local knownPlParams = {
["olsrd_bmf.so.1.5.3"] = {
{ Value, "BmfInterface", "bmf0" },
{ Value, "BmfInterfaceIp", "10.10.10.234/24" },
{ Flag, "DoLocalBroadcast", "no" },
{ Flag, "CapturePacketsOnOlsrInterfaces", "yes" },
{ ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } },
{ Value, "BroadcastRetransmitCount", "2" },
{ Value, "FanOutLimit", "4" },
{ DynamicList, "NonOlsrIf", "br-lan" }
},
["olsrd_dyn_gw.so.0.4"] = {
{ Value, "Interval", "40" },
{ DynamicList, "Ping", "141.1.1.1" },
{ DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask }
},
["olsrd_httpinfo.so.0.1"] = {
{ Value, "port", "80" },
{ DynamicList, "Host", "163.24.87.3" },
{ DynamicList, "Net", "0.0.0.0/0", Cidr2IpMask }
},
["olsrd_nameservice.so.0.3"] = {
{ DynamicList, "name", "my-name.mesh" },
{ DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" },
{ Value, "suffix", ".olsr" },
{ Value, "hosts_file", "/path/to/hosts_file" },
{ Value, "add_hosts", "/path/to/file" },
{ Value, "dns_server", "141.1.1.1" },
{ Value, "resolv_file", "/path/to/resolv.conf" },
{ Value, "interval", "120" },
{ Value, "timeout", "240" },
{ Value, "lat", "12.123" },
{ Value, "lon", "12.123" },
{ Value, "latlon_file", "/var/run/latlon.js" },
{ Value, "latlon_infile", "/var/run/gps.txt" },
{ Value, "sighup_pid_file", "/var/run/dnsmasq.pid" },
{ Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" },
{ DynamicList, "service", "http://me.olsr:80|tcp|my little homepage" },
{ Value, "services_file", "/var/run/services_olsr" },
{ Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" },
{ DynamicList, "mac", "xx:xx:xx:xx:xx:xx[,0-255]" },
{ Value, "macs_file", "/path/to/macs_file" },
{ Value, "macs_change_script", "/path/to/script" }
},
["olsrd_quagga.so.0.2.2"] = {
{ StaticList, "redistribute", {
"system", "kernel", "connect", "static", "rip", "ripng", "ospf",
"ospf6", "isis", "bgp", "hsls"
} },
{ ListValue, "ExportRoutes", { "only", "both" } },
{ Flag, "LocalPref", "true" },
{ Value, "Distance", Range(0,255) }
},
["olsrd_secure.so.0.5"] = {
{ Value, "Keyfile", "/etc/private-olsr.key" }
},
["olsrd_txtinfo.so.0.1"] = {
{ Value, "accept", "127.0.0.1" }
},
["olsrd_jsoninfo.so.0.0"] = {
{ Value, "accept", "127.0.0.1" },
{ Value, "port", "9090" },
{ Value, "UUIDFile", "/etc/olsrd/olsrd.uuid" },
},
["olsrd_watchdog.so.0.1"] = {
{ Value, "file", "/var/run/olsrd.watchdog" },
{ Value, "interval", "30" }
},
["olsrd_mdns.so.1.0.0"] = {
{ DynamicList, "NonOlsrIf", "lan" }
},
["olsrd_p2pd.so.0.1.0"] = {
{ DynamicList, "NonOlsrIf", "lan" },
{ Value, "P2pdTtl", "10" }
},
["olsrd_arprefresh.so.0.1"] = {},
["olsrd_dot_draw.so.0.3"] = {},
["olsrd_dyn_gw_plain.so.0.4"] = {},
["olsrd_pgraph.so.1.1"] = {},
["olsrd_tas.so.0.1"] = {}
}
-- build plugin options with dependencies
if knownPlParams[arg[1]] then
for _, option in ipairs(knownPlParams[arg[1]]) do
local otype, name, default, uci2cbi, cbi2uci = unpack(option)
local values
if type(default) == "table" then
values = default
default = default[1]
end
if otype == Flag then
local bool = p:option( Flag, name, name )
if default == "yes" or default == "no" then
bool.enabled = "yes"
bool.disabled = "no"
elseif default == "on" or default == "off" then
bool.enabled = "on"
bool.disabled = "off"
elseif default == "1" or default == "0" then
bool.enabled = "1"
bool.disabled = "0"
else
bool.enabled = "true"
bool.disabled = "false"
end
bool.optional = true
bool.default = default
bool:depends({ library = plugin })
else
local field = p:option( otype, name, name )
if values then
for _, value in ipairs(values) do
field:value( value )
end
end
if type(uci2cbi) == "function" then
function field.cfgvalue(self, section)
return uci2cbi(otype.cfgvalue(self, section))
end
end
if type(cbi2uci) == "function" then
function field.formvalue(self, section)
return cbi2uci(otype.formvalue(self, section))
end
end
field.optional = true
field.default = default
--field:depends({ library = arg[1] })
end
end
end
return mp
else
mpi = Map("olsrd", translate("OLSR - Plugins"))
local plugins = {}
mpi.uci:foreach("olsrd", "LoadPlugin",
function(section)
if section.library and not plugins[section.library] then
plugins[section.library] = true
end
end
)
-- create a loadplugin section for each found plugin
for v in fs.dir("/usr/lib") do
if v:sub(1, 6) == "olsrd_" then
if not plugins[v] then
mpi.uci:section(
"olsrd", "LoadPlugin", nil,
{ library = v, ignore = 1 }
)
end
end
end
t = mpi:section( TypedSection, "LoadPlugin", translate("Plugins") )
t.anonymous = true
t.template = "cbi/tblsection"
t.override_scheme = true
function t.extedit(self, section)
local lib = self.map:get(section, "library") or ""
return luci.dispatcher.build_url("admin", "services", "olsrd", "plugins") .. "/" .. lib
end
ign = t:option( Flag, "ignore", translate("Enabled") )
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
t:option( DummyValue, "library", translate("Library") )
return mpi
end
| apache-2.0 |
lichtl/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_0ro.lua | 14 | 1644 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: Oil lamp
-- @pos -60 -23 60 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorOffset = npc:getID();
player:messageSpecial(LAMP_OFFSET+4); -- ice lamp
npc:openDoor(7); -- lamp animation
local element = VanadielDayElement();
--printf("element: %u",element);
if (element == 0) then -- fireday
if (GetNPCByID(DoorOffset+6):getAnimation() == 8) then -- lamp fire open?
GetNPCByID(DoorOffset-3):openDoor(15); -- Open Door _0rk
end
elseif (element == 4) then -- iceday
if (GetNPCByID(DoorOffset+5):getAnimation() == 8) then -- lamp wind open?
GetNPCByID(DoorOffset-3):openDoor(15); -- Open Door _0rk
end
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.