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 |
|---|---|---|---|---|---|
RebootRevival/FFXI_Test | scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_2.lua | 28 | 3113 | -----------------------------------
-- Area: LaLoff Amphitheater
-- Name: Ark Angels 2 (Tarutaru)
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
-----------------------------------
-- Death cutscenes:
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- Hume
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvan
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompletedMission(ZILART,ARK_ANGELS)) then
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,1,1); -- winning CS (allow player to skip)
else
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,1,0); -- winning CS (allow player to skip)
end
elseif (leavecode == 4) then
player:startEvent(0x7d02, 0, 0, 0, 0, 0, instance:getEntrance(), 180); -- player lost
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);
local AAKeyitems = (player:hasKeyItem(SHARD_OF_APATHY) and player:hasKeyItem(SHARD_OF_ARROGANCE)
and player:hasKeyItem(SHARD_OF_ENVY) and player:hasKeyItem(SHARD_OF_RAGE));
if (csid == 0x7d01) then
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
player:addKeyItem(SHARD_OF_COWARDICE);
player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_COWARDICE);
if (AAKeyitems == true) then
player:completeMission(ZILART,ARK_ANGELS);
player:addMission(ZILART,THE_SEALED_SHRINE);
player:setVar("ZilartStatus",0);
end
end
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/items/serving_of_leadafry.lua | 12 | 1190 | -----------------------------------------
-- ID: 5161
-- Item: serving_of_leadafry
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Agility 5
-- Vitality 2
-----------------------------------------
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,5161);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 5);
target:addMod(MOD_VIT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 5);
target:delMod(MOD_VIT, 2);
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Windurst_Waters_[S]/npcs/Pahpe_Rauulih.lua | 3 | 1065 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Pahpe Rauulih
-- Type: Standard NPC
-- @zone 94
-- !pos -39.740 -4.499 53.223
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01ab);
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 |
RebootRevival/FFXI_Test | scripts/zones/Lower_Jeuno/npcs/Yin_Pocanakhu.lua | 3 | 1375 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Yin Pocanakhu
-- Involved in Quest: Borghertz's Hands (1st quest only)
-- @zone 245
-- !pos 35 4 -43
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BorghertzHandsFirstTime") == 2) then
player:startEvent(0x00dc);
else
player:startEvent(0x00d1);
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 == 0x00dc and option == 0 and player:delGil(1000)) then
player:startEvent(0x00dd);
player:setVar("BorghertzHandsFirstTime",0);
player:setVar("BorghertzCS",1);
end
end; | gpl-3.0 |
mzguanglin/LuCI | modules/admin-full/luasrc/model/cbi/admin_system/system.lua | 1 | 3025 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
require("luci.fs")
m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone."))
local has_rdate = false
m.uci:foreach("system", "rdate",
function()
has_rdate = true
return false
end)
s = m:section(TypedSection, "system", "")
s.anonymous = true
s.addremove = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("System")).value = system
s:option(DummyValue, "_cpu", translate("Processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("Load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("Memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("cached")),
100 * membuffers / memtotal,
tostring(translate("buffered")),
100 * memfree / memtotal,
tostring(translate("free"))
)
s:option(DummyValue, "_systime", translate("Local Time")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("Uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("Hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("Timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
local timezone = lookup_zone(value) or "GMT0"
self.map.uci:set("system", section, "timezone", timezone)
luci.fs.writefile("/etc/TZ", timezone .. "\n")
end
s:option(Value, "log_size", translate("System log buffer size"), "kiB").optional = true
s:option(Value, "log_ip", translate("External system log server")).optional = true
s:option(Value, "log_port", translate("External system log server port")).optional = true
s:option(Value, "conloglevel", translate("Log output level")).optional = true
s:option(Value, "cronloglevel", translate("Cron Log Level")).optional = true
if has_rdate then
s2 = m:section(TypedSection, "rdate", translate("Time Server (rdate)"))
s2.anonymous = true
s2.addremove = false
s2:option(DynamicList, "server", translate("Server"))
end
return m
| apache-2.0 |
RebootRevival/FFXI_Test | scripts/globals/abilities/stutter_step.lua | 1 | 7923 | -----------------------------------
-- Ability: Stutter Step
-- Applies Weakened Daze. Lowers the targets magic resistance. If successful, you will earn two Finishing Moves.
-- Obtained: Dancer Level 40
-- TP Required: 10%
-- Recast Time: 00:05
-- Duration: First Step lasts 1 minute, each following Step extends its current duration by 30 seconds.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/weaponskills");
require("scripts/globals/msg");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getAnimation() ~= 1) then
return msgBasic.REQUIRES_COMBAT,0;
else
if (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 100) then
return msgBasic.NOT_ENOUGH_TP,0;
else
return 0,0;
end
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability,action)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(100);
end;
local hit = 3;
local effect = 1;
if math.random() <= getHitRate(player,target,true,player:getMod(MOD_STEP_ACCURACY)) then
hit = 7;
local mjob = player:getMainJob();
local daze = 1;
if (mjob == 19) then
if (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_1)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_1):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_1);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30);
daze = 3;
effect = 3;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30);
daze = 2;
effect = 2;
end
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_2)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_2):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_2);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30);
daze = 3;
effect = 4;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30);
daze = 2;
effect = 3;
end
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_3)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_3):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_3);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
daze = 3;
effect = 5;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30);
daze = 2;
effect = 4;
end
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_4)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_4):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_4);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
daze = 3;
else
daze = 2;
end
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
effect = 5;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_5)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_5):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_5);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
daze = 1;
effect = 5;
else
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,60);
daze = 3;
effect = 2;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_1,1,0,60);
daze = 2;
effect = 1;
end
end;
else
if (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_1)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_1):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_1);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30);
effect = 2;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_2)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_2):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_2);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30);
effect = 3;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_3)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_3):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_3);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30);
effect = 4;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_4)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_4):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_4);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
effect = 5;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_5)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_5):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_5);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
effect = 5;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_1,1,0,60);
effect = 1;
end;
end
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_1);
player:addStatusEffect(EFFECT_FINISHING_MOVE_1+daze,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_2);
player:addStatusEffect(EFFECT_FINISHING_MOVE_2+daze,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3);
if (daze > 2) then
daze = 2;
end;
player:addStatusEffect(EFFECT_FINISHING_MOVE_3+daze,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4);
player:addStatusEffect(EFFECT_FINISHING_MOVE_5,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
else
player:addStatusEffect(EFFECT_FINISHING_MOVE_1 - 1 + daze,1,0,7200);
end;
else
ability:setMsg(158);
end
action:animation(target:getID(), getStepAnimation(player:getWeaponSkillType(SLOT_MAIN)))
action:speceffect(target:getID(), hit)
return effect
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/commands/completequest.lua | 1 | 1855 | ---------------------------------------------------------------------------------------------------
-- func: completequest <logID> <questID> <player>
-- desc: Completes the given quest for the GM or target player.
---------------------------------------------------------------------------------------------------
require("scripts/globals/quests")
cmdprops =
{
permission = 1,
parameters = "sss"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!completequest <logID> <questID> {player}");
end;
function onTrigger(player, logId, questId, target)
-- validate logId
local logName;
if (logId == nil) then
error(player, "You must provide a logID.");
return;
elseif (tonumber(logId) ~= nil) then
logId = tonumber(logId);
logId = QUEST_LOGS[logId];
end
if (logId ~= nil) then
logId = _G[string.upper(logId)];
end
if ((type(logId) == "table") and logId.quest_log ~= nil) then
logName = logId.full_name;
logId = logId.quest_log;
else
error(player, "Invalid logID.");
return;
end
-- validate questId
if (questId ~= nil) then
questId = tonumber(questId) or _G[string.upper(questId)];
end
if (questId == nil or questId < 0) then
error(player, "Invalid questID.");
return;
end
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format("Player named '%s' not found!", target));
return;
end
end
-- complete quest
targ:completeQuest( logId, questId );
player:PrintToPlayer( string.format( "Completed %s Quest with ID %u for %s", logName, questId, targ:getName() ) );
end;
| gpl-3.0 |
mzguanglin/LuCI | libs/web/luasrc/http.lua | 5 | 8064 | --[[
LuCI - HTTP-Interaction
Description:
HTTP-Header manipulator and form variable preprocessor
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 ltn12 = require "luci.ltn12"
local protocol = require "luci.http.protocol"
local util = require "luci.util"
local string = require "string"
local coroutine = require "coroutine"
local table = require "table"
local ipairs, pairs, next, type, tostring, error =
ipairs, pairs, next, type, tostring, error
--- LuCI Web Framework high-level HTTP functions.
module "luci.http"
context = util.threadlocal()
Request = util.class()
function Request.__init__(self, env, sourcein, sinkerr)
self.input = sourcein
self.error = sinkerr
-- File handler
self.filehandler = function() end
-- HTTP-Message table
self.message = {
env = env,
headers = {},
params = protocol.urldecode_params(env.QUERY_STRING or ""),
}
self.parsed_input = false
end
function Request.formvalue(self, name, noparse)
if not noparse and not self.parsed_input then
self:_parse_input()
end
if name then
return self.message.params[name]
else
return self.message.params
end
end
function Request.formvaluetable(self, prefix)
local vals = {}
prefix = prefix and prefix .. "." or "."
if not self.parsed_input then
self:_parse_input()
end
local void = self.message.params[nil]
for k, v in pairs(self.message.params) do
if k:find(prefix, 1, true) == 1 then
vals[k:sub(#prefix + 1)] = tostring(v)
end
end
return vals
end
function Request.content(self)
if not self.parsed_input then
self:_parse_input()
end
return self.message.content, self.message.content_length
end
function Request.getcookie(self, name)
local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";")
local p = ";" .. name .. "=(.-);"
local i, j, value = c:find(p)
return value and urldecode(value)
end
function Request.getenv(self, name)
if name then
return self.message.env[name]
else
return self.message.env
end
end
function Request.setfilehandler(self, callback)
self.filehandler = callback
end
function Request._parse_input(self)
protocol.parse_message_body(
self.input,
self.message,
self.filehandler
)
self.parsed_input = true
end
--- Close the HTTP-Connection.
function close()
if not context.eoh then
context.eoh = true
coroutine.yield(3)
end
if not context.closed then
context.closed = true
coroutine.yield(5)
end
end
--- Return the request content if the request was of unknown type.
-- @return HTTP request body
-- @return HTTP request body length
function content()
return context.request:content()
end
--- Get a certain HTTP input value or a table of all input values.
-- @param name Name of the GET or POST variable to fetch
-- @param noparse Don't parse POST data before getting the value
-- @return HTTP input value or table of all input value
function formvalue(name, noparse)
return context.request:formvalue(name, noparse)
end
--- Get a table of all HTTP input values with a certain prefix.
-- @param prefix Prefix
-- @return Table of all HTTP input values with given prefix
function formvaluetable(prefix)
return context.request:formvaluetable(prefix)
end
--- Get the value of a certain HTTP-Cookie.
-- @param name Cookie Name
-- @return String containing cookie data
function getcookie(name)
return context.request:getcookie(name)
end
--- Get the value of a certain HTTP environment variable
-- or the environment table itself.
-- @param name Environment variable
-- @return HTTP environment value or environment table
function getenv(name)
return context.request:getenv(name)
end
--- Set a handler function for incoming user file uploads.
-- @param callback Handler function
function setfilehandler(callback)
return context.request:setfilehandler(callback)
end
--- Send a HTTP-Header.
-- @param key Header key
-- @param value Header value
function header(key, value)
if not context.headers then
context.headers = {}
end
context.headers[key:lower()] = value
coroutine.yield(2, key, value)
end
--- Set the mime type of following content data.
-- @param mime Mimetype of following content
function prepare_content(mime)
if not context.headers or not context.headers["content-type"] then
if mime == "application/xhtml+xml" then
if not getenv("HTTP_ACCEPT") or
not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then
mime = "text/html; charset=UTF-8"
end
header("Vary", "Accept")
end
header("Content-Type", mime)
end
end
--- Get the RAW HTTP input source
-- @return HTTP LTN12 source
function source()
return context.request.input
end
--- Set the HTTP status code and status message.
-- @param code Status code
-- @param message Status message
function status(code, message)
code = code or 200
message = message or "OK"
context.status = code
coroutine.yield(1, code, message)
end
--- Send a chunk of content data to the client.
-- This function is as a valid LTN12 sink.
-- If the content chunk is nil this function will automatically invoke close.
-- @param content Content chunk
-- @param src_err Error object from source (optional)
-- @see close
function write(content, src_err)
if not content then
if src_err then
error(src_err)
else
close()
end
return true
elseif #content == 0 then
return true
else
if not context.eoh then
if not context.status then
status()
end
if not context.headers or not context.headers["content-type"] then
header("Content-Type", "text/html; charset=utf-8")
end
if not context.headers["cache-control"] then
header("Cache-Control", "no-cache")
header("Expires", "0")
end
context.eoh = true
coroutine.yield(3)
end
coroutine.yield(4, content)
return true
end
end
--- Splice data from a filedescriptor to the client.
-- @param fp File descriptor
-- @param size Bytes to splice (optional)
function splice(fd, size)
coroutine.yield(6, fd, size)
end
--- Redirects the client to a new URL and closes the connection.
-- @param url Target URL
function redirect(url)
status(302, "Found")
header("Location", url)
close()
end
--- Create a querystring out of a table of key - value pairs.
-- @param table Query string source table
-- @return Encoded HTTP query string
function build_querystring(q)
local s = { "?" }
for k, v in pairs(q) do
if #s > 1 then s[#s+1] = "&" end
s[#s+1] = urldecode(k)
s[#s+1] = "="
s[#s+1] = urldecode(v)
end
return table.concat(s, "")
end
--- Return the URL-decoded equivalent of a string.
-- @param str URL-encoded string
-- @param no_plus Don't decode + to " "
-- @return URL-decoded string
-- @see urlencode
urldecode = protocol.urldecode
--- Return the URL-encoded equivalent of a string.
-- @param str Source string
-- @return URL-encoded string
-- @see urldecode
urlencode = protocol.urlencode
--- Send the given data as JSON encoded string.
-- @param data Data to send
function write_json(x)
if x == nil then
write("null")
elseif type(x) == "table" then
local k, v
if type(next(x)) == "number" then
write("[ ")
for k, v in ipairs(x) do
write_json(v)
if next(x, k) then
write(", ")
end
end
write(" ]")
else
write("{ ")
for k, v in pairs(x) do
write("%q: " % k)
write_json(v)
if next(x, k) then
write(", ")
end
end
write(" }")
end
elseif type(x) == "number" or type(x) == "boolean" then
write(tostring(x))
elseif type(x) == "string" then
write("%q" % tostring(x))
end
end
| apache-2.0 |
sjmGithub/csi280LearningExperience | share/lua/meta/art/01_googleimage.lua | 30 | 1659 | --[[
Gets an artwork from images.google.com
$Id$
Copyright © 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Return the artwork
function fetch_art()
if vlc.item == nil then return nil end
local meta = vlc.item:metas()
-- Radio Entries
if meta["Listing Type"] == "radio"
then
title = meta["title"] .. " radio logo"
-- TV Entries
elseif meta["Listing Type"] == "tv"
then
title = meta["title"] .. " tv logo"
-- Album entries
elseif meta["artist"] and meta["album"] then
title = meta["artist"].." "..meta["album"].." cover"
elseif meta["artist"] and meta["title"] then
title = meta["artist"].." "..meta["title"].." cover"
else
return nil
end
fd = vlc.stream( "http://images.google.com/images?q="..vlc.strings.encode_uri_component( title ) )
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, arturl = string.find( page, "imgurl=([^&]*)" )
return arturl
end
| gpl-2.0 |
petoju/awesome | lib/awful/widget/common.lua | 3 | 7109 | ---------------------------------------------------------------------------
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008-2009 Julien Danjou
-- @classmod awful.widget.common
---------------------------------------------------------------------------
-- Grab environment we need
local type = type
local ipairs = ipairs
local capi = { button = button }
local wibox = require("wibox")
local gdebug = require("gears.debug")
local dpi = require("beautiful").xresources.apply_dpi
local base = require("wibox.widget.base")
--- Common utilities for awful widgets
local common = {}
--- Common method to create buttons.
-- @tparam table buttons
-- @param object
-- @treturn table
function common.create_buttons(buttons, object)
local is_formatted = buttons and buttons[1] and (
type(buttons[1]) == "button" or buttons[1]._is_capi_button) or false
if buttons then
local btns = {}
for _, src in ipairs(buttons) do
--TODO v6 Remove this legacy overhead
for _, b in ipairs(is_formatted and {src} or src) do
-- Create a proxy button object: it will receive the real
-- press and release events, and will propagate them to the
-- button object the user provided, but with the object as
-- argument.
local btn = capi.button { modifiers = b.modifiers, button = b.button }
btn:connect_signal("press", function () b:emit_signal("press", object) end)
btn:connect_signal("release", function () b:emit_signal("release", object) end)
btns[#btns + 1] = btn
end
end
return btns
end
end
local function custom_template(args)
local l = base.make_widget_from_value(args.widget_template)
-- The template system requires being able to get children elements by ids.
-- This is not optimal, but for now there is no way around it.
assert(l.get_children_by_id,"The given widget template did not result in a"..
"layout with a 'get_children_by_id' method")
return {
ib = l:get_children_by_id( "icon_role" )[1],
tb = l:get_children_by_id( "text_role" )[1],
bgb = l:get_children_by_id( "background_role" )[1],
tbm = l:get_children_by_id( "text_margin_role" )[1],
ibm = l:get_children_by_id( "icon_margin_role" )[1],
primary = l,
update_callback = l.update_callback,
create_callback = l.create_callback,
}
end
local function default_template()
return custom_template {
widget_template = {
id = 'background_role',
border_strategy = 'inner',
widget = wibox.container.background,
{
widget = wibox.layout.fixed.horizontal,
fill_space = true,
{
id = 'icon_margin_role',
widget = wibox.container.margin,
{
id = 'icon_role',
widget = wibox.widget.imagebox,
left = dpi(4),
},
},
{
id = 'text_margin_role',
widget = wibox.container.margin,
left = dpi(4),
right = dpi(4),
{
id = 'text_role',
widget = wibox.widget.textbox,
},
}
}
}
}
end
-- Find all the childrens (without the hierarchy) and set a property.
function common._set_common_property(widget, property, value)
if widget["set_"..property] then
widget["set_"..property](widget, value)
end
if widget.get_children then
for _, w in ipairs(widget:get_children()) do
common._set_common_property(w, property, value)
end
end
end
--- Common update method.
-- @param w The widget.
-- @tparam table buttons
-- @func label Function to generate label parameters from an object.
-- The function gets passed an object from `objects`, and
-- has to return `text`, `bg`, `bg_image`, `icon`.
-- @tparam table data Current data/cache, indexed by objects.
-- @tparam table objects Objects to be displayed / updated.
-- @tparam[opt={}] table args
function common.list_update(w, buttons, label, data, objects, args)
-- update the widgets, creating them if needed
w:reset()
for i, o in ipairs(objects) do
local cache = data[o]
if not cache then
cache = (args and args.widget_template) and
custom_template(args) or default_template()
cache.primary.buttons = {common.create_buttons(buttons, o)}
if cache.create_callback then
cache.create_callback(cache.primary, o, i, objects)
end
if args and args.create_callback then
args.create_callback(cache.primary, o, i, objects)
end
data[o] = cache
elseif cache.update_callback then
cache.update_callback(cache.primary, o, i, objects)
end
local text, bg, bg_image, icon, item_args = label(o, cache.tb)
item_args = item_args or {}
-- The text might be invalid, so use pcall.
if cache.tbm and (text == nil or text == "") then
cache.tbm:set_margins(0)
elseif cache.tb then
if not cache.tb:set_markup_silently(text) then
cache.tb:set_markup("<i><Invalid text></i>")
end
end
if cache.bgb then
cache.bgb:set_bg(bg)
--TODO v5 remove this if, it existed only for a removed and
-- undocumented API
if type(bg_image) ~= "function" then
cache.bgb:set_bgimage(bg_image)
else
gdebug.deprecate("If you read this, you used an undocumented API"..
" which has been replaced by the new awful.widget.common "..
"templating system, please migrate now. This feature is "..
"already staged for removal", {
deprecated_in = 4
})
end
cache.bgb.shape = item_args.shape
cache.bgb.border_width = item_args.shape_border_width
cache.bgb.border_color = item_args.shape_border_color
end
if cache.ib and icon then
cache.ib:set_image(icon)
elseif cache.ibm then
cache.ibm:set_margins(0)
end
if item_args.icon_size and cache.ib then
cache.ib.forced_height = item_args.icon_size
cache.ib.forced_width = item_args.icon_size
elseif cache.ib then
cache.ib.forced_height = nil
cache.ib.forced_width = nil
end
w:add(cache.primary)
end
end
return common
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Mhaura/npcs/Radhika.lua | 3 | 1093 | -----------------------------------
-- Area: Mhaura
-- NPC: Radhika
-- Type: Standard NPC
-- !pos 34.124 -8.999 39.629 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() >= 39) then
player:startEvent(0x00E5);
else
player:startEvent(0x00DE);
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 |
RebootRevival/FFXI_Test | scripts/globals/mobskills/auroral_drape.lua | 1 | 1081 | ---------------------------------------------
-- Auroral Drape
--
-- Description: Silence and Blind Area of Effect (10.0')
-- Type: Enfeebling
-- Utsusemi/Blink absorb: Ignores shadows
---------------------------------------------
require("scripts/globals/monstertpmoves");
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/msg");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local silenced = false;
local blinded = false;
silenced = MobStatusEffectMove(mob, target, EFFECT_SILENCE, 1, 0, 60);
blinded = MobStatusEffectMove(mob, target, EFFECT_BLINDNESS, 60, 0, 60);
skill:setMsg(msgBasic.ENFEEB_IS);
-- display silenced first, else blind
if (silenced == msgBasic.ENFEEB_IS) then
typeEffect = EFFECT_SILENCE;
elseif (blinded == msgBasic.ENFEEB_IS) then
typeEffect = EFFECT_BLINDNESS;
else
skill:setMsg(msgBasic.MISS);
end
return typeEffect;
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Arrapago_Reef/TextIDs.lua | 3 | 1225 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6386; -- Obtained: <item>
GIL_OBTAINED = 6387; -- Obtained <number> gil
KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>
FISHING_MESSAGE_OFFSET = 7047; -- You can't fish here
-- Assault
CANNOT_ENTER = 8443; -- You cannot enter at this time. Please wait a while before trying again.
AREA_FULL = 8444; -- This area is fully occupied. You were unable to enter.
MEMBER_NO_REQS = 8448; -- Not all of your party members meet the requirements for this objective. Unable to enter area.
MEMBER_TOO_FAR = 8452; -- One or more party members are too far away from the entrance. Unable to enter area.
-- Other Texts
YOU_NO_REQS = 7582; -- You do not meet the requirements to enter the battlefield
NOTHING_HAPPENS = 119; -- Nothing happens...
RESPONSE = 7327; -- There is no response...
-- Medusa
MEDUSA_ENGAGE = 8554; -- Foolish two-legs... Have you forgotten the terrible power of the gorgons you created? It is time you were reminded...
MEDUSA_DEATH = 8555; -- No... I cannot leave my sisters...
| gpl-3.0 |
geoffleyland/lua-geometry2d | src-lua/geometry2d/polyline_offset.lua | 1 | 8761 | --- @module nz.co.incremental.geometry2d.polyline_offset
-- (c) Copyright 2013-2016 Geoff Leyland.
--local math_sqrt, math_min, math_max, math_atan2, math_pi =
-- math.sqrt, math.min, math.max, math.atan2, math.pi
local math_abs, math_atan2, math_cos, math_floor, math_pi, math_sin, math_sqrt =
math.abs, math.atan2, math.cos, math.floor, math.pi, math.sin, math.sqrt
------------------------------------------------------------------------------
local function round(x)
return math_floor(x + 0.5)
end
local function sign(x)
return x>0 and 1 or x<0 and -1 or 0
end
--- Compute the normal to a line segment
local function normal(x1, y1, x2, y2)
local dx, dy = x2 - x1, y2 - y1
local di = 1.0 / math_sqrt(dx*dx + dy*dy)
return { -dy * di, dx * di }
end
--- Compute the angle between two normals
local function normal_angle(normals, i, j)
local angle = math_atan2(normals[j][2], normals[j][1]) - math_atan2(normals[i][2], normals[i][1])
while (angle < -math_pi) do angle = angle + 2.0 * math_pi end
while (angle > math_pi) do angle = angle - 2.0 * math_pi end
return angle
end
local function smooth_corner(points, normals, new_points, new_normals, d, i, j)
local corner_angle = normal_angle(normals, i, j)
if (d > 0.0 and (corner_angle < -math_pi*0.25 or corner_angle > math_pi*0.9999)) or
(d < 0.0 and (corner_angle > math_pi*0.25 or corner_angle < -math_pi*0.9999)) then
local start_angle = math_atan2(normals[i][2], normals[i][1])
local section_count = round(math_abs(corner_angle / math_pi * 8))
local angle_step = -math_abs(corner_angle / section_count) * sign(d)
for k = 1, section_count-1 do
local section_angle = start_angle + k * angle_step;
new_normals[#new_normals+1] = { math_cos(section_angle), math_sin(section_angle) }
new_points[#new_points+1] = { points[j][1], points[j][2] }
end
end
end
--- Smooth off outside corners over 45 degrees
-- It adds copies of the points on outside corner to points (so all the
-- points are coincident), but makes the normals to the sections between
-- them do the right thing.
local function smooth_corners(points, normals, d, polygon, length)
local new_normals = { normals[1] }
local new_points = { points[1] }
for i = 2, length-1 do
new_points[#new_points+1] = points[i]
smooth_corner(points, normals, new_points, new_normals, d, i-1, i)
new_normals[#new_normals+1] = normals[i]
end
if polygon then
smooth_corner(points, normals, new_points, new_normals, d, length-1, 1)
end
new_points[#new_points+1] = points[length]
return new_points, new_normals;
end
--- Work out the direction a point that is at the intersection of two
-- line segments with the given normals will move in.
local function direction(normals, i, j)
local dot = normals[i][1]*normals[j][1] + normals[i][2]*normals[j][2]
local multiplier = 1 / (1 + dot)
return { multiplier * (normals[i][1] + normals[j][1]),
multiplier * (normals[i][2] + normals[j][2]) }
end
--- Work out when a line segment will disappear if its two ends
-- are moving in the given directions.
local function disappear(offset, x1, y1, dx1, dy1, x2, y2, dx2, dy2)
local d
if x2 == x1 then
if dy1 == dy2 then return false end
d = (y2 - y1) / (dy1 - dy2)
else
if dx1 == dx2 then return false end
d = (x2 - x1) / (dx1 - dx2)
end
if offset < 0.0 then
return d < 0.0 and d >= offset
else
return d > 0.0 and d <= offset
end
end
------------------------------------------------------------------------------
--- Work out the intersection of two line segments given a point on the
-- segments and a normal to them (we do it this way because the segments might
-- have no length if they were produced by smooth_corners)
local function intersection(p1, n1, p2, n2)
local x1, y1 = p1[1], p1[2]
local dx1, dy1 = n1[2], -n1[1]
local x2, y2 = p2[1], p2[2]
local dx2, dy2 = n2[2], -n2[1]
local den = dx1*dy2 - dy1*dx2
-- if the lines are too parallel, then we don't need the intermediate point
-- at all.
if math.abs(den) < 0.1 then return end
local w = ((x2 - x1) * dy2 - (y2 - y1) * dx2) / den
return { x1 + w * dx1, y1 + w * dy1 }
end
local function offset(points, d, polygon, first, last, X, Y)
if d == 0 then
local map = {}
for i = first, last do
map[i] = i
end
return points, map
end
-- The easiest thing to do here is just take a copy of the polyline
-- into a table
local length
if (first ~= 1 or X ~= 1 or Y ~= 2) then
length = 0
local p2 = {}
for i = first, last do
length = length + 1
p2[length] = { points[i][X], points[i][Y] }
end
points = p2
else
length = last - first + 1
end
-- Number all the points, so we can return a table telling us where our
-- original points have moved to
for i = 1, length do
points[i].index = i + first - 1
end
-- Compute normals to all the line segments in the polyline
local normals = {}
for i = 1, length-1 do
normals[i] = normal(points[i][1], points[i][2], points[i+1][1], points[i+1][2])
end
-- Smooth out any corners over 45 degress
points, normals = smooth_corners(points, normals, d, polygon, length)
-- Compute the directions every intersection is going to move in
local directions = {}
if polygon then
directions[1] = direction(normals, #normals, 1, d)
else
directions[1] = normals[1]
end
for i = 2, #normals do
directions[i] = direction(normals, i-1, i, d)
end
if polygon then
directions[#points] = direction(normals, #normals, 1, d)
else
directions[#points] = normals[#normals]
end
-- run through this loop until we see no changes
while true do
-- Run through all the line segments, checking if they'll disappear
-- at this level of offset. If so, mark them to disappear and note
-- that we saw a change.
local changes, keep_any = false, false
local keep = {}
for i = 2, #directions do
if disappear(d,
points[i-1][1], points[i-1][2],
directions[i-1][1], directions[i-1][2],
points[i][1], points[i][2],
directions[i][1], directions[i][2]) then
changes = true
keep[i-1] = false
else
keep[i-1] = true
keep_any = true
end
end
-- If nothing's going to disappear, we're done.
if not changes then break end
if not keep_any then points = {} break end
local i = 1
while not keep[i] do i = i + 1 end
local new_normals, new_points, new_directions = {}, {}, {}
local function add_point(j)
new_normals[#new_normals+1] = normals[j]
new_points[#new_points+1] = points[j]
new_directions[#new_directions+1] = directions[j]
end
add_point(i)
while true do
local j = i + 1
if keep[j] then
add_point(j)
else
-- If we drop a segment (or segments) we have to replace it/them
-- with a point at the intersection of the surrounding kept segments.
while not keep[j] and j <= #keep do j = j + 1 end
if keep[j] then
local new_point = intersection(points[i], normals[i], points[j], normals[j])
if new_point then
new_points[#new_points+1] = new_point
new_normals[#new_normals+1] = normals[j]
new_directions[#new_directions+1] = direction(normals, i, j)
end
else
new_directions[#new_directions+1] = normals[i]
new_points[#new_points+1] = points[i+1]
break
end
end
i = j
end
normals = new_normals
points = new_points
directions = new_directions
end
-- Now we've got all the points we're keeping. Offsetting them is easy.
local result, map = {}, {}
for i = 1, #points do
result[first+i-1] =
{
[X] = points[i][1] + d * directions[i][1],
[Y] = points[i][2] + d * directions[i][2]
}
if points[i].index then
map[points[i].index] = first+i-1
end
end
-- This is a bit of a nasty hack. If the input is a closed polygon, then
-- make sure the output is too. This should happen anyway, but sometimes
-- it doesn't. I need to work out why.
if points[1] and result[first] and
points[1][1] == points[#points][1] and
points[1][2] == points[#points][2] and
(result[first][X] ~= result[#result][X] or
result[first][Y] ~= result[#result][Y]) then
result[#result+1] = { [X] = result[first][X], [Y] = result[first][Y] }
end
return result, map
end
------------------------------------------------------------------------------
return { offset = offset }
------------------------------------------------------------------------------
| mit |
moteus/lua-lluv | test/test-defer-error.lua | 4 | 1061 | local RUN = lunit and function()end or function ()
local res = lunit.run()
if res.errors + res.failed > 0 then
os.exit(-1)
end
return os.exit(0)
end
local lunit = require "lunit"
local TEST_CASE = assert(lunit.TEST_CASE)
local skip = lunit.skip or function() end
local uv = require "lluv.unsafe"
local ENABLE = true
local _ENV = TEST_CASE'defer_error' if ENABLE then
local it = setmetatable(_ENV or _M, {__call = function(self, describe, fn)
self["test " .. describe] = fn
end})
function setup()
sock = assert(uv.udp())
end
function teardown()
sock:close()
uv.run("once")
end
it("should raise error", function()
assert_error(function() sock:send("798897", 12, "hello") end)
uv.run()
end)
it("should call callback", function()
local flag = false
assert_pass(function()
sock:send("798897", 12, "hello", function(s, e)
flag = true
assert_equal(sock, s)
assert(e)
assert_equal("798897:12", e:ext())
end)
end)
assert_false(flag)
uv.run()
assert_true(flag)
end)
end
RUN()
| mit |
SinisterRectus/Discordia | libs/containers/abstract/GuildChannel.lua | 1 | 7455 | --[=[
@c GuildChannel x Channel
@t abc
@d Defines the base methods and properties for all Discord guild channels.
]=]
local json = require('json')
local enums = require('enums')
local class = require('class')
local Channel = require('containers/abstract/Channel')
local PermissionOverwrite = require('containers/PermissionOverwrite')
local Invite = require('containers/Invite')
local Cache = require('iterables/Cache')
local Resolver = require('client/Resolver')
local isInstance = class.isInstance
local classes = class.classes
local channelType = enums.channelType
local insert, sort = table.insert, table.sort
local min, max, floor = math.min, math.max, math.floor
local huge = math.huge
local GuildChannel, get = class('GuildChannel', Channel)
function GuildChannel:__init(data, parent)
Channel.__init(self, data, parent)
self.client._channel_map[self._id] = parent
self._permission_overwrites = Cache({}, PermissionOverwrite, self)
return self:_loadMore(data)
end
function GuildChannel:_load(data)
Channel._load(self, data)
return self:_loadMore(data)
end
function GuildChannel:_loadMore(data)
return self._permission_overwrites:_load(data.permission_overwrites, true)
end
--[=[
@m setName
@t http
@p name string
@r boolean
@d Sets the channel's name. This must be between 2 and 100 characters in length.
]=]
function GuildChannel:setName(name)
return self:_modify({name = name or json.null})
end
--[=[
@m setCategory
@t http
@p id Channel-ID-Resolvable
@r boolean
@d Sets the channel's parent category.
]=]
function GuildChannel:setCategory(id)
id = Resolver.channelId(id)
return self:_modify({parent_id = id or json.null})
end
local function sorter(a, b)
if a.position == b.position then
return tonumber(a.id) < tonumber(b.id)
else
return a.position < b.position
end
end
local function getSortedChannels(self)
local channels
local t = self._type
if t == channelType.text or t == channelType.news then
channels = self._parent._text_channels
elseif t == channelType.voice then
channels = self._parent._voice_channels
elseif t == channelType.category then
channels = self._parent._categories
end
local ret = {}
for channel in channels:iter() do
insert(ret, {id = channel._id, position = channel._position})
end
sort(ret, sorter)
return ret
end
local function setSortedChannels(self, channels)
local data, err = self.client._api:modifyGuildChannelPositions(self._parent._id, channels)
if data then
return true
else
return false, err
end
end
--[=[
@m moveUp
@t http
@p n number
@r boolean
@d Moves a channel up its list. The parameter `n` indicates how many spaces the
channel should be moved, clamped to the highest position, with a default of 1 if
it is omitted. This will also normalize the positions of all channels.
]=]
function GuildChannel:moveUp(n)
n = tonumber(n) or 1
if n < 0 then
return self:moveDown(-n)
end
local channels = getSortedChannels(self)
local new = huge
for i = #channels - 1, 0, -1 do
local v = channels[i + 1]
if v.id == self._id then
new = max(0, i - floor(n))
v.position = new
elseif i >= new then
v.position = i + 1
else
v.position = i
end
end
return setSortedChannels(self, channels)
end
--[=[
@m moveDown
@t http
@p n number
@r boolean
@d Moves a channel down its list. The parameter `n` indicates how many spaces the
channel should be moved, clamped to the lowest position, with a default of 1 if
it is omitted. This will also normalize the positions of all channels.
]=]
function GuildChannel:moveDown(n)
n = tonumber(n) or 1
if n < 0 then
return self:moveUp(-n)
end
local channels = getSortedChannels(self)
local new = -huge
for i = 0, #channels - 1 do
local v = channels[i + 1]
if v.id == self._id then
new = min(i + floor(n), #channels - 1)
v.position = new
elseif i <= new then
v.position = i - 1
else
v.position = i
end
end
return setSortedChannels(self, channels)
end
--[=[
@m createInvite
@t http
@op payload table
@r Invite
@d Creates an invite to the channel. Optional payload fields are: max_age: number
time in seconds until expiration, default = 86400 (24 hours), max_uses: number
total number of uses allowed, default = 0 (unlimited), temporary: boolean whether
the invite grants temporary membership, default = false, unique: boolean whether
a unique code should be guaranteed, default = false
]=]
function GuildChannel:createInvite(payload)
local data, err = self.client._api:createChannelInvite(self._id, payload)
if data then
return Invite(data, self.client)
else
return nil, err
end
end
--[=[
@m getInvites
@t http
@r Cache
@d Returns a newly constructed cache of all invite objects for the channel. The
cache and its objects are not automatically updated via gateway events. You must
call this method again to get the updated objects.
]=]
function GuildChannel:getInvites()
local data, err = self.client._api:getChannelInvites(self._id)
if data then
return Cache(data, Invite, self.client)
else
return nil, err
end
end
--[=[
@m getPermissionOverwriteFor
@t mem
@p obj Role/Member
@r PermissionOverwrite
@d Returns a permission overwrite object corresponding to the provided member or
role object. If a cached overwrite is not found, an empty overwrite with
zero-permissions is returned instead. Therefore, this can be used to create a
new overwrite when one does not exist. Note that the member or role must exist
in the same guild as the channel does.
]=]
function GuildChannel:getPermissionOverwriteFor(obj)
local id, type
if isInstance(obj, classes.Role) and self._parent == obj._parent then
id, type = obj._id, 'role'
elseif isInstance(obj, classes.Member) and self._parent == obj._parent then
id, type = obj._user._id, 'member'
else
return nil, 'Invalid Role or Member: ' .. tostring(obj)
end
local overwrites = self._permission_overwrites
return overwrites:get(id) or overwrites:_insert(setmetatable({
id = id, type = type, allow = 0, deny = 0
}, {__jsontype = 'object'}))
end
--[=[
@m delete
@t http
@r boolean
@d Permanently deletes the channel. This cannot be undone!
]=]
function GuildChannel:delete()
return self:_delete()
end
--[=[@p permissionOverwrites Cache An iterable cache of all overwrites that exist in this channel. To access an
overwrite that may exist, but is not cached, use `GuildChannel:getPermissionOverwriteFor`.]=]
function get.permissionOverwrites(self)
return self._permission_overwrites
end
--[=[@p name string The name of the channel. This should be between 2 and 100 characters in length.]=]
function get.name(self)
return self._name
end
--[=[@p position number The position of the channel, where 0 is the highest.]=]
function get.position(self)
return self._position
end
--[=[@p guild Guild The guild in which this channel exists.]=]
function get.guild(self)
return self._parent
end
--[=[@p category GuildCategoryChannel/nil The parent channel category that may contain this channel.]=]
function get.category(self)
return self._parent._categories:get(self._parent_id)
end
--[=[@p private boolean Whether the "everyone" role has permission to view this
channel. In the Discord channel, private text channels are indicated with a lock
icon and private voice channels are not visible.]=]
function get.private(self)
local overwrite = self._permission_overwrites:get(self._parent._id)
return overwrite and overwrite:getDeniedPermissions():has('readMessages')
end
return GuildChannel
| mit |
babymannen/theforgottenserver-7.4 | server/data/npc/lib/npcsystem/modules.lua | 1 | 39265 | -- Advanced NPC System by Jiddo
if Modules == nil then
-- default words for greeting and ungreeting the npc. Should be a table containing all such words.
FOCUS_GREETWORDS = {"hi", "hello"}
FOCUS_FAREWELLWORDS = {"bye", "farewell"}
-- The words for requesting trade window.
SHOP_TRADEREQUEST = {"trade"}
-- The word for accepting/declining an offer. CAN ONLY CONTAIN ONE FIELD! Should be a table with a single string value.
SHOP_YESWORD = {"yes"}
SHOP_NOWORD = {"no"}
-- Pattern used to get the amount of an item a player wants to buy/sell.
PATTERN_COUNT = "%d+"
-- Constants used to separate buying from selling.
SHOPMODULE_SELL_ITEM = 1
SHOPMODULE_BUY_ITEM = 2
SHOPMODULE_BUY_ITEM_CONTAINER = 3
-- Constants used for shop mode. Notice: addBuyableItemContainer is working on all modes
SHOPMODULE_MODE_TALK = 1 -- Old system used before client version 8.2: sell/buy item name
SHOPMODULE_MODE_TRADE = 2 -- Trade window system introduced in client version 8.2
SHOPMODULE_MODE_BOTH = 3 -- Both working at one time
-- Used shop mode
SHOPMODULE_MODE = SHOPMODULE_MODE_TALK
Modules = {
parseableModules = {}
}
StdModule = {}
-- These callback function must be called with parameters.npcHandler = npcHandler in the parameters table or they will not work correctly.
-- Notice: The members of StdModule have not yet been tested. If you find any bugs, please report them to me.
-- Usage:
-- keywordHandler:addKeyword({"offer"}, StdModule.say, {npcHandler = npcHandler, text = "I sell many powerful melee weapons."})
function StdModule.say(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if npcHandler == nil then
error("StdModule.say called without any npcHandler instance.")
end
local onlyFocus = (parameters.onlyFocus == nil or parameters.onlyFocus == true)
if not npcHandler:isFocused(cid) and onlyFocus then
return false
end
local parseInfo = {
[TAG_PLAYERNAME] = Player(cid):getName(),
[TAG_TIME] = getFormattedWorldTime()
}
npcHandler:say(npcHandler:parseMessage(parameters.text or parameters.message, parseInfo), cid, parameters.publicize and true)
if parameters.reset then
npcHandler:resetNpc(cid)
elseif parameters.moveup ~= nil then
npcHandler.keywordHandler:moveUp(cid, parameters.moveup)
end
return true
end
--Usage:
-- local node1 = keywordHandler:addKeyword({"promot"}, StdModule.say, {npcHandler = npcHandler, text = "I can promote you for 20000 gold coins. Do you want me to promote you?"})
-- node1:addChildKeyword({"yes"}, StdModule.promotePlayer, {npcHandler = npcHandler, cost = 20000, level = 20}, text = "Congratulations! You are now promoted.")
-- node1:addChildKeyword({"no"}, StdModule.say, {npcHandler = npcHandler, text = "Allright then. Come back when you are ready."}, reset = true)
function StdModule.promotePlayer(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if npcHandler == nil then
error("StdModule.promotePlayer called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
local promotion = player:getVocation():getPromotion()
if player:getStorageValue(STORAGEVALUE_PROMOTION) == 1 then
npcHandler:say("You are already promoted!", cid)
elseif player:getLevel() < parameters.level then
npcHandler:say("I am sorry, but I can only promote you once you have reached level " .. parameters.level .. ".", cid)
elseif not player:removeMoney(parameters.cost) then
npcHandler:say("You do not have enough money!", cid)
else
npcHandler:say(parameters.text, cid)
player:setVocation(promotion)
player:setStorageValue(STORAGEVALUE_PROMOTION, 1)
end
else
npcHandler:say("You need a premium account in order to get promoted.", cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.learnSpell(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if npcHandler == nil then
error("StdModule.learnSpell called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:hasLearnedSpell(parameters.spellName) then
npcHandler:say("You already know this spell.", cid)
elseif not player:canLearnSpell(parameters.spellName) then
npcHandler:say("You cannot learn this spell.", cid)
elseif not player:removeMoney(parameters.price) then
npcHandler:say("You do not have enough money, this spell costs " .. parameters.price .. " gold.", cid)
else
npcHandler:say("You have learned " .. parameters.spellName .. ".", cid)
player:learnSpell(parameters.spellName)
end
else
npcHandler:say("You need a premium account in order to buy " .. parameters.spellName .. ".", cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.bless(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if npcHandler == nil then
error("StdModule.bless called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) or getWorldType() == WORLD_TYPE_PVP_ENFORCED then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:hasBlessing(parameters.bless) then
npcHandler:say("Gods have already blessed you with this blessing!", cid)
elseif not player:removeMoney(parameters.cost) then
npcHandler:say("You don't have enough money for blessing.", cid)
else
player:addBlessing(parameters.bless)
npcHandler:say("You have been blessed by one of the five gods!", cid)
end
else
npcHandler:say("You need a premium account in order to be blessed.", cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.travel(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if npcHandler == nil then
error("StdModule.travel called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:isPzLocked() then
npcHandler:say("First get rid of those blood stains! You are not going to ruin my vehicle!", cid)
elseif parameters.level and player:getLevel() < parameters.level then
npcHandler:say("You must reach level " .. parameters.level .. " before I can let you go there.", cid)
elseif not player:removeMoney(parameters.cost) then
npcHandler:say("You don't have enough money.", cid)
else
npcHandler:say(parameters.msg or "Set the sails!", cid)
npcHandler:releaseFocus(cid)
local destination = Position(parameters.destination)
local position = player:getPosition()
player:teleportTo(destination)
position:sendMagicEffect(CONST_ME_TELEPORT)
destination:sendMagicEffect(CONST_ME_TELEPORT)
end
else
npcHandler:say("I'm sorry, but you need a premium account in order to travel onboard our ships.", cid)
end
npcHandler:resetNpc(cid)
return true
end
FocusModule = {
npcHandler = nil
}
-- Creates a new instance of FocusModule without an associated NpcHandler.
function FocusModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
-- Inits the module and associates handler to it.
function FocusModule:init(handler)
self.npcHandler = handler
for i, word in pairs(FOCUS_GREETWORDS) do
local obj = {}
obj[#obj + 1] = word
obj.callback = FOCUS_GREETWORDS.callback or FocusModule.messageMatcher
handler.keywordHandler:addKeyword(obj, FocusModule.onGreet, {module = self})
end
for i, word in pairs(FOCUS_FAREWELLWORDS) do
local obj = {}
obj[#obj + 1] = word
obj.callback = FOCUS_FAREWELLWORDS.callback or FocusModule.messageMatcher
handler.keywordHandler:addKeyword(obj, FocusModule.onFarewell, {module = self})
end
return true
end
-- Greeting callback function.
function FocusModule.onGreet(cid, message, keywords, parameters)
parameters.module.npcHandler:onGreet(cid)
return true
end
-- UnGreeting callback function.
function FocusModule.onFarewell(cid, message, keywords, parameters)
if parameters.module.npcHandler:isFocused(cid) then
parameters.module.npcHandler:onFarewell(cid)
return true
else
return false
end
end
-- Custom message matching callback function for greeting messages.
function FocusModule.messageMatcher(keywords, message)
for i, word in pairs(keywords) do
if type(word) == "string" then
if string.find(message, word) and not string.find(message, "[%w+]" .. word) and not string.find(message, word .. "[%w+]") then
return true
end
end
end
return false
end
KeywordModule = {
npcHandler = nil
}
-- Add it to the parseable module list.
Modules.parseableModules["module_keywords"] = KeywordModule
function KeywordModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
function KeywordModule:init(handler)
self.npcHandler = handler
return true
end
-- Parses all known parameters.
function KeywordModule:parseParameters()
local ret = NpcSystem.getParameter("keywords")
if ret ~= nil then
self:parseKeywords(ret)
end
end
function KeywordModule:parseKeywords(data)
local n = 1
for keys in string.gmatch(data, "[^;]+") do
local i = 1
local keywords = {}
for temp in string.gmatch(keys, "[^,]+") do
keywords[#keywords + 1] = temp
i = i + 1
end
if i ~= 1 then
local reply = NpcSystem.getParameter("keyword_reply" .. n)
if reply ~= nil then
self:addKeyword(keywords, reply)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter '" .. "keyword_reply" .. n .. "' missing. Skipping...")
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "No keywords found for keyword set #" .. n .. ". Skipping...")
end
n = n + 1
end
end
function KeywordModule:addKeyword(keywords, reply)
self.npcHandler.keywordHandler:addKeyword(keywords, StdModule.say, {npcHandler = self.npcHandler, onlyFocus = true, text = reply, reset = true})
end
TravelModule = {
npcHandler = nil,
destinations = nil,
yesNode = nil,
noNode = nil,
}
-- Add it to the parseable module list.
Modules.parseableModules["module_travel"] = TravelModule
function TravelModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
function TravelModule:init(handler)
self.npcHandler = handler
self.yesNode = KeywordNode:new(SHOP_YESWORD, TravelModule.onConfirm, {module = self})
self.noNode = KeywordNode:new(SHOP_NOWORD, TravelModule.onDecline, {module = self})
self.destinations = {}
return true
end
-- Parses all known parameters.
function TravelModule:parseParameters()
local ret = NpcSystem.getParameter("travel_destinations")
if ret ~= nil then
self:parseDestinations(ret)
self.npcHandler.keywordHandler:addKeyword({"destination"}, TravelModule.listDestinations, {module = self})
self.npcHandler.keywordHandler:addKeyword({"where"}, TravelModule.listDestinations, {module = self})
self.npcHandler.keywordHandler:addKeyword({"travel"}, TravelModule.listDestinations, {module = self})
end
end
function TravelModule:parseDestinations(data)
for destination in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local x = nil
local y = nil
local z = nil
local cost = nil
local premium = false
for temp in string.gmatch(destination, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
x = tonumber(temp)
elseif i == 3 then
y = tonumber(temp)
elseif i == 4 then
z = tonumber(temp)
elseif i == 5 then
cost = tonumber(temp)
elseif i == 6 then
premium = temp == "true"
else
print("[Warning : " .. getCreatureName(getNpcCid()) .. "] NpcSystem:", "Unknown parameter found in travel destination parameter.", temp, destination)
end
i = i + 1
end
if name ~= nil and x ~= nil and y ~= nil and z ~= nil and cost ~= nil then
self:addDestination(name, {x=x, y=y, z=z}, cost, premium)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for travel destination:", name, x, y, z, cost, premium)
end
end
end
function TravelModule:addDestination(name, position, price, premium)
self.destinations[#self.destinations + 1] = name
local parameters = {
cost = price,
destination = position,
premium = premium,
module = self
}
local keywords = {}
keywords[#keywords + 1] = name
local keywords2 = {}
keywords2[#keywords2 + 1] = "bring me to " .. name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, TravelModule.travel, parameters)
self.npcHandler.keywordHandler:addKeyword(keywords2, TravelModule.bringMeTo, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
if npcs_loaded_travel[getNpcCid()] == nil then
npcs_loaded_travel[getNpcCid()] = getNpcCid()
self.npcHandler.keywordHandler:addKeyword({'yes'}, TravelModule.onConfirm, {module = self})
self.npcHandler.keywordHandler:addKeyword({'no'}, TravelModule.onDecline, {module = self})
end
end
function TravelModule.travel(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
local npcHandler = module.npcHandler
shop_destination[cid] = parameters.destination
shop_cost[cid] = parameters.cost
shop_premium[cid] = parameters.premium
shop_npcuid[cid] = getNpcCid()
local cost = parameters.cost
local destination = parameters.destination
local premium = parameters.premium
module.npcHandler:say("Do you want to travel to " .. keywords[1] .. " for " .. cost .. " gold coins?", cid)
return true
end
function TravelModule.onConfirm(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
if shop_npcuid[cid] ~= Npc().uid then
return false
end
local npcHandler = module.npcHandler
local cost = shop_cost[cid]
local destination = Position(shop_destination[cid])
local player = Player(cid)
if player:isPremium() or not shop_premium[cid] then
if not player:removeMoney(cost) then
npcHandler:say("You do not have enough money!", cid)
elseif player:isPzLocked(cid) then
npcHandler:say("Get out of there with this blood.", cid)
else
npcHandler:say("It was a pleasure doing business with you.", cid)
npcHandler:releaseFocus(cid)
local position = player:getPosition()
player:teleportTo(destination)
position:sendMagicEffect(CONST_ME_TELEPORT)
destination:sendMagicEffect(CONST_ME_TELEPORT)
end
else
npcHandler:say("I can only allow premium players to travel there.", cid)
end
npcHandler:resetNpc(cid)
return true
end
-- onDecline keyword callback function. Generally called when the player sais "no" after wanting to buy an item.
function TravelModule.onDecline(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then
return false
end
local parentParameters = node:getParent():getParameters()
local parseInfo = { [TAG_PLAYERNAME] = Player(cid):getName() }
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_DECLINE), parseInfo)
module.npcHandler:say(msg, cid)
module.npcHandler:resetNpc(cid)
return true
end
function TravelModule.bringMeTo(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
local cost = parameters.cost
local destination = Position(parameters.destination)
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:removeMoney(cost) then
local position = player:getPosition()
player:teleportTo(destination)
position:sendMagicEffect(CONST_ME_TELEPORT)
destination:sendMagicEffect(CONST_ME_TELEPORT)
end
end
return true
end
function TravelModule.listDestinations(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
local msg = "I can bring you to "
--local i = 1
local maxn = #module.destinations
for i, destination in pairs(module.destinations) do
msg = msg .. destination
if i == maxn - 1 then
msg = msg .. " and "
elseif i == maxn then
msg = msg .. "."
else
msg = msg .. ", "
end
i = i + 1
end
module.npcHandler:say(msg, cid)
module.npcHandler:resetNpc(cid)
return true
end
ShopModule = {
npcHandler = nil,
yesNode = nil,
noNode = nil,
noText = "",
maxCount = 100,
amount = 0
}
-- Add it to the parseable module list.
Modules.parseableModules["module_shop"] = ShopModule
-- Creates a new instance of ShopModule
function ShopModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
-- Parses all known parameters.
function ShopModule:parseParameters()
local ret = NpcSystem.getParameter("shop_buyable")
if ret ~= nil then
self:parseBuyable(ret)
end
local ret = NpcSystem.getParameter("shop_sellable")
if ret ~= nil then
self:parseSellable(ret)
end
local ret = NpcSystem.getParameter("shop_buyable_containers")
if ret ~= nil then
self:parseBuyableContainers(ret)
end
end
-- Parse a string contaning a set of buyable items.
function ShopModule:parseBuyable(data)
for item in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local itemid = nil
local cost = nil
local subType = nil
local realName = nil
for temp in string.gmatch(item, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
itemid = tonumber(temp)
elseif i == 3 then
cost = tonumber(temp)
elseif i == 4 then
subType = tonumber(temp)
elseif i == 5 then
realName = temp
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in buyable items parameter.", temp, item)
end
i = i + 1
end
local it = ItemType(itemid)
if subType == nil and it:getCharges() ~= 0 then
subType = it:getCharges()
end
if SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE then
if itemid ~= nil and cost ~= nil then
if subType == nil and it:isFluidContainer() then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item)
else
self:addBuyableItem(nil, itemid, cost, subType, realName)
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", itemid, cost)
end
else
if name ~= nil and itemid ~= nil and cost ~= nil then
if subType == nil and it:isFluidContainer() then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item)
else
local names = {}
names[#names + 1] = name
self:addBuyableItem(names, itemid, cost, subType, realName)
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, itemid, cost)
end
end
end
end
-- Parse a string contaning a set of sellable items.
function ShopModule:parseSellable(data)
for item in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local itemid = nil
local cost = nil
local realName = nil
local subType = nil
for temp in string.gmatch(item, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
itemid = tonumber(temp)
elseif i == 3 then
cost = tonumber(temp)
elseif i == 4 then
realName = temp
elseif i == 5 then
subType = tonumber(temp)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in sellable items parameter.", temp, item)
end
i = i + 1
end
if SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE then
if itemid ~= nil and cost ~= nil then
self:addSellableItem(nil, itemid, cost, realName, subType)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", itemid, cost)
end
else
if name ~= nil and itemid ~= nil and cost ~= nil then
local names = {}
names[#names + 1] = name
self:addSellableItem(names, itemid, cost, realName, subType)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, itemid, cost)
end
end
end
end
-- Parse a string contaning a set of buyable items.
function ShopModule:parseBuyableContainers(data)
for item in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local container = nil
local itemid = nil
local cost = nil
local subType = nil
local realName = nil
for temp in string.gmatch(item, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
itemid = tonumber(temp)
elseif i == 3 then
itemid = tonumber(temp)
elseif i == 4 then
cost = tonumber(temp)
elseif i == 5 then
subType = tonumber(temp)
elseif i == 6 then
realName = temp
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in buyable items parameter.", temp, item)
end
i = i + 1
end
if name ~= nil and container ~= nil and itemid ~= nil and cost ~= nil then
if subType == nil and ItemType(itemid):isFluidContainer() then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item)
else
local names = {}
names[#names + 1] = name
self:addBuyableItemContainer(names, container, itemid, cost, subType, realName)
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, container, itemid, cost)
end
end
end
-- Initializes the module and associates handler to it.
function ShopModule:init(handler)
self.npcHandler = handler
self.yesNode = KeywordNode:new(SHOP_YESWORD, ShopModule.onConfirm, {module = self})
self.noNode = KeywordNode:new(SHOP_NOWORD, ShopModule.onDecline, {module = self})
self.noText = handler:getMessage(MESSAGE_DECLINE)
if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then
for i, word in pairs(SHOP_TRADEREQUEST) do
local obj = {}
obj[#obj + 1] = word
obj.callback = SHOP_TRADEREQUEST.callback or ShopModule.messageMatcher
handler.keywordHandler:addKeyword(obj, ShopModule.requestTrade, {module = self})
end
end
return true
end
-- Custom message matching callback function for requesting trade messages.
function ShopModule.messageMatcher(keywords, message)
for i, word in pairs(keywords) do
if type(word) == "string" then
if string.find(message, word) and not string.find(message, "[%w+]" .. word) and not string.find(message, word .. "[%w+]") then
return true
end
end
end
return false
end
-- Resets the module-specific variables.
function ShopModule:reset()
self.amount = 0
end
-- Function used to match a number value from a string.
function ShopModule:getCount(message)
local ret = 1
local b, e = string.find(message, PATTERN_COUNT)
if b ~= nil and e ~= nil then
ret = tonumber(string.sub(message, b, e))
end
if ret <= 0 then
ret = 1
elseif ret > self.maxCount then
ret = self.maxCount
end
return ret
end
-- Adds a new buyable item.
-- names = A table containing one or more strings of alternative names to this item. Used only for old buy/sell system.
-- itemid = The itemid of the buyable item
-- cost = The price of one single item
-- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 1.
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemName will be used)
function ShopModule:addBuyableItem(names, itemid, cost, itemSubType, realName)
if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then
if itemSubType == nil then
itemSubType = 1
end
local shopItem = self:getShopItem(itemid, itemSubType)
if shopItem == nil then
self.npcHandler.shopItems[#self.npcHandler.shopItems + 1] = {id = itemid, buy = cost, sell = -1, subType = itemSubType, name = realName or ItemType(itemid):getName()}
else
shopItem.buy = cost
end
end
if names ~= nil and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE then
for i, name in pairs(names) do
local parameters = {
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_BUY_ITEM,
module = self,
realName = realName or ItemType(itemid):getName(),
subType = itemSubType or 1
}
keywords = {}
keywords[#keywords + 1] = name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
if npcs_loaded_shop[getNpcCid()] == nil then
npcs_loaded_shop[getNpcCid()] = getNpcCid()
self.npcHandler.keywordHandler:addKeyword({'yes'}, ShopModule.onConfirm, {module = self})
self.npcHandler.keywordHandler:addKeyword({'no'}, ShopModule.onDecline, {module = self})
end
end
function ShopModule:getShopItem(itemId, itemSubType)
if ItemType(itemId):isFluidContainer() then
for i = 1, #self.npcHandler.shopItems do
local shopItem = self.npcHandler.shopItems[i]
if shopItem.id == itemId and shopItem.subType == itemSubType then
return shopItem
end
end
else
for i = 1, #self.npcHandler.shopItems do
local shopItem = self.npcHandler.shopItems[i]
if shopItem.id == itemId then
return shopItem
end
end
end
return nil
end
-- Adds a new buyable container of items.
-- names = A table containing one or more strings of alternative names to this item.
-- container = Backpack, bag or any other itemid of container where bought items will be stored
-- itemid = The itemid of the buyable item
-- cost = The price of one single item
-- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 1.
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemName will be used)
function ShopModule:addBuyableItemContainer(names, container, itemid, cost, subType, realName)
if names ~= nil then
for i, name in pairs(names) do
local parameters = {
container = container,
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_BUY_ITEM_CONTAINER,
module = self,
realName = realName or ItemType(itemid):getName(),
subType = subType or 1
}
keywords = {}
keywords[#keywords + 1] = name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
end
-- Adds a new sellable item.
-- names = A table containing one or more strings of alternative names to this item. Used only by old buy/sell system.
-- itemid = The itemid of the sellable item
-- cost = The price of one single item
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemName will be used)
function ShopModule:addSellableItem(names, itemid, cost, realName, itemSubType)
if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then
if itemSubType == nil then
itemSubType = 0
end
local shopItem = self:getShopItem(itemid, itemSubType)
if shopItem == nil then
self.npcHandler.shopItems[#self.npcHandler.shopItems + 1] = {id = itemid, buy = -1, sell = cost, subType = itemSubType, name = realName or getItemName(itemid)}
else
shopItem.sell = cost
end
end
if names ~= nil and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE then
for i, name in pairs(names) do
local parameters = {
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_SELL_ITEM,
module = self,
realName = realName or getItemName(itemid)
}
keywords = {}
keywords[#keywords + 1] = "sell"
keywords[#keywords + 1] = name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
end
-- onModuleReset callback function. Calls ShopModule:reset()
function ShopModule:callbackOnModuleReset()
self:reset()
return true
end
-- Callback onBuy() function. If you wish, you can change certain Npc to use your onBuy().
function ShopModule:callbackOnBuy(cid, itemid, subType, amount, ignoreCap, inBackpacks)
local shopItem = self:getShopItem(itemid, subType)
if shopItem == nil then
error("[ShopModule.onBuy] shopItem == nil")
return false
end
if shopItem.buy == -1 then
error("[ShopModule.onSell] attempt to buy a non-buyable item")
return false
end
local backpack = 1988
local totalCost = amount * shopItem.buy
if inBackpacks then
totalCost = isItemStackable(itemid) == TRUE and totalCost + 20 or totalCost + (math.max(1, math.floor(amount / getContainerCapById(backpack))) * 20)
end
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = amount,
[TAG_TOTALCOST] = totalCost,
[TAG_ITEMNAME] = shopItem.name
}
if getPlayerMoney(cid) < totalCost then
local msg = self.npcHandler:getMessage(MESSAGE_NEEDMONEY)
msg = self.npcHandler:parseMessage(msg, parseInfo)
doPlayerSendCancel(cid, msg)
return false
end
local subType = shopItem.subType or 1
local a, b = doNpcSellItem(cid, itemid, amount, subType, ignoreCap, inBackpacks, backpack)
if a < amount then
local msgId = MESSAGE_NEEDMORESPACE
if a == 0 then
msgId = MESSAGE_NEEDSPACE
end
local msg = self.npcHandler:getMessage(msgId)
parseInfo[TAG_ITEMCOUNT] = a
msg = self.npcHandler:parseMessage(msg, parseInfo)
doPlayerSendCancel(cid, msg)
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
if a > 0 then
doPlayerRemoveMoney(cid, ((a * shopItem.buy) + (b * 20)))
return true
end
return false
else
local msg = self.npcHandler:getMessage(MESSAGE_BOUGHT)
msg = self.npcHandler:parseMessage(msg, parseInfo)
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, msg)
doPlayerRemoveMoney(cid, totalCost)
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
return true
end
end
-- Callback onSell() function. If you wish, you can change certain Npc to use your onSell().
function ShopModule:callbackOnSell(cid, itemid, subType, amount, ignoreEquipped, _)
local shopItem = self:getShopItem(itemid, subType)
if shopItem == nil then
error("[ShopModule.onSell] items[itemid] == nil")
return false
end
if shopItem.sell == -1 then
error("[ShopModule.onSell] attempt to sell a non-sellable item")
return false
end
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = amount,
[TAG_TOTALCOST] = amount * shopItem.sell,
[TAG_ITEMNAME] = shopItem.name
}
if not isItemFluidContainer(itemid) then
subType = -1
end
if doPlayerRemoveItem(cid, itemid, amount, subType, ignoreEquipped) then
local msg = self.npcHandler:getMessage(MESSAGE_SOLD)
msg = self.npcHandler:parseMessage(msg, parseInfo)
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, msg)
doPlayerAddMoney(cid, amount * shopItem.sell)
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
return true
else
local msg = self.npcHandler:getMessage(MESSAGE_NEEDITEM)
msg = self.npcHandler:parseMessage(msg, parseInfo)
doPlayerSendCancel(cid, msg)
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
return false
end
end
-- Callback for requesting a trade window with the NPC.
function ShopModule.requestTrade(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
if not module.npcHandler:onTradeRequest(cid) then
return false
end
local itemWindow = {}
for i = 1, #module.npcHandler.shopItems do
itemWindow[#itemWindow + 1] = module.npcHandler.shopItems[i]
end
if itemWindow[1] == nil then
local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) }
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_NOSHOP), parseInfo)
module.npcHandler:say(msg, cid)
return true
end
local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) }
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_SENDTRADE), parseInfo)
module.npcHandler:say(msg, cid)
return true
end
-- onConfirm keyword callback function. Sells/buys the actual item.
function ShopModule.onConfirm(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then
return false
end
shop_npcuid[cid] = 0
local parentParameters = node:getParent():getParameters()
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = shop_amount[cid],
[TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid],
[TAG_ITEMNAME] = shop_rlname[cid]
}
if shop_eventtype[cid] == SHOPMODULE_SELL_ITEM then
local ret = doPlayerSellItem(cid, shop_itemid[cid], shop_amount[cid], shop_cost[cid] * shop_amount[cid])
if ret == true then
local msg = module.npcHandler:getMessage(MESSAGE_ONSELL)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
else
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGITEM)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM then
local cost = shop_cost[cid] * shop_amount[cid]
if getPlayerMoney(cid) < cost then
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
return false
end
local a, b = doNpcSellItem(cid, shop_itemid[cid], shop_amount[cid], shop_subtype[cid], false, false, 1988)
if a < shop_amount[cid] then
local msgId = MESSAGE_NEEDMORESPACE
if a == 0 then
msgId = MESSAGE_NEEDSPACE
end
local msg = module.npcHandler:getMessage(msgId)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
if a > 0 then
doPlayerRemoveMoney(cid, a * shop_cost[cid])
if shop_itemid[cid] == ITEM_PARCEL then
doNpcSellItem(cid, ITEM_LABEL, shop_amount[cid], shop_subtype[cid], true, false, 1988)
end
return true
end
return false
else
local msg = module.npcHandler:getMessage(MESSAGE_ONBUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
doPlayerRemoveMoney(cid, cost)
if shop_itemid[cid] == ITEM_PARCEL then
doNpcSellItem(cid, ITEM_LABEL, shop_amount[cid], shop_subtype[cid], true, false, 1988)
end
return true
end
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM_CONTAINER then
local ret = doPlayerBuyItemContainer(cid, shop_container[cid], shop_itemid[cid], shop_amount[cid], shop_cost[cid] * shop_amount[cid], shop_subtype[cid])
if ret == true then
local msg = module.npcHandler:getMessage(MESSAGE_ONBUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
else
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
end
module.npcHandler:resetNpc(cid)
return true
end
-- onDecline keyword callback function. Generally called when the player sais "no" after wanting to buy an item.
function ShopModule.onDecline(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then
return false
end
shop_npcuid[cid] = 0
local parentParameters = node:getParent():getParameters()
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = shop_amount[cid],
[TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid],
[TAG_ITEMNAME] = shop_rlname[cid]
}
local msg = module.npcHandler:parseMessage(module.noText, parseInfo)
module.npcHandler:say(msg, cid)
module.npcHandler:resetNpc(cid)
return true
end
-- tradeItem callback function. Makes the npc say the message defined by MESSAGE_BUY or MESSAGE_SELL
function ShopModule.tradeItem(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
if not module.npcHandler:onTradeRequest(cid) then
return true
end
local count = module:getCount(message)
module.amount = count
shop_amount[cid] = module.amount
shop_cost[cid] = parameters.cost
shop_rlname[cid] = count > 1 and parameters.realName .. ItemType(itemid):getPluralName() or parameters.realName
shop_itemid[cid] = parameters.itemid
shop_container[cid] = parameters.container
shop_npcuid[cid] = getNpcCid()
shop_eventtype[cid] = parameters.eventType
shop_subtype[cid] = parameters.subType
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = shop_amount[cid],
[TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid],
[TAG_ITEMNAME] = shop_rlname[cid]
}
if shop_eventtype[cid] == SHOPMODULE_SELL_ITEM then
local msg = module.npcHandler:getMessage(MESSAGE_SELL)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM then
local msg = module.npcHandler:getMessage(MESSAGE_BUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM_CONTAINER then
local msg = module.npcHandler:getMessage(MESSAGE_BUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
return true
end
end
| gpl-2.0 |
abbasgh12345/extreme11 | plugins/inpm.lua | 14 | 3149 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
--
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
gowadbd/DevDroid | data/config.lua | 2 | 8378 | do local _ = {
about_text = "lcome to KING_TELE \n DEV1: @ll_B5 \n DEV2: @sadikal_knani10 \n\n الاصدار :- V 3.0 \n CH1: @illOlli \n CH2: @KINGTELE1 \n it is Bakury ",
enabled_plugins = {
"admin",
"all",
"anti_spam",
"ar-banhammer",
"ar-broadcast",
"ar-getfile",
"ar-help",
"ar-info",
"ar-lock-bot",
"ar-lock-fwd",
"ar-onservice",
"ar-plugins",
"ar-robot",
"ar_version",
"arabic_lock",
"setwelcome",
"get",
"ingroup",
"inrealm",
"invite",
"isup",
"leave_ban",
"msg_checks",
"newgroup",
"@illOlli",
"ardevs",
"endevs",
"h1",
"h2",
"hsudo",
"owners",
"set",
"stats",
"run",
"ar-getlink",
"hello",
"serverinfo",
"ar-me",
"ar-badword",
"en_version",
"replay",
"ar-supergroup",
"BAKURY",
"we",
"ar-we",
"calc",
"h3",
"h4",
"photo",
"z",
"map",
"kik",
"ndf",
"steck",
},
help_text = "Commands list :\n\n!kick [username|id]\nYou can also do it by reply\n\n!ban [ username|id]\nYou can also do it by reply\n\n!unban [id]\nYou can also do it by reply\n\n!who\nMembers list\n\n!modlist\nModerators list\n\n!promote [username]\nPromote someone\n\n!demote [username]\nDemote someone\n\n!kickme\nWill kick user\n\n!about\nGroup description\n\n!setphoto\nSet and locks group photo\n\n!setname [name]\nSet group name\n\n!rules\nGroup rules\n\n!id\nreturn group id or user id\n\n!help\nReturns help text\n\n!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]\nLock group settings\n*rtl: Kick user if Right To Left Char. is in name*\n\n!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]\nUnlock group settings\n*rtl: Kick user if Right To Left Char. is in name*\n\n!mute [all|audio|gifs|photo|video]\nmute group message types\n*If \"muted\" message type: user is kicked if message type is posted \n\n!unmute [all|audio|gifs|photo|video]\nUnmute group message types\n*If \"unmuted\" message type: user is not kicked if message type is posted \n\n!set rules <text>\nSet <text> as rules\n\n!set about <text>\nSet <text> as about\n\n!settings\nReturns group settings\n\n!muteslist\nReturns mutes for chat\n\n!muteuser [username]\nMute a user in chat\n*user is kicked if they talk\n*only owners can mute | mods and owners can unmute\n\n!mutelist\nReturns list of muted users in chat\n\n!newlink\ncreate/revoke your group link\n\n!link\nreturns group link\n\n!owner\nreturns group owner id\n\n!setowner [id]\nWill set id as owner\n\n!setflood [value]\nSet [value] as flood sensitivity\n\n!stats\nSimple message statistics\n\n!save [value] <text>\nSave <text> as [value]\n\n!get [value]\nReturns text of [value]\n\n!clean [modlist|rules|about]\nWill clear [modlist|rules|about] and set it to nil\n\n!res [username]\nreturns user id\n\"!res @username\"\n\n!log\nReturns group logs\n\n!banlist\nwill return group ban list\n\n**You can use \"#\", \"!\", or \"/\" to begin all commands\n\n\n*Only owner and mods can add bots in group\n\n\n*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands\n\n*Only owner can use res,setowner,promote,demote and log commands\n\n",
help_text_realm = "Realm Commands:\n\n!creategroup [Name]\nCreate a group\n\n!createrealm [Name]\nCreate a realm\n\n!setname [Name]\nSet realm name\n\n!setabout [group|sgroup] [GroupID] [Text]\nSet a group's about text\n\n!setrules [GroupID] [Text]\nSet a group's rules\n\n!lock [GroupID] [setting]\nLock a group's setting\n\n!unlock [GroupID] [setting]\nUnock a group's setting\n\n!settings [group|sgroup] [GroupID]\nSet settings for GroupID\n\n!wholist\nGet a list of members in group/realm\n\n!who\nGet a file of members in group/realm\n\n!type\nGet group type\n\n!kill chat [GroupID]\nKick all memebers and delete group\n\n!kill realm [RealmID]\nKick all members and delete realm\n\n!addadmin [id|username]\nPromote an admin by id OR username *Sudo only\n\n!removeadmin [id|username]\nDemote an admin by id OR username *Sudo only\n\n!list groups\nGet a list of all groups\n\n!list realms\nGet a list of all realms\n\n!support\nPromote user to support\n\n!-support\nDemote user from support\n\n!log\nGet a logfile of current group or realm\n\n!broadcast [text]\n!broadcast Hello !\nSend text to all groups\nOnly sudo users can run this command\n\n!bc [group_id] [text]\n!bc 123456789 Hello !\nThis command will send text to [group_id]\n\n\n**You can use \"#\", \"!\", or \"/\" to begin all commands\n\n\n*Only admins and sudo can add bots in group\n\n\n*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands\n\n*Only admins and sudo can use res, setowner, commands\n",
help_text_super = "SuperGroup Commands:\n\n!gpinfo\nDisplays general info about the SuperGroup\n\n!admins\nReturns SuperGroup admins list\n\n!owner\nReturns group owner\n\n!modlist\nReturns Moderators list\n\n!bots\nLists bots in SuperGroup\n\n!who\nLists all users in SuperGroup\n\n!block\nKicks a user from SuperGroup\n*Adds user to blocked list*\n\n!kick\nKicks a user from SuperGroup\n*Adds user to blocked list*\n\n!ban\nBans user from the SuperGroup\n\n!unban\nUnbans user from the SuperGroup\n\n!id\nReturn SuperGroup ID or user id\n*For userID's: !id @username or reply !id*\n\n!id from\nGet ID of user message is forwarded from\n\n!kickme\nKicks user from SuperGroup\n*Must be unblocked by owner or use join by pm to return*\n\n!setowner\nSets the SuperGroup owner\n\n!promote [username|id]\nPromote a SuperGroup moderator\n\n!demote [username|id]\nDemote a SuperGroup moderator\n\n!setname\nSets the chat name\n\n!setphoto\nSets the chat photo\n\n!setrules\nSets the chat rules\n\n!setabout\nSets the about section in chat info(members list)\n\n!save [value] <text>\nSets extra info for chat\n\n!get [value]\nRetrieves extra info for chat by value\n\n!newlink\nGenerates a new group link\n\n!link\nRetireives the group link\n\n!rules\nRetrieves the chat rules\n\n!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict|tag|username|fwd|reply|fosh|tgservice|leave|join|emoji|english|media|operator]\nLock group settings\n*rtl: Delete msg if Right To Left Char. is in name*\n*strict: enable strict settings enforcement (violating user will be kicked)*\n*fosh: Delete badword msg*\n*fwd: Delete forward msg*\n\n!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict|tag|username|fwd|reply|fosh|tgservice|leave|join|emoji|english|media|operator]\nUnlock group settings\n*rtl: Delete msg if Right To Left Char. is in name*\n*strict: disable strict settings enforcement (violating user will not be kicked)*\n\n!mute [all|audio|gifs|photo|video|service]\nmute group message types\n*A \"muted\" message type is auto-deleted if posted\n\n!unmute [all|audio|gifs|photo|video|service]\nUnmute group message types\n*A \"unmuted\" message type is not auto-deleted if posted\n\n!setflood [value]\nSet [value] as flood sensitivity\n\n!type [name]\nset type for supergroup\n\n!settings\nReturns chat settings\n\n!mutelist\nReturns mutes for chat\n\n!silent [username]\nMute a user in chat\n*If a muted user posts a message, the message is deleted automaically\n*only owners can mute | mods and owners can unmute\n\n!silentlist\nReturns list of muted users in chat\n\n!banlist\nReturns SuperGroup ban list\n\n!clean [rules|about|modlist|silentlist|filterlist]\n\n!del\nDeletes a message by reply\n\n!filter [word]\nbot Delete word if member send\n\n!unfilter [word]\nDelete word in filter list\n\n!filterlist\nget filter list\n\n!clean msg [value]\n\n!public [yes|no]\nSet chat visibility in pm !chats or !chatlist commands\n\n!res [username]\nReturns users name and id by username\n\n!log\nReturns group logs\n*Search for kick reasons using [#RTL|#spam|#lockmember]\n\n**You can use \"#\", \"!\", or \"/\" to begin all commands\n*Only owner can add members to SuperGroup\n(use invite link to invite)\n*Only moderators and owner can use block, ban, unban, newlink, link, setphoto, setname, lock, unlock, setrules, setabout and settings commands\n*Only owner can use res, setowner, promote, demote, and log commands\n",
moderation = {
data = "data/moderation.json"
},
sudo_users = {
284670491,
55197430,
}
}
return _
end
| gpl-2.0 |
TheRikyHUN/fooniks | resources/phoenix_Skills/achievements_c.lua | 2 | 7104 | AchievementDraw = {
rootElement,
thePlayer,
sx, sy, scale,
positions = { },
imagepos = { },
labelpos = { },
textpos = { },
coinspos = { },
xppos = { },
messageLoop = { },
white = tocolor( 255, 255, 255, 255 ),
labelColor = tocolor( 254, 201, 7, 255 ),
textColor = tocolor( 255, 255, 255, 255 ),
alpha = 255
};
function AchievementDraw:new( o )
o = o or { };
setmetatable( o, self );
self.__index = self;
self.rootElement = getRootElement( );
self.thePlayer = getLocalPlayer( );
self.sx, self.sy = guiGetScreenSize( );
self:Calculate( );
return o;
end
function AchievementDraw:doEvents( )
addEventHandler( "onClientRender", self.rootElement,
function ( )
self:OnDraw( );
end
);
setTimer( function ( ) self:OnTimer( ); end, 1000, 0 );
addEvent( "onAchievementCompleted", true );
addEventHandler( "onAchievementCompleted", self.rootElement,
function ( theLabel, aData )
local sTbl = { };
sTbl.img = aData["img"];
sTbl.label = theLabel;
sTbl.text = aData["name"] .. " - " .. aData["desc"];
sTbl.coins = aData["coins"];
sTbl.xp = aData["xp"];
self:PushMessage( sTbl );
end
);
end
function AchievementDraw:SetColors( )
self.white = tocolor( 255, 255, 255, self.alpha );
self.labelColor = tocolor( 254, 201, 7, self.alpha );
self.textColor = tocolor( 255, 255, 255, self.alpha );
end
function AchievementDraw:Calculate( )
self.scale = ( self.sx / 1366 ); -- 1366 x 768
--
self.positions[1] = self.sx - ( 300 * self.scale );
self.positions[2] = self.sy - ( 125 * self.scale );
self.positions[3] = ( 300 * self.scale );
self.positions[4] = ( 125 * self.scale );
--
self.imagepos[1] = self.positions[1] + ( 12.5 * self.scale );
self.imagepos[2] = self.positions[2] + ( 12.5 * self.scale );
self.imagepos[3] = ( 100 * self.scale );
self.imagepos[4] = ( 100 * self.scale );
--
self.labelpos[1] = self.positions[1] + ( 120 * self.scale );
self.labelpos[2] = self.positions[2] + ( 12.5 * self.scale );
self.labelpos[3] = self.labelpos[1] + ( 160 * self.scale );
self.labelpos[4] = self.labelpos[2] + ( 20 * self.scale );
--
self.textpos[1] = self.positions[1] + ( 120 * self.scale );
self.textpos[2] = self.positions[2] + ( 32.5 * self.scale );
self.textpos[3] = self.textpos[1] + ( 160 * self.scale );
self.textpos[4] = self.textpos[2] + ( 60 * self.scale );
--
self.coinspos[1] = self.positions[1] + ( 120 * self.scale );
self.coinspos[2] = self.positions[2] + ( 96.5 * self.scale );
self.coinspos[3] = 16 * self.scale;
self.coinspos[4] = 16 * self.scale;
self.coinspos[5] = self.coinspos[1] + self.coinspos[3] + ( 5 * self.scale );
self.coinspos[6] = self.coinspos[2];
self.coinspos[7] = self.coinspos[5] + ( 20 * self.scale );
self.coinspos[8] = self.coinspos[6] + ( 60 );
--
self.xppos[1] = self.positions[1] + ( 205 * self.scale );
self.xppos[2] = self.positions[2] + ( 96.5 * self.scale );
self.xppos[3] = 16 * self.scale;
self.xppos[4] = 16 * self.scale;
self.xppos[5] = self.xppos[1] + self.xppos[3] + ( 5 * self.scale );
self.xppos[6] = self.xppos[2];
self.xppos[7] = self.xppos[5] + ( 20 * self.scale );
self.xppos[8] = self.xppos[6] + ( 60 );
-- Colors
self:SetColors( );
end
function AchievementDraw:PushMessage( messageTable )
table.insert( self.messageLoop, messageTable );
end
function AchievementDraw:RemoveMessage( theId )
table.remove( self.messageLoop, theId );
end
function AchievementDraw:OnTimer( )
if( #self.messageLoop > 0 ) then
if( self.messageLoop[1].tstamp and getTickCount( ) - self.messageLoop[1].tstamp > 4000 ) then
self.messageLoop[1].rem = true;
end
end
end
function AchievementDraw:OnDraw( )
if( #self.messageLoop > 0 ) then
if( not self.messageLoop[1].tstamp ) then
if( self.Animation and not self.Animation.Complete ) then
local alphachange = self.Animation:ShowTick( self.alpha / 255 );
self.alpha = 255 * alphachange;
self:SetColors( );
else
if( self.Animation ) then self.Animation.Complete = false; end
self.messageLoop[1].tstamp = getTickCount( );
end
elseif( self.messageLoop[1].rem ) then
if( self.Animation and not self.Animation.Complete ) then
local alphachange = self.Animation:HideTick( self.alpha / 255 );
self.alpha = 255 * alphachange;
self:SetColors( );
else
if( self.Animation ) then self.Animation.Complete = false; end
self:RemoveMessage( 1 );
return false;
end
end
dxDrawImage( self.positions[1], self.positions[2], self.positions[3], self.positions[4], "levelUpBack.png", 0, 0, 0, self.white, true );
dxDrawImage( self.imagepos[1], self.imagepos[2], self.imagepos[3], self.imagepos[4], self.messageLoop[1].img or "aimages/achievement.png", 0, 0, 0, self.white, true );
dxDrawText( self.messageLoop[1].label or "Label", self.labelpos[1], self.labelpos[2], self.labelpos[3], self.labelpos[4], self.labelColor, 1.5 * self.scale, "default-bold", "left", "top", true, false, true );
dxDrawText( self.messageLoop[1].text or "Dummy text", self.textpos[1], self.textpos[2], self.textpos[3], self.textpos[4], self.textColor, 1 * self.scale, "default", "left", "top", false, true, true );
-- DrawXP and Coins
dxDrawImage( self.coinspos[1], self.coinspos[2], self.coinspos[3], self.coinspos[4], "coins.png", 0, 0, 0, self.white, true );
dxDrawImage( self.xppos[1], self.xppos[2], self.xppos[3], self.xppos[4], "xp.png", 0, 0, 0, self.white, true );
dxDrawText( tostring( self.messageLoop[1].coins ) or "0", self.coinspos[5], self.coinspos[6], self.coinspos[7], self.coinspos[8], self.textColor, 1 * self.scale, "default", "left", "top", true, false, true );
dxDrawText( tostring( self.messageLoop[1].xp ) or "0", self.xppos[5], self.xppos[6], self.xppos[7], self.xppos[8], self.textColor, 1 * self.scale, "default", "left", "top", true, false, true );
end
end
AlphaAnimation = {
cAlpha = 0.0,
step = 0.05,
Complete = false
};
function AlphaAnimation:new( start, o )
o = o or { };
setmetatable( o, self );
self.__index = self;
self.cAlpha = start;
return o;
end
function AlphaAnimation:ShowTick( remAlpha )
if( self.Complete ) then self.Complete = false; end
self.cAlpha = self.cAlpha + self.step;
if( self.cAlpha >= 1 ) then
self.cAlpha = 1;
self.Complete = true;
end
return self.cAlpha;
end
function AlphaAnimation:HideTick( remAlpha )
if( self.Complete ) then self.Complete = false; end
self.cAlpha = self.cAlpha - self.step;
if( self.cAlpha <= 0 ) then
self.cAlpha = 0;
self.Complete = true;
end
return self.cAlpha;
end
theDraw = AchievementDraw:new( );
theDraw:doEvents( );
theDraw:SetColors( );
local theAnim = AlphaAnimation:new( 0 );
theDraw.Animation = theAnim;
| gpl-3.0 |
shahabsaf1/fucker | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
naader1380/Dragon1 | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/globals/items/caedarva_frog.lua | 12 | 1478 | -----------------------------------------
-- ID: 5465
-- Item: Caedarva Frog
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Agility 2
-- Mind -4
-- Evasion 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5465);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
target:addMod(MOD_AGI, 2);
target:addMod(MOD_EVA, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
target:delMod(MOD_AGI, 2);
target:delMod(MOD_EVA, 5);
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Jugner_Forest_[S]/npcs/Larkin_CA.lua | 3 | 1044 | -----------------------------------
-- Area: Jugner Forest (S)
-- NPC: Larkin, C.A.
-- Type: Campaign Arbiter
-- !pos 50.217 -1.769 51.095 82
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Jugner_Forest_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01c5);
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 |
RebootRevival/FFXI_Test | scripts/zones/RuAun_Gardens/npcs/relic.lua | 3 | 1868 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: <this space intentionally left blank>
-- !pos -241 -12 332 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18299 and trade:getItemCount() == 4 and trade:hasItemQty(18299,1) and
trade:hasItemQty(1578,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1451,1)) then
player:startEvent(60,18300);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 60) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18300);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1450);
else
player:tradeComplete();
player:addItem(18300);
player:addItem(1450,30);
player:messageSpecial(ITEM_OBTAINED,18300);
player:messageSpecial(ITEMS_OBTAINED,1450,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Port_Bastok/npcs/Styi_Palneh.lua | 3 | 4322 | -----------------------------------
-- Area: Port Bastok
-- NPC: Styi Palneh
-- Title Change NPC
-- !pos 28 4 -15 236
-----------------------------------
require("scripts/globals/titles");
local title2 = { NEW_ADVENTURER , BASTOK_WELCOMING_COMMITTEE , BUCKET_FISHER , PURSUER_OF_THE_PAST , MOMMYS_HELPER , HOT_DOG ,
STAMPEDER , RINGBEARER , ZERUHN_SWEEPER , TEARJERKER , CRAB_CRUSHER , BRYGIDAPPROVED , GUSTABERG_TOURIST , MOGS_MASTER , CERULEAN_SOLDIER ,
DISCERNING_INDIVIDUAL , VERY_DISCERNING_INDIVIDUAL , EXTREMELY_DISCERNING_INDIVIDUAL , APOSTATE_FOR_HIRE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title3 = { SHELL_OUTER , PURSUER_OF_THE_TRUTH , QIJIS_FRIEND , TREASURE_SCAVENGER , SAND_BLASTER , DRACHENFALL_ASCETIC ,
ASSASSIN_REJECT , CERTIFIED_ADVENTURER , QIJIS_RIVAL , CONTEST_RIGGER , KULATZ_BRIDGE_COMPANION , AVENGER , AIRSHIP_DENOUNCER ,
STAR_OF_IFRIT , PURPLE_BELT , MOGS_KIND_MASTER , TRASH_COLLECTOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title4 = { BEADEAUX_SURVEYOR , PILGRIM_TO_DEM , BLACK_DEATH , DARK_SIDER , SHADOW_WALKER , SORROW_DROWNER , STEAMING_SHEEP_REGULAR ,
SHADOW_BANISHER , MOGS_EXCEPTIONALLY_KIND_MASTER , HYPER_ULTRA_SONIC_ADVENTURER , GOBLIN_IN_DISGUISE , BASTOKS_SECOND_BEST_DRESSED ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title5 = { PARAGON_OF_WARRIOR_EXCELLENCE , PARAGON_OF_MONK_EXCELLENCE , PARAGON_OF_DARK_KNIGHT_EXCELLENCE , HEIR_OF_THE_GREAT_EARTH ,
MOGS_LOVING_MASTER , HERO_AMONG_HEROES , DYNAMISBASTOK_INTERLOPER , MASTER_OF_MANIPULATION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title6 = { LEGIONNAIRE , DECURION , CENTURION , JUNIOR_MUSKETEER , SENIOR_MUSKETEER , MUSKETEER_COMMANDER , GOLD_MUSKETEER ,
PRAEFECTUS , SENIOR_GOLD_MUSKETEER , PRAEFECTUS_CASTRORUM , ANVIL_ADVOCATE , FORGE_FANATIC , ACCOMPLISHED_BLACKSMITH , ARMORY_OWNER , TRINKET_TURNER ,
SILVER_SMELTER , ACCOMPLISHED_GOLDSMITH , JEWELRY_STORE_OWNER , FORMULA_FIDDLER , POTION_POTENTATE , ACCOMPLISHED_ALCHEMIST , APOTHECARY_OWNER ,
0 , 0 , 0 , 0 , 0 , 0 }
local title7 = { MOG_HOUSE_HANDYPERSON , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00C8,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid==0x00C8) then
if (option > 0 and option <29) then
if (player:delGil(200)) then
player:setTitle( title2[option] )
end
elseif (option > 256 and option <285) then
if (player:delGil(300)) then
player:setTitle( title3[option - 256] )
end
elseif (option > 512 and option < 541) then
if (player:delGil(400)) then
player:setTitle( title5[option - 512] )
end
elseif (option > 768 and option <797) then
if (player:delGil(500)) then
player:setTitle( title5[option - 768] )
end
elseif (option > 1024 and option < 1053) then
if (player:delGil(600)) then
player:setTitle( title6[option - 1024] )
end
elseif (option > 1280 and option < 1309) then
if (player:delGil(700)) then
player:setTitle( title7[option - 1280])
end
end
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Abyssea-Konschtat/npcs/qm5.lua | 3 | 1347 | -----------------------------------
-- Zone: Abyssea-Konschtat
-- NPC: qm5 (???)
-- Spawns Keratyrannos
-- !pos ? ? ? 15
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
if (trade:hasItemQty(2910,1) and trade:getItemCount() == 1) then -- Player has all the required items.
if (GetMobAction(16838871) == ACTION_NONE) then -- Mob not already spawned from this
SpawnMob(16838871):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:tradeComplete();
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(1010, 2910); -- Inform payer what items they need.
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 |
RebootRevival/FFXI_Test | scripts/zones/Northern_San_dOria/npcs/Aurege.lua | 3 | 1969 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Aurege
-- Type: Quest Giver NPC
-- Starts Quest: Exit the Gambler
-- @zone 231
-- !pos -156.253 11.999 253.691
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
exitTheGambler = player:getQuestStatus(SANDORIA,EXIT_THE_GAMBLER);
if (player:hasKeyItem(MAP_OF_KING_RANPERRES_TOMB)) then
player:startEvent(0x0202);
elseif (exitTheGambler == QUEST_COMPLETED) then
player:startEvent(0x0204);
else
player:startEvent(0x0209);
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);
exitTheGambler = player:getQuestStatus(SANDORIA,EXIT_THE_GAMBLER);
if (exitTheGambler == QUEST_AVAILABLE) then
player:addQuest(SANDORIA,EXIT_THE_GAMBLER);
elseif (exitTheGambler == QUEST_COMPLETED and player:hasKeyItem(MAP_OF_KING_RANPERRES_TOMB) == false) then
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_KING_RANPERRES_TOMB);
player:addKeyItem(MAP_OF_KING_RANPERRES_TOMB);
player:addTitle(DAYBREAK_GAMBLER);
player:addFame(SANDORIA,30);
end
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Horlais_Peak/bcnms/double_dragonian.lua | 30 | 1807 | -----------------------------------
-- Area: Horlias peak
-- Name: double_dragonian
-- KSNM30
-----------------------------------
package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Horlais_Peak/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
end;
| gpl-3.0 |
vyacht/carambola2 | package/vyacht-web/files/lib/lib/sys.lua | 3 | 5640 | local io = require "io"
local os = require "os"
local nixio = require "nixio"
--- stolen from luci
local type, table, tonumber, print
= type, table, tonumber, print
module "vyacht.sys"
--- Execute a given shell command and return the error code
-- @class function
-- @name call
-- @param ... Command to call
-- @return Error code of the command
function call(...)
return os.execute(...) / 256
end
--- Execute given commandline and gather stdout.
-- @param command String containing command to execute
-- @return String containing the command's stdout
function exec(command)
local pp = io.popen(command)
local data = pp:read("*a")
pp:close()
return data
end
--- Return a line-buffered iterator over the output of given command.
-- @param command String containing the command to execute
-- @return Iterator
function execi(command)
local pp = io.popen(command)
return pp and function()
local line = pp:read()
if not line then
pp:close()
end
return line
end
end
--- Get or set the current hostname.
-- @param String containing a new hostname to set (optional)
-- @return String containing the system hostname
function hostname(newname)
if type(newname) == "string" and #newname > 0 then
fs.writefile( "/proc/sys/kernel/hostname", newname )
return newname
else
return nixio.uname().nodename
end
end
--- Returns the current system uptime stats.
-- @return String containing total uptime in seconds
function uptime()
return nixio.sysinfo().uptime
end
--- Retrieve information about currently mounted file systems.
-- @return Table containing mount information
function mounts()
local data = {}
local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"}
local ps = execi("df")
if not ps then
return
else
ps()
end
for line in ps do
local row = {}
local j = 1
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
if row[k[1]] then
-- this is a rather ugly workaround to cope with wrapped lines in
-- the df output:
--
-- /dev/scsi/host0/bus0/target0/lun0/part3
-- 114382024 93566472 15005244 86% /mnt/usb
--
if not row[k[2]] then
j = 2
line = ps()
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
end
table.insert(data, row)
end
end
return data
end
--- Retrieve information about currently running processes.
-- @return Table containing process information
function processes()
local data = {}
local k
local ps = execi("/bin/busybox top -bn1")
if not ps then
return
end
for line in ps do
local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
"^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)"
)
local idx = tonumber(pid)
if idx then
data[idx] = {
['PID'] = pid,
['PPID'] = ppid,
['USER'] = user,
['STAT'] = stat,
['VSZ'] = vsz,
['%MEM'] = mem,
['%CPU'] = cpu,
['COMMAND'] = cmd
}
end
end
return data
end
| gpl-2.0 |
vyacht/carambola2 | package/vyacht-web/files/lib/sys.lua | 3 | 5640 | local io = require "io"
local os = require "os"
local nixio = require "nixio"
--- stolen from luci
local type, table, tonumber, print
= type, table, tonumber, print
module "vyacht.sys"
--- Execute a given shell command and return the error code
-- @class function
-- @name call
-- @param ... Command to call
-- @return Error code of the command
function call(...)
return os.execute(...) / 256
end
--- Execute given commandline and gather stdout.
-- @param command String containing command to execute
-- @return String containing the command's stdout
function exec(command)
local pp = io.popen(command)
local data = pp:read("*a")
pp:close()
return data
end
--- Return a line-buffered iterator over the output of given command.
-- @param command String containing the command to execute
-- @return Iterator
function execi(command)
local pp = io.popen(command)
return pp and function()
local line = pp:read()
if not line then
pp:close()
end
return line
end
end
--- Get or set the current hostname.
-- @param String containing a new hostname to set (optional)
-- @return String containing the system hostname
function hostname(newname)
if type(newname) == "string" and #newname > 0 then
fs.writefile( "/proc/sys/kernel/hostname", newname )
return newname
else
return nixio.uname().nodename
end
end
--- Returns the current system uptime stats.
-- @return String containing total uptime in seconds
function uptime()
return nixio.sysinfo().uptime
end
--- Retrieve information about currently mounted file systems.
-- @return Table containing mount information
function mounts()
local data = {}
local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"}
local ps = execi("df")
if not ps then
return
else
ps()
end
for line in ps do
local row = {}
local j = 1
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
if row[k[1]] then
-- this is a rather ugly workaround to cope with wrapped lines in
-- the df output:
--
-- /dev/scsi/host0/bus0/target0/lun0/part3
-- 114382024 93566472 15005244 86% /mnt/usb
--
if not row[k[2]] then
j = 2
line = ps()
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
end
table.insert(data, row)
end
end
return data
end
--- Retrieve information about currently running processes.
-- @return Table containing process information
function processes()
local data = {}
local k
local ps = execi("/bin/busybox top -bn1")
if not ps then
return
end
for line in ps do
local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
"^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)"
)
local idx = tonumber(pid)
if idx then
data[idx] = {
['PID'] = pid,
['PPID'] = ppid,
['USER'] = user,
['STAT'] = stat,
['VSZ'] = vsz,
['%MEM'] = mem,
['%CPU'] = cpu,
['COMMAND'] = cmd
}
end
end
return data
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Wajaom_Woodlands/Zone.lua | 12 | 4137 | -----------------------------------
--
-- Zone: Wajaom_Woodlands (51)
--
-----------------------------------
package.loaded["scripts/zones/Wajaom_Woodlands/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Wajaom_Woodlands/TextIDs");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 770, 50, DIGREQ_NONE },
{ 2150, 60, DIGREQ_NONE },
{ 622, 197, DIGREQ_NONE },
{ 2155, 23, DIGREQ_NONE },
{ 739, 5, DIGREQ_NONE },
{ 17296, 133, DIGREQ_NONE },
{ 703, 69, DIGREQ_NONE },
{ 2213, 135, DIGREQ_NONE },
{ 838, 21, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 1255, 10, DIGREQ_NONE }, -- all ores
{ 688, 144, DIGREQ_BURROW },
{ 702, 14, DIGREQ_BURROW },
{ 690, 23, DIGREQ_BURROW },
{ 1446, 3, DIGREQ_BURROW },
{ 700, 14, DIGREQ_BURROW },
{ 699, 37, DIGREQ_BURROW },
{ 701, 28, DIGREQ_BURROW },
{ 696, 23, DIGREQ_BURROW },
{ 678, 9, DIGREQ_BORE },
{ 645, 3, DIGREQ_BORE },
{ 768, 193, DIGREQ_BORE },
{ 737, 22, DIGREQ_BORE },
{ 2475, 3, DIGREQ_BORE },
{ 738, 3, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- 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
if (player:getCurrentMission(TOAU) == UNRAVELING_REASON) then
player:setPos(-200.036,-10,79.948,254);
cs = 11;
else
player:setPos(610.542,-28.547,356.247,122);
end
elseif (player:getVar("threemenandaclosetCS") == 2 and prevZone == 50) then
cs = 0x01fe;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("Update CSID: %u",csid);
-- printf("Update RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("Finish CSID: %u",csid);
-- printf("Finish RESULT: %u",option);
if (csid == 0x01fe) then
player:setVar("threemenandaclosetCS",3);
elseif (csid == 11) then
player:startEvent(21);
elseif (csid == 21) then
player:startEvent(22);
elseif (csid == 22) then
player:completeMission(TOAU,UNRAVELING_REASON);
player:setTitle(ENDYMION_PARATROOPER);
player:setVar("TOAUM40_STARTDAY", 0);
player:addMission(TOAU,LIGHT_OF_JUDGMENT);
end
end;
| gpl-3.0 |
ashang/koreader | frontend/ui/message/messagequeue.lua | 6 | 2531 | local ffi = require("ffi")
local util = require("ffi/util")
local Event = require("ui/event")
local DEBUG = require("dbg")
local dummy = require("ffi/zeromq_h")
local czmq = ffi.load("libs/libczmq.so.1")
local zyre = ffi.load("libs/libzyre.so.1")
local MessageQueue = {}
function MessageQueue:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
self.messages = {}
return o
end
function MessageQueue:init()
end
function MessageQueue:start()
end
function MessageQueue:stop()
end
function MessageQueue:waitEvent()
end
function MessageQueue:handleZMsgs(messages)
local function drop_message()
if czmq.zmsg_size(messages[1]) == 0 then
czmq.zmsg_destroy(ffi.new('zmsg_t *[1]', messages[1]))
table.remove(messages, 1)
end
end
local function pop_string()
local str_p = czmq.zmsg_popstr(messages[1])
local message_size = czmq.zmsg_size(messages[1])
local res = ffi.string(str_p)
czmq.zstr_free(ffi.new('char *[1]', str_p))
drop_message()
return res
end
local function pop_header()
local header = {}
local frame = czmq.zmsg_pop(messages[1])
if frame ~= nil then
local hash = czmq.zhash_unpack(frame)
czmq.zframe_destroy(ffi.new('zframe_t *[1]', frame))
if hash ~= nil then
local value, key = czmq.zhash_first(hash), czmq.zhash_cursor(hash)
while value ~= nil and key ~= nil do
header[ffi.string(key)] = ffi.string(value)
value, key = czmq.zhash_next(hash), czmq.zhash_cursor(hash)
end
czmq.zhash_destroy(ffi.new('zhash_t *[1]', hash))
end
end
drop_message()
return header
end
if #messages == 0 then return end
local message_size = czmq.zmsg_size(messages[1])
local command = pop_string()
DEBUG("ØMQ message", command)
if command == "ENTER" then
local id = pop_string()
local name = pop_string()
local header = pop_header()
local endpoint = pop_string()
--DEBUG(id, name, header, endpoint)
return Event:new("ZyreEnter", id, name, header, endpoint)
elseif command == "DELIVER" then
local filename = pop_string()
local fullname = pop_string()
--DEBUG("received", filename)
return Event:new("FileDeliver", filename, fullname)
end
end
return MessageQueue
| agpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Windurst_Waters/npcs/Kerutoto.lua | 3 | 12516 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Kerutoto
-- Starts Quest Food For Thought
-- Involved in Quest: Riding on the Clouds
-- @zone 238
-- !pos 13 -5 -157
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Waters/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
if (player:getQuestStatus(WINDURST,BLUE_RIBBON_BLUES) == QUEST_ACCEPTED) then
if (trade:hasItemQty(12521,1) and count == 1) then
player:startEvent(0x016a);
elseif (trade:hasItemQty(13569,1) and count == 1) then
if (player:getVar("BlueRibbonBluesProg") == 4) then
player:startEvent(0x016d); -- Lost, ribbon but it came back
else
player:startEvent(0x0166,3600);
end
end
end
if (player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT) == QUEST_ACCEPTED and trade:hasItemQty(4371,1) and count == 1) then
player:startEvent(0x014c,440);
player:setVar("Kerutoto_Food_var",2);
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 3) then
if (trade:hasItemQty(1127,1) and count == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_4",0);
player:tradeComplete();
player:addKeyItem(SPIRITED_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local KerutotoFood = player:getVar("Kerutoto_Food_var"); -- Variable to track progress of Kerutoto in Food for Thought
local FoodForThought = player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT);
local OhbiruFood = player:getVar("Ohbiru_Food_var"); -- Variable to track progress of Ohbiru-Dohbiru in Food for Thought
local BlueRibbonBlues = player:getQuestStatus(WINDURST,BLUE_RIBBON_BLUES);
local needZone = player:needToZone();
local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
local waking_dreams = player:getQuestStatus(WINDURST,WAKING_DREAMS)
-- Awakening of the Gods --
if (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02E1);
elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 1) then
player:startEvent(0x02E0);
elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 2) then
player:startEvent(0x02E2);
-- Three Paths --
elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 3) then
player:startEvent(0x036c);
-- Waking Dreams --
elseif (player:hasKeyItem(VIAL_OF_DREAM_INCENSE)==false and ((player:hasCompletedMission(COP,DARKNESS_NAMED) and waking_dreams == QUEST_AVAILABLE ) or(waking_dreams == QUEST_COMPLETED and realday ~= player:getVar("Darkness_Named_date")))) then
player:addQuest(WINDURST,WAKING_DREAMS);
player:startEvent(0x0396);--918
elseif (player:hasKeyItem(WHISPER_OF_DREAMS)==true) then
local availRewards = 0
if (player:hasItem(17599)) then availRewards = availRewards + 1; end -- Diabolos's Pole
if (player:hasItem(14814)) then availRewards = availRewards + 2; end -- Diabolos's Earring
if (player:hasItem(15557)) then availRewards = availRewards + 4; end -- Diabolos's Ring
if (player:hasItem(15516)) then availRewards = availRewards + 8; end -- Diabolos's Torque
if (player:hasSpell(304)) then availRewards = availRewards + 32; -- Pact
else availRewards = availRewards + 16 -- Gil
end
player:startEvent(0x0398,17599,14814,15557,15516,0,0,0,availRewards);
-- Blue Ribbon Blues --
elseif (BlueRibbonBlues == QUEST_COMPLETED and needZone) then
player:startEvent(0x016b);--363
elseif (BlueRibbonBlues == QUEST_ACCEPTED) then
local blueRibbonProg = player:getVar("BlueRibbonBluesProg");
if (player:hasItem(12521)) then
player:startEvent(0x016a);--362
elseif (blueRibbonProg == 2 and needZone == false) then
local timerDay = player:getVar("BlueRibbonBluesTimer_Day");
local currentDay = VanadielDayOfTheYear();
if (player:getVar("BlueRibbonBluesTimer_Year") < VanadielYear()) then
player:startEvent(0x0168); -- go to the grave 360
elseif (timerDay + 1 == VanadielDayOfTheYear() and player:getVar("BlueRibbonBluesTimer_Hour") <= VanadielHour()) then
player:startEvent(0x0168); -- go to the grave 360
elseif (timerDay + 2 <= VanadielDayOfTheYear()) then
player:startEvent(0x0168); -- go to the grave 360
else
player:startEvent(0x0167); -- Thanks for the ribbon 359
end
elseif (blueRibbonProg == 3) then
if (player:hasItem(13569)) then
player:startEvent(0x0169,0,13569); -- remidner, go to the grave
else
player:startEvent(0x016e,0,13569); -- lost the ribbon
end
elseif (blueRibbonProg == 4) then
player:startEvent(0x016e,0,13569);
else
player:startEvent(0x0132); -- Standard Conversation
end
elseif (BlueRibbonBlues == QUEST_AVAILABLE and player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_COMPLETED and player:getFameLevel(WINDURST) >= 5) then
player:startEvent(0x0165);
-- Food for Thought --
elseif (FoodForThought == QUEST_AVAILABLE) then
if (OhbiruFood == 1 and KerutotoFood ~= 256) then -- Player knows the researchers are hungry and quest not refused
player:startEvent(0x0139,0,4371); -- Offered Quest 1 (Including Order ifYES)
elseif (OhbiruFood == 1 and KerutotoFood == 256) then -- Player knows the researchers are hungry and quest refused previously
player:startEvent(0x013a,0,4371); -- Offered Quest 2 (Including Order ifYES)
else
player:startEvent(0x0138); -- Before Quest: Asks you to check on others.
end
elseif (FoodForThought == QUEST_ACCEPTED) then
if (KerutotoFood == 1) then
player:startEvent(0x013b,0,4371); -- Repeats Order
elseif (KerutotoFood == 3) then
player:startEvent(0x014d); -- Reminder to check with the others if this NPC has already been fed
end
elseif (FoodForThought == QUEST_COMPLETED and needZone) then
player:startEvent(0x0130); -- NPC is sleeping but feels full (post Food for Thought)
else
player:startEvent(0x0132); -- Standard Conversation
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 == 0x036c) then
player:setVar("COP_Ulmia_s_Path",4);
elseif ((csid == 0x0139 and option == 0) or (csid == 0x013a and option == 0)) then
player:addQuest(WINDURST,FOOD_FOR_THOUGHT);
player:setVar("Kerutoto_Food_var",1);
elseif (csid == 0x0139 and option == 1) then
player:setVar("Kerutoto_Food_var",256);
elseif (csid == 0x014c) then
if (player:getVar("Kerutoto_Food_var") == 2 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 3) then -- If this is the last NPC to be fed
player:addGil(GIL_RATE*440);
player:tradeComplete();
player:addTitle(FAST_FOOD_DELIVERER);
player:addFame(WINDURST,100);
player:needToZone(true);
player:completeQuest(WINDURST,FOOD_FOR_THOUGHT);
player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------
player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest
player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------
else
player:tradeComplete();
player:addGil(GIL_RATE*440);
player:setVar("Kerutoto_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed.
end
elseif (csid == 0x0165) then
player:addQuest(WINDURST,BLUE_RIBBON_BLUES);
elseif (csid == 0x0166 or csid == 0x016d) then
player:tradeComplete();
player:setVar("BlueRibbonBluesProg",2);
player:setVar("BlueRibbonBluesTimer_Hour",VanadielHour());
player:setVar("BlueRibbonBluesTimer_Year",VanadielYear());
player:setVar("BlueRibbonBluesTimer_Day",VanadielDayOfTheYear());
player:needToZone(true);
if (csid == 0x0166) then
player:addGil(GIL_RATE*3600);
end
elseif (csid == 0x0168) then
if (player:getFreeSlotsCount() >= 1) then
player:setVar("BlueRibbonBluesProg",3);
player:setVar("BlueRibbonBluesTimer_Hour",0);
player:setVar("BlueRibbonBluesTimer_Year",0);
player:setVar("BlueRibbonBluesTimer_Day",0);
player:addItem(13569);
player:messageSpecial(ITEM_OBTAINED,13569);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13569);
end
elseif (csid == 0x016a) then
player:completeQuest(WINDURST,BLUE_RIBBON_BLUES);
player:setVar("BlueRibbonBluesProg",0);
player:addFame(WINDURST,140);
player:addTitle(GHOSTIE_BUSTER);
player:needToZone(true);
elseif (csid == 0x0396) then --diablos start
player:addKeyItem(VIAL_OF_DREAM_INCENSE);
player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_DREAM_INCENSE);
elseif (csid == 0x0398) then --diablos reward
local item = 0;
local addspell = 0;
if (option == 1 and player:hasItem(17599)==false) then item = 17599;--diaboloss-pole
elseif (option == 2 and player:hasItem(14814)==false) then item = 14814;--diaboloss-earring
elseif (option == 3 and player:hasItem(15557)==false) then item = 15557;--diaboloss-ring
elseif (option == 4 and player:hasItem(15516)==false) then item = 15516;--diaboloss-torque
elseif (option == 5) then
player:addGil(GIL_RATE*15000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*15000); -- Gil
player:delKeyItem(WHISPER_OF_DREAMS);
player:setVar("Darkness_Named_date", os.date("%j")); -- %M for next minute, %j for next day
player:completeQuest(WINDURST,WAKING_DREAMS);
elseif (option == 6 and player:hasSpell(304)==false) then
player:addSpell(304); -- diabolos Spell
player:messageSpecial(DIABOLOS_UNLOCKED,0,0,0);
addspell=1;
end
if (addspell==1) then
player:delKeyItem(WHISPER_OF_DREAMS);
player:setVar("Darkness_Named_date", os.date("%j")); -- %M for next minute, %j for next day
player:completeQuest(WINDURST,WAKING_DREAMS);
elseif (item > 0 and player:getFreeSlotsCount()~=0) then
player:delKeyItem(WHISPER_OF_DREAMS);
player:setVar("Darkness_Named_date", os.date("%j")); -- %M for next minute, %j for next day
player:completeQuest(WINDURST,WAKING_DREAMS);
player:addItem(item);
player:messageSpecial(ITEM_OBTAINED,item); -- Item
elseif ( option ~= 5 and (( item == 0 and addspell==0 ) or (item > 0 and player:getFreeSlotsCount()==0) ) ) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item);
end
elseif (csid == 0x02E0) then
player:setVar("MissionStatus",2);
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Bastok_Markets/npcs/Peritrage.lua | 15 | 1527 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Peritrage
-- Standard Merchant NPC
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PERITRAGE_SHOP_DIALOG);
stock = {
0x4100, 284,3, --Bronze Axe
0x4101, 1435,3, --Brass Axe
0x4140, 604,3, --Butterfly Axe
0x4141, 4095,3, --Greataxe
0x4051, 147,3, --Bronze Knife
0x4052, 2182,3, --Knife
0x4040, 140,3, --Bronze Dagger
0x4041, 837,3, --Brass Dagger
0x4042, 1827,3 --Dagger
}
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 |
RebootRevival/FFXI_Test | scripts/zones/Xarcabard_[S]/mobs/Fusty_Gnole.lua | 17 | 1823 | -----------------------------------
-- Area: Xarcabard (S)
-- NPC: Fusty Gnole
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("transformTime", os.time())
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local transformTime = mob:getLocalVar("transformTime");
local roamChance = math.random(1,100);
local roamMoonPhase = VanadielMoonPhase();
if (roamChance > 100-roamMoonPhase) then
if (mob:AnimationSub() == 0 and os.time() - transformTime > 300) then
mob:AnimationSub(1);
mob:setLocalVar("transformTime", os.time());
elseif (mob:AnimationSub() == 1 and os.time() - transformTime > 300) then
mob:AnimationSub(0);
mob:setLocalVar("transformTime", os.time());
end
end
end;
-----------------------------------
-- onMobEngaged
-- Change forms every 60 seconds
-----------------------------------
function onMobEngaged(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local chance = math.random(1,100);
local moonPhase = VanadielMoonPhase();
if (chance > 100-moonPhase) then
if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(1);
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end; | gpl-3.0 |
wskplho/sl4a | lua/json4lua/json/json.lua | 20 | 15751 | -----------------------------------------------------------------------------
-- JSON4Lua: JSON encoding / decoding support for the Lua language.
-- json Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.20
-- This module is released under the The GNU General Public License (GPL).
-- Please see LICENCE.txt for details.
--
-- USAGE:
-- This module exposes two functions:
-- encode(o)
-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string.
-- decode(json_string)
-- Returns a Lua object populated with the data encoded in the JSON string json_string.
--
-- REQUIREMENTS:
-- compat-5.1 if using Lua 5.0
--
-- CHANGELOG
-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix).
-- Fixed Lua 5.1 compatibility issues.
-- Introduced json.null to have null values in associative arrays.
-- encode() performance improvement (more than 50%) through table.concat rather than ..
-- Introduced decode ability to ignore /**/ comments in the JSON string.
-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Imports and dependencies
-----------------------------------------------------------------------------
local math = require('math')
local string = require("string")
local table = require("table")
local base = _G
-----------------------------------------------------------------------------
-- Module declaration
-----------------------------------------------------------------------------
module("json")
-- Public functions
-- Private functions
local decode_scanArray
local decode_scanComment
local decode_scanConstant
local decode_scanNumber
local decode_scanObject
local decode_scanString
local decode_scanWhitespace
local encodeString
local isArray
local isEncodable
-----------------------------------------------------------------------------
-- PUBLIC FUNCTIONS
-----------------------------------------------------------------------------
--- Encodes an arbitrary Lua object / variable.
-- @param v The Lua object / variable to be JSON encoded.
-- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
function encode (v)
-- Handle nil values
if v==nil then
return "null"
end
local vtype = base.type(v)
-- Handle strings
if vtype=='string' then
return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
end
-- Handle booleans
if vtype=='number' or vtype=='boolean' then
return base.tostring(v)
end
-- Handle tables
if vtype=='table' then
local rval = {}
-- Consider arrays separately
local bArray, maxCount = isArray(v)
if bArray then
for i = 1,maxCount do
table.insert(rval, encode(v[i]))
end
else -- An object, not an array
for i,j in base.pairs(v) do
if isEncodable(i) and isEncodable(j) then
table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
end
end
end
if bArray then
return '[' .. table.concat(rval,',') ..']'
else
return '{' .. table.concat(rval,',') .. '}'
end
end
-- Handle null values
if vtype=='function' and v==null then
return 'null'
end
base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
end
--- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
-- @param s The string to scan.
-- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
-- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
-- and the position of the first character after
-- the scanned JSON object.
function decode(s, startPos)
startPos = startPos and startPos or 1
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
local curChar = string.sub(s,startPos,startPos)
-- Object
if curChar=='{' then
return decode_scanObject(s,startPos)
end
-- Array
if curChar=='[' then
return decode_scanArray(s,startPos)
end
-- Number
if string.find("+-0123456789.eE", curChar, 1, true) then
return decode_scanNumber(s,startPos)
end
-- String
if curChar==[["]] or curChar==[[']] then
return decode_scanString(s,startPos)
end
if string.sub(s,startPos,startPos+1)=='/*' then
return decode(s, decode_scanComment(s,startPos))
end
-- Otherwise, it must be a constant
return decode_scanConstant(s,startPos)
end
--- The null function allows one to specify a null value in an associative array (which is otherwise
-- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
function null()
return null -- so json.null() will also return null ;-)
end
-----------------------------------------------------------------------------
-- Internal, PRIVATE functions.
-- Following a Python-like convention, I have prefixed all these 'PRIVATE'
-- functions with an underscore.
-----------------------------------------------------------------------------
--- Scans an array from JSON into a Lua object
-- startPos begins at the start of the array.
-- Returns the array and the next starting position
-- @param s The string being scanned.
-- @param startPos The starting position for the scan.
-- @return table, int The scanned array as a table, and the position of the next character to scan.
function decode_scanArray(s,startPos)
local array = {} -- The return value
local stringLen = string.len(s)
base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
startPos = startPos + 1
-- Infinite loop for array elements
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
local curChar = string.sub(s,startPos,startPos)
if (curChar==']') then
return array, startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
object, startPos = decode(s,startPos)
table.insert(array,object)
until false
end
--- Scans a comment and discards the comment.
-- Returns the position of the next character following the comment.
-- @param string s The JSON string to scan.
-- @param int startPos The starting position of the comment
function decode_scanComment(s, startPos)
base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
local endPos = string.find(s,'*/',startPos+2)
base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
return endPos+2
end
--- Scans for given constants: true, false or null
-- Returns the appropriate Lua type, and the position of the next character to read.
-- @param s The string being scanned.
-- @param startPos The position in the string at which to start scanning.
-- @return object, int The object (true, false or nil) and the position at which the next character should be
-- scanned.
function decode_scanConstant(s, startPos)
local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
local constNames = {"true","false","null"}
for i,k in base.pairs(constNames) do
--print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
return consts[k], startPos + string.len(k)
end
end
base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
end
--- Scans a number from the JSON encoded string.
-- (in fact, also is able to scan numeric +- eqns, which is not
-- in the JSON spec.)
-- Returns the number, and the position of the next character
-- after the number.
-- @param s The string being scanned.
-- @param startPos The position at which to start scanning.
-- @return number, int The extracted number and the position of the next character to scan.
function decode_scanNumber(s,startPos)
local endPos = startPos+1
local stringLen = string.len(s)
local acceptableChars = "+-0123456789.eE"
while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
and endPos<=stringLen
) do
endPos = endPos + 1
end
local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON object into a Lua object.
-- startPos begins at the start of the object.
-- Returns the object and the next starting position.
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return table, int The scanned object as a table and the position of the next character to scan.
function decode_scanObject(s,startPos)
local object = {}
local stringLen = string.len(s)
local key, value
base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
startPos = startPos + 1
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
local curChar = string.sub(s,startPos,startPos)
if (curChar=='}') then
return object,startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
-- Scan the key
key, startPos = decode(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
startPos = decode_scanWhitespace(s,startPos+1)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
value, startPos = decode(s,startPos)
object[key]=value
until false -- infinite loop while key-value pairs are found
end
--- Scans a JSON string from the opening inverted comma or single quote to the
-- end of the string.
-- Returns the string extracted as a Lua string,
-- and the position of the next non-string character
-- (after the closing inverted comma or single quote).
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return string, int The extracted string as a Lua string, and the next character to parse.
function decode_scanString(s,startPos)
base.assert(startPos, 'decode_scanString(..) called without start position')
local startChar = string.sub(s,startPos,startPos)
base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
local escaped = false
local endPos = startPos + 1
local bEnded = false
local stringLen = string.len(s)
repeat
local curChar = string.sub(s,endPos,endPos)
if not escaped then
if curChar==[[\]] then
escaped = true
else
bEnded = curChar==startChar
end
else
-- If we're escaped, we accept the current character come what may
escaped = false
end
endPos = endPos + 1
base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
until bEnded
local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON string skipping all whitespace from the current start position.
-- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
-- @param s The string being scanned
-- @param startPos The starting position where we should begin removing whitespace.
-- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
-- was reached.
function decode_scanWhitespace(s,startPos)
local whitespace=" \n\r\t"
local stringLen = string.len(s)
while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
startPos = startPos + 1
end
return startPos
end
--- Encodes a string to be JSON-compatible.
-- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
-- @param s The string to return as a JSON encoded (i.e. backquoted string)
-- @return The string appropriately escaped.
function encodeString(s)
s = string.gsub(s,'\\','\\\\')
s = string.gsub(s,'"','\\"')
s = string.gsub(s,"'","\\'")
s = string.gsub(s,'\n','\\n')
s = string.gsub(s,'\t','\\t')
return s
end
-- Determines whether the given Lua type is an array or a table / dictionary.
-- We consider any table an array if it has indexes 1..n for its n items, and no
-- other data in the table.
-- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
-- @param t The table to evaluate as an array
-- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
-- the second returned value is the maximum
-- number of indexed elements in the array.
function isArray(t)
-- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
-- (with the possible exception of 'n')
local maxIndex = 0
for k,v in base.pairs(t) do
if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
if (not isEncodable(v)) then return false end -- All array elements must be encodable
maxIndex = math.max(maxIndex,k)
else
if (k=='n') then
if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
else -- Else of (k=='n')
if isEncodable(v) then return false end
end -- End of (k~='n')
end -- End of k,v not an indexed pair
end -- End of loop across all pairs
return true, maxIndex
end
--- Determines whether the given Lua object / table / variable can be JSON encoded. The only
-- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
-- In this implementation, all other types are ignored.
-- @param o The object to examine.
-- @return boolean True if the object should be JSON encoded, false if it should be ignored.
function isEncodable(o)
local t = base.type(o)
return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
end
| apache-2.0 |
AmirPGA/pgahide | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Xarcabard/npcs/Magumo-Yagimo_WW.lua | 3 | 3329 | -----------------------------------
-- Area: Xarcabard
-- NPC: Magumo-Yagimo, W.W.
-- Type: Outpost Conquest Guards
-- !pos 207.548 -24.795 -203.694 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Xarcabard/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VALDEAUNIA;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
binesiyu/hammerspoon | hs/_asm/undocumented/spaces/init.lua | 6 | 22220 | --- === hs._asm.undocumented.spaces ===
---
--- These functions utilize private API's within the OS X internals, and are known to have unpredictable behavior under Mavericks and Yosemite when "Displays have separate Spaces" is checked under the Mission Control system preferences.
---
-- some of the commands can really get you in a bit of a fix, so this file will be mostly wrappers and
-- predefined, common actions.
local internal = require("hs._asm.undocumented.spaces.internal")
local module = {}
local screen = require("hs.screen")
local window = require("hs.window")
local settings = require("hs.settings")
local inspect = require("hs.inspect")
local application = require("hs.application")
-- private variables and methods -----------------------------------------
-- flag is checked to see if certain functions are called from module or from module.raw to prevent doing
-- dangerous/unexpected/unknown things unless explicitly enabled
local _BE_DANGEROUS_FLAG_ = false
local _kMetaTable = {}
_kMetaTable._k = {}
_kMetaTable.__index = function(obj, key)
if _kMetaTable._k[obj] then
if _kMetaTable._k[obj][key] then
return _kMetaTable._k[obj][key]
else
for k,v in pairs(_kMetaTable._k[obj]) do
if v == key then return k end
end
end
end
return nil
end
_kMetaTable.__newindex = function(obj, key, value)
error("attempt to modify a table of constants",2)
return nil
end
_kMetaTable.__pairs = function(obj) return pairs(_kMetaTable._k[obj]) end
_kMetaTable.__tostring = function(obj)
local result = ""
if _kMetaTable._k[obj] then
local width = 0
for k,v in pairs(_kMetaTable._k[obj]) do width = width < #k and #k or width end
for k,v in pairs(_kMetaTable._k[obj]) do
result = result..string.format("%-"..tostring(width).."s %s\n", k, tostring(v))
end
else
result = "constants table missing"
end
return result
end
_kMetaTable.__metatable = _kMetaTable -- go ahead and look, but don't unset this
local _makeConstantsTable = function(theTable)
local results = setmetatable({}, _kMetaTable)
_kMetaTable._k[results] = theTable
return results
end
local reverseWithoutSystemSpaces = function(list)
local results = {}
for i,v in ipairs(list) do
if internal.spaceType(v) ~= internal.types.system then
table.insert(results, 1, v)
end
end
return results
end
local isSpaceSafe = function(spaceID, func)
func = func or "undocumented.spaces"
if not _BE_DANGEROUS_FLAG_ then
local t = internal.spaceType(spaceID)
if t ~= internal.types.fullscreen and t ~= internal.types.tiled and t ~= internal.types.user then
_BE_DANGEROUS_FLAG_ = false
error(func..":must be user-created or fullscreen application space", 3)
end
end
_BE_DANGEROUS_FLAG_ = false
return spaceID
end
local screenMT = hs.getObjectMetatable("hs.screen")
local windowMT = hs.getObjectMetatable("hs.window")
-- Public interface ------------------------------------------------------
module.types = _makeConstantsTable(internal.types)
module.masks = _makeConstantsTable(internal.masks)
-- replicate legacy functions
--- hs._asm.undocumented.spaces.count() -> number
--- Function
--- LEGACY: The number of spaces you currently have.
---
--- Notes:
--- * this function may go away in a future update
---
--- * this functions is included for backwards compatibility. It is not recommended because it worked by indexing the spaces ignoring that fullscreen applications are included in the list twice, and only worked with one monitor. Use `hs._asm.undocumented.spaces.query` or `hs._asm.undocumented.spaces.spacesByScreenUUID`.
module.count = function()
return #reverseWithoutSystemSpaces(module.query(internal.masks.allSpaces))
end
--- hs._asm.undocumented.spaces.currentSpace() -> number
--- Function
--- LEGACY: The index of the space you're currently on, 1-indexed (as usual).
---
--- Notes:
--- * this function may go away in a future update
---
--- * this functions is included for backwards compatibility. It is not recommended because it worked by indexing the spaces, which can be rearranged by the operating system anyways. Use `hs._asm.undocumented.spaces.query` or `hs._asm.undocumented.spaces.spacesByScreenUUID`.
module.currentSpace = function()
local theSpaces = reverseWithoutSystemSpaces(module.query(internal.masks.allSpaces))
local currentID = internal.query(internal.masks.currentSpaces)[1]
for i,v in ipairs(theSpaces) do
if v == currentID then return i end
end
return nil
end
--- hs._asm.undocumented.spaces.moveToSpace(number)
--- Function
--- LEGACY: Switches to the space at the given index, 1-indexed (as usual).
---
--- Notes:
--- * this function may go away in a future update
---
--- * this functions is included for backwards compatibility. It is not recommended because it was never really reliable and worked by indexing the spaces, which can be rearranged by the operating system anyways. Use `hs._asm.undocumented.spaces.changeToSpace`.
module.moveToSpace = function(whichIndex)
local theID = internal.query(internal.masks.allSpaces)[whichIndex]
if theID then
internal._changeToSpace(theID, false)
return true
else
return false
end
end
--- hs._asm.undocumented.spaces.isAnimating([screen]) -> bool
--- Function
--- Returns the state of space changing animation for the specified monitor, or for any monitor if no parameter is specified.
---
--- Parameters:
--- * screen - an optional hs.screen object specifying the specific monitor to check the animation status for.
---
--- Returns:
--- * a boolean value indicating whether or not a space changing animation is currently active.
---
--- Notes:
--- * This function can be used in `hs.eventtap` based space changing functions to determine when to release the mouse and key events.
---
--- * This function is also added to the `hs.screen` object metatable so that you can check a specific screen's animation status with `hs.screen:spacesAnimating()`.
module.isAnimating = function(...)
local args = table.pack(...)
if args.n == 0 then
local isAnimating = false
for i,v in ipairs(screen.allScreens()) do
isAnimating = isAnimating or internal.screenUUIDisAnimating(internal.UUIDforScreen(v))
end
return isAnimating
elseif args.n == 1 then
return internal.screenUUIDisAnimating(internal.UUIDforScreen(args[1]))
else
error("isAnimating:invalid argument, none or hs.screen object expected", 2)
end
end
module.spacesByScreenUUID = function(...)
local args = table.pack(...)
if args.n == 0 or args.n == 1 then
local masks = args[1] or internal.masks.allSpaces
local theSpaces = module.query(masks)
local holding = {}
for i,v in ipairs(theSpaces) do
local myScreen = internal.spaceScreenUUID(v) or "screenUndefined"
if not holding[myScreen] then holding[myScreen] = {} end
table.insert(holding[myScreen], v)
end
return holding
else
error("spacesByScreenUUID:invalid argument, none or integer expected", 2)
end
end
-- need to make sure its a user accessible space
module.changeToSpace = function(...)
local args = table.pack(...)
if args.n == 1 or args.n == 2 then
local spaceID = isSpaceSafe(args[1], "changeToSpace")
if type(args[2]) == "boolean" then resetDock = args[2] else resetDock = true end
local fromID, uuid = 0, internal.spaceScreenUUID(spaceID)
for i, v in ipairs(module.query(internal.masks.currentSpaces)) do
if uuid == internal.spaceScreenUUID(v) then
fromID = v
break
end
end
if fromID == 0 then
error("changeToSpace:unable to identify screen for space id "..spaceID, 2)
end
-- this is where you could do some sort of animation with the transform functions
-- may add that in the future
internal.disableUpdates()
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) + 1)
end
end
internal.spaceLevel(spaceID, internal.spaceLevel(spaceID) + 1)
-- doesn't seem to be necessary, _changeToSpace does it for us, though you would need
-- it if you did any animation for the switch
-- internal.showSpaces(spaceID)
internal._changeToSpace(spaceID)
internal.hideSpaces(fromID)
internal.spaceLevel(spaceID, internal.spaceLevel(spaceID) - 1)
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) - 1)
end
end
internal.enableUpdates()
if resetDock then hs.execute("killall Dock") end
else
error("changeToSpace:invalid argument, spaceID and optional boolean expected", 2)
end
return internal.query(internal.masks.currentSpaces)
end
module.mainScreenUUID = function(...)
local UUID = internal.mainScreenUUID(...)
if #UUID ~= 36 then -- on one screen machines, it returns "Main" which doesn't work for spaceCreate
UUID = internal.spaceScreenUUID(internal.activeSpace())
end
return UUID
end
-- -need a way to determine/specify which screen
module.createSpace = function(...)
local args = table.pack(...)
if args.n <= 2 then
local uuid, resetDock
if type(args[1]) == "string" then uuid = args[1] else uuid = module.mainScreenUUID() end
if type(args[#args]) == "boolean" then resetDock = args[#args] else resetDock = true end
local newID = internal.createSpace(uuid)
if resetDock then hs.execute("killall Dock") end
return newID
else
error("createSpace:invalid argument, screenUUID and optional boolean expected", 2)
end
end
-- -need to make sure no windows are only there
-- -need to make sure its a user window
-- ?check for how to do tiled/fullscreen?
module.removeSpace = function(...)
local args = table.pack(...)
if args.n == 1 or args.n == 2 then
local _Are_We_Being_Dangerous_ = _BE_DANGEROUS_FLAG_
local spaceID = isSpaceSafe(args[1], "removeSpace")
local resetDock
if type(args[2]) == "boolean" then resetDock = args[2] else resetDock = true end
if internal.spaceType(spaceID) ~= internal.types.user then
error("removeSpace:you can only remove user created spaces", 2)
end
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if spaceID == v then
error("removeSpace:you can't remove one of the currently active spaces", 2)
end
end
local targetUUID = internal.spaceScreenUUID(spaceID)
local sameScreenSpaces = module.spacesByScreenUUID()[targetUUID]
local userSpacesCount = 0
for i,v in ipairs(sameScreenSpaces) do
if internal.spaceType(v) == internal.types.user then
userSpacesCount = userSpacesCount + 1
end
end
if userSpacesCount < 2 then
error("removeSpace:there must be at least one user space on each screen", 2)
end
-- Probably not necessary, with above checks, but if I figure out how to safely
-- "remove" fullscreen/tiled spaces, I may remove them for experimenting
_BE_DANGEROUS_FLAG_ = _Are_We_Being_Dangerous_
-- check for windows which need to be moved
local theWindows = {}
for i, v in ipairs(module.allWindowsForSpace(spaceID)) do if v:id() then table.insert(theWindows, v:id()) end end
-- get id of screen to move them to
local baseID = 0
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
baseID = v
break
end
end
for i,v in ipairs(theWindows) do
-- only add windows that exist in only one place
if #internal.windowsOnSpaces(v) == 1 then
internal.windowsAddTo(v, baseID)
end
end
internal.windowsRemoveFrom(theWindows, spaceID)
internal._removeSpace(spaceID)
if resetDock then hs.execute("killall Dock") end
else
error("removeSpace:invalid argument, spaceID and optional boolean expected", 2)
end
end
module.allWindowsForSpace = function(...)
local args = table.pack(...)
if args.n == 1 then
local ok, spaceID = pcall(isSpaceSafe, args[1], "allWindowsForSpace")
if not ok then
if internal.spaceName(args[1]) == "dashboard" then spaceID = args[1] else error(spaceID, 2) end
end
local isCurrent, windowIDs = false, {}
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if v == spaceID then
isCurrent = true
break
end
end
if isCurrent then
windowIDs = window.allWindows()
else
local targetUUID = internal.spaceScreenUUID(spaceID)
local baseID = 0
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
baseID = v
break
end
end
internal.disableUpdates()
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) + 1)
end
end
internal.spaceLevel(baseID, internal.spaceLevel(baseID) + 1)
internal._changeToSpace(spaceID)
windowIDs = window.allWindows()
internal.hideSpaces(spaceID)
internal._changeToSpace(baseID)
internal.spaceLevel(baseID, internal.spaceLevel(baseID) - 1)
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) - 1)
end
end
internal.enableUpdates()
end
local realWindowIDs = {}
for i,v in ipairs(windowIDs) do
if v:id() then
for j,k in ipairs(internal.windowsOnSpaces(v:id())) do
if k == spaceID then
table.insert(realWindowIDs, v)
end
end
end
end
windowIDs = realWindowIDs
return windowIDs
else
error("allWindowsForSpace:invalid argument, spaceID expected", 2)
end
end
module.windowOnSpaces = function(...)
local args = table.pack(...)
if args.n == 1 then
windowIDs = internal.windowsOnSpaces(args[1])
return windowIDs
else
error("windowOnSpaces:invalid argument, windowID expected", 2)
end
end
module.moveWindowToSpace = function(...)
local args = table.pack(...)
if args.n == 2 then
local windowID = args[1]
local spaceID = isSpaceSafe(args[2], "moveWindowToSpace")
local currentSpaces = internal.windowsOnSpaces(windowID)
if #currentSpaces == 0 then
error("moveWindowToSpace:no spaceID found for window", 2)
elseif #currentSpaces > 1 then
error("moveWindowToSpace:window on multiple spaces", 2)
end
if currentSpaces[1] ~= spaceID then
internal.windowsAddTo(windowID, spaceID)
internal.windowsRemoveFrom(windowID, currentSpaces[1])
end
return internal.windowsOnSpaces(windowID)[1]
else
error("moveWindowToSpace:invalid argument, windowID and spaceID expected", 2)
end
end
module.layout = function()
local results = {}
for i,v in ipairs(internal.details()) do
local screenID = v["Display Identifier"]
if screenID == "Main" then
screenID = module.mainScreenUUID()
end
results[screenID] = {}
for j,k in ipairs(v.Spaces) do
table.insert(results[screenID], k.ManagedSpaceID)
end
end
return results
end
module.query = function(...)
local args = table.pack(...)
if args.n <= 2 then
local mask, flatten = internal.masks.allSpaces, true
if type(args[1]) == "number" then mask = args[1] end
if type(args[#args]) == "boolean" then flatten = args[#args] end
local results = internal.query(mask)
if not flatten then
return results
else
local userWants, seen = {}, {}
for i, v in ipairs(results) do
if not seen[v] then
seen[v] = true
table.insert(userWants, v)
end
end
return userWants
end
else
error("query:invalid argument, mask and optional boolean expected", 2)
end
end
-- map the basic functions to the main module spaceID
module.screensHaveSeparateSpaces = internal.screensHaveSeparateSpaces
module.activeSpace = internal.activeSpace
module.spaceType = internal.spaceType
module.spaceName = internal.spaceName
module.spaceOwners = internal.spaceOwners
module.spaceScreenUUID = internal.spaceScreenUUID
-- generate debugging information
module.debug = {}
module.debug.layout = function(...) return inspect(internal.details(...)) end
module.debug.report = function(...)
local mask = 7 -- user accessible spaces
local _ = table.pack(...)[1]
if type(_) == "boolean" and _ then
mask = 31 -- I think this gets user and "system" spaces like expose, etc.
elseif type(_) == "boolean" then
mask = 917519 -- I think this gets *everything*, but it may change as I dig
elseif type(_) == "number" then
mask = _ -- user specified mask
elseif table.pack(...).n ~= 0 then
error("debugReport:bad mask type provided, expected number", 2)
end
local list, report = module.query(mask), ""
report = "Screens have separate spaces: "..tostring(internal.screensHaveSeparateSpaces()).."\n"..
"Spaces for mask "..string.format("0x%08x", mask)..": "..(inspect(internal.query(mask)):gsub("%s+"," "))..
"\n\n"
for i,v in ipairs(list) do
report = report..module.debug.spaceInfo(v).."\n"
end
-- see if mask included any of the users accessible spaces flag
if (mask & (1 << 2) ~= 0) then report = report.."\nLayout: "..inspect(internal.details()).."\n" end
return report
end
module.debug.spaceInfo = function(v)
local results =
"Space: "..v.." ("..inspect(internal.spaceName(v))..")\n"..
" Type: "..(module.types[internal.spaceType(v)] and module.types[internal.spaceType(v)] or "-- unknown --")
.." ("..internal.spaceType(v)..")\n"..
" Level: ".. internal.spaceLevel(v).."\n"..
" CompatID: ".. internal.spaceCompatID(v).."\n"..
" Screen: ".. inspect(internal.spaceScreenUUID(v)).."\n"..
" Shape: "..(inspect(internal.spaceShape(v)):gsub("%s+"," ")).."\n"..
" MShape: "..(inspect(internal.spaceManagedShape(v)):gsub("%s+"," ")).."\n"..
" Transform: "..(inspect(internal.spaceTransform(v)):gsub("%s+"," ")).."\n"..
" Values: "..(inspect(internal.spaceValues(v)):gsub("%s+"," ")).."\n"..
" Owners: "..(inspect(internal.spaceOwners(v)):gsub("%s+"," ")).."\n"
if #internal.spaceOwners(v) > 0 then
local apps = {}
for i,v in ipairs(internal.spaceOwners(v)) do
table.insert(apps, (application.applicationForPID(v) and
application.applicationForPID(v):title() or "n/a"))
end
results = results.." : "..(inspect(apps):gsub("%s+"," ")).."\n"
end
return results
end
-- extend built in modules
screenMT.__index.spaces = function(obj) return module.spacesByScreenUUID()[internal.UUIDforScreen(obj)] end
screenMT.__index.spacesUUID = internal.UUIDforScreen
screenMT.__index.spacesAnimating = function(obj) return internal.screenUUIDisAnimating(internal.UUIDforScreen(obj)) end
windowMT.__index.spaces = function(obj) return obj:id() and internal.windowsOnSpaces(obj:id()) or nil end
windowMT.__index.spacesMoveTo = function(obj, ...)
if obj:id() then
module.moveWindowToSpace(obj:id(), ...)
return obj
end
return nil
end
-- add raw subtable if the user has enabled it
if settings.get("_ASMundocumentedSpacesRaw") then
module.raw = internal
module.raw.changeToSpace = function(...)
_BE_DANGEROUS_FLAG_ = true
local result = module.changeToSpace(...)
_BE_DANGEROUS_FLAG_ = false -- should be already, but just in case
return result
end
module.raw.removeSpace = function(...)
_BE_DANGEROUS_FLAG_ = true
local result = module.changeToSpace(...)
_BE_DANGEROUS_FLAG_ = false -- should be already, but just in case
return result
end
module.raw.allWindowsForSpace = function(...)
_BE_DANGEROUS_FLAG_ = true
local result = module.allWindowsForSpace(...)
_BE_DANGEROUS_FLAG_ = false -- should be already, but just in case
return result
end
end
-- Return Module Object --------------------------------------------------
return module
| mit |
RebootRevival/FFXI_Test | scripts/zones/Apollyon/mobs/Borametz.lua | 23 | 1130 | -----------------------------------
-- Area: Apollyon NE
-- NPC: Borametz
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local mobID = mob:getID();
-- print(mobID);
-- local mobX = mob:getXPos();
--local mobY = mob:getYPos();
--local mobZ = mob:getZPos();
if (mobID ==16933048) then -- time T1
GetNPCByID(16932864+118):setPos(452,-1,30);
GetNPCByID(16932864+118):setStatus(STATUS_NORMAL);
elseif (mobID ==16933052) then -- recover
GetNPCByID(16932864+120):setPos(470,-1,30);
GetNPCByID(16932864+120):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Northern_San_dOria/npcs/Malfine.lua | 3 | 1036 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Malfine
-- Type: Standard Dialogue NPC
-- @zone 231
-- !pos 136.943 0.000 132.305
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MALFINE_DIALOG);
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 |
JunichiWatanuki/wireshark | test/lua/field.lua | 20 | 6064 | -- test script for wslua Field/FieldInfo functions
-- use with dhcp.pcap in test/captures directory
------------- helper funcs ------------
local packet_count = 0
local function incPktCount(name)
packet_count = packet_count + 1
end
local function testing(...)
print("---- Testing "..tostring(...).." for packet #"..packet_count.." ----")
end
local function test(name, ...)
io.stdout:write("test "..name.."-"..packet_count.."...")
if (...) == true then
io.stdout:write("passed\n")
else
io.stdout:write("failed!\n")
error(name.." test failed!")
end
end
local function toMacAddr(addrhex)
return addrhex:gsub("..","%0:"):sub(1,-2)
end
-- the following are so we can use pcall (which needs a function to call)
local function makeField(name)
local foo = Field.new(name)
return true
end
local function makeFieldInfo(field)
local foo = field()
return true
end
local function setFieldInfo(finfo,name,value)
finfo[name] = value
return true
end
local function getFieldInfo(finfo,name)
local foo = finfo[name]
return true
end
--------------------------
testing("Field")
test("Field.new-0",pcall(makeField,"ip.src"))
test("Field.new-1",not pcall(makeField,"FooBARhowdy"))
test("Field.new-2",not pcall(makeField))
test("Field.new-3",not pcall(makeField,""))
test("Field.new-4",not pcall(makeField,"IP.SRC"))
-- declare some field extractors
local f_frame_proto = Field.new("frame.protocols")
local f_eth_src = Field.new("eth.src")
local f_eth_dst = Field.new("eth.dst")
local f_eth_mac = Field.new("eth.addr")
local f_ip_src = Field.new("ip.src")
local f_ip_dst = Field.new("ip.dst")
local f_udp_srcport = Field.new("udp.srcport")
local f_udp_dstport = Field.new("udp.dstport")
local f_bootp_hw = Field.new("bootp.hw.mac_addr")
local f_bootp_opt = Field.new("bootp.option.type")
test("Field__tostring-1", tostring(f_frame_proto) == "frame.protocols")
test("Field.name-1", f_frame_proto.name == "frame.protocols")
test("Field.name-2", f_eth_src.name == "eth.src")
test("Field.display-1", f_frame_proto.display == "Protocols in frame")
test("Field.display-2", f_eth_src.display == "Source")
test("Field.type-1", f_frame_proto.type == ftypes.STRING)
test("Field.type-2", f_eth_src.type == ftypes.ETHER)
test("Field.type-3", f_ip_src.type == ftypes.IPv4)
test("Field.type-4", f_udp_srcport.type == ftypes.UINT16)
test("Field.type-5", f_bootp_opt.type == ftypes.UINT8)
-- make sure can't create a FieldInfo outside tap
test("Field__call-1",not pcall(makeFieldInfo,f_eth_src))
local tap = Listener.new()
--------------------------
function tap.packet(pinfo,tvb)
incPktCount()
testing("Field")
test("Field__tostring-2", tostring(f_frame_proto) == "frame.protocols")
-- make sure can't create a Field inside tap
test("Field.new-5",not pcall(makeField,"ip.src"))
test("Field__call-2",pcall(makeFieldInfo,f_eth_src))
test("Field.name-3", f_frame_proto.name == "frame.protocols")
test("Field.name-4", f_eth_src.name == "eth.src")
test("Field.display-3", f_frame_proto.display == "Protocols in frame")
test("Field.display-4", f_eth_src.display == "Source")
test("Field.type-6", f_frame_proto.type == ftypes.STRING)
test("Field.type-7", f_eth_src.type == ftypes.ETHER)
test("Field.type-8", f_ip_src.type == ftypes.IPv4)
test("Field.type-9", f_udp_srcport.type == ftypes.UINT16)
test("Field.type-10", f_bootp_opt.type == ftypes.UINT8)
testing("FieldInfo")
local finfo_udp_srcport = f_udp_srcport()
test("FieldInfo.name-1", finfo_udp_srcport.name == "udp.srcport")
test("FieldInfo.type-1", finfo_udp_srcport.type == ftypes.UINT16)
test("FieldInfo.little_endian-1", finfo_udp_srcport.little_endian == false)
-- the following should be true, but UDP doesn't set it right?
-- test("FieldInfo.big_endian-1", finfo_udp_srcport.big_endian == true)
test("FieldInfo.is_url-1", finfo_udp_srcport.is_url == false)
test("FieldInfo.offset-1", finfo_udp_srcport.offset == 34)
test("FieldInfo.source-1", finfo_udp_srcport.source == tvb)
-- check ether addr
local fi_eth_src = f_eth_src()
test("FieldInfo.type-2", fi_eth_src.type == ftypes.ETHER)
test("FieldInfo.range-0",pcall(getFieldInfo,fi_eth_src,"range"))
local eth_macs = { f_eth_mac() }
local eth_src1 = tostring(f_eth_src().range)
local eth_src2 = tostring(tvb:range(6,6))
local eth_src3 = tostring(eth_macs[2].tvb)
test("FieldInfo.range-1", eth_src1 == eth_src2)
test("FieldInfo.range-2", eth_src1 == eth_src3)
test("FieldInfo.range-3",not pcall(setFieldInfo,fi_eth_src,"range",3))
test("FieldInfo.generated-1", f_frame_proto().generated == true)
test("FieldInfo.generated-2", eth_macs[2].generated == false)
test("FieldInfo.generated-3",not pcall(setFieldInfo,fi_eth_src,"generated",3))
test("FieldInfo.name-1", fi_eth_src.name == "eth.src")
test("FieldInfo.name-2",not pcall(setFieldInfo,fi_eth_src,"name","3"))
test("FieldInfo.label-1", fi_eth_src.label == tostring(fi_eth_src))
test("FieldInfo.label-2", fi_eth_src.label == toMacAddr(eth_src1))
test("FieldInfo.label-3",not pcall(setFieldInfo,fi_eth_src,"label","3"))
test("FieldInfo.display-1", select(1, string.find(fi_eth_src.display, toMacAddr(eth_src1))) ~= nil)
test("FieldInfo.display-2",not pcall(setFieldInfo,fi_eth_src,"display","3"))
test("FieldInfo.eq-1", eth_macs[2] == select(2, f_eth_mac()))
test("FieldInfo.eq-2", eth_macs[1] ~= fi_eth_src)
test("FieldInfo.eq-3", eth_macs[1] == f_eth_dst())
test("FieldInfo.offset-1", eth_macs[1].offset == 0)
test("FieldInfo.offset-2", -fi_eth_src == 6)
test("FieldInfo.offset-3",not pcall(setFieldInfo,fi_eth_src,"offset","3"))
test("FieldInfo.len-1", fi_eth_src.len == 6)
test("FieldInfo.len-2",not pcall(setFieldInfo,fi_eth_src,"len",6))
if packet_count == 4 then
print("\n-----------------------------\n")
print("All tests passed!\n\n")
end
end
| gpl-2.0 |
chen0031/sysdig | userspace/sysdig/chisels/iobytes_net.lua | 18 | 1667 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
-- Chisel description
description = "Counts the total bytes read from and written to the network, and prints the result every second";
short_description = "Show total network I/O bytes";
category = "Net";
-- Chisel argument list
args = {}
tot = 0
totin = 0
totout = 0
-- Initialization callback
function on_init()
-- Request the fields
fbytes = chisel.request_field("evt.rawarg.res")
ftime = chisel.request_field("evt.time.s")
fisread = chisel.request_field("evt.is_io_read")
-- set the filter
chisel.set_filter("evt.is_io=true and (fd.type=ipv4 or fd.type=ipv6)")
chisel.set_interval_s(1)
return true
end
-- Event parsing callback
function on_event()
bytes = evt.field(fbytes)
isread = evt.field(fisread)
if bytes ~= nil and bytes > 0 then
tot = tot + bytes
if isread then
totin = totin + bytes
else
totout = totout + bytes
end
end
return true
end
function on_interval(delta)
etime = evt.field(ftime)
print(etime .. " in:" .. totin .. " out:" .. totout .. " tot:" .. tot)
tot = 0
totin = 0
totout = 0
return true
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Waughroon_Shrine/npcs/Burning_Circle.lua | 8 | 2249 | -----------------------------------
-- Area: Waughroon Shrine
-- NPC: Burning Circle
-- Waughroon Shrine Burning Circle
-- !pos -345 104 -260 144
-------------------------------------
package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Waughroon_Shrine/TextIDs");
---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad"
---- 1: Worms Turn
---- 2: Grimshell Shocktroopers
---- 3: On my Way
---- 4: Thief in Norg
---- 5: 3, 2, 1
---- 6: Shattering Stars (RDM)
---- 7: Shattering Stars (THF)
---- 8: Shattering Stars (BST)
---- 9: Birds of the feather
---- 10: Crustacean Conundrum
---- 11: Grove Gardians
---- 12: The Hills are alive
---- 13: Royal Jelly
---- 14: The Final Bout
---- 15: Up in arms
---- 16: Copy Cat
---- 17: Operation Desert Swarm
---- 18: Prehistoric Pigeons
---- 19: The Palborough Project
---- 20: Shell Shocked
---- 21: Beyond infinity
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
openwrt-es/openwrt-luci | libs/luci-lib-ipkg/luasrc/model/ipkg.lua | 16 | 5309 | -- Copyright 2008-2011 Jo-Philipp Wich <jow@openwrt.org>
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local os = require "os"
local io = require "io"
local fs = require "nixio.fs"
local util = require "luci.util"
local type = type
local pairs = pairs
local error = error
local table = table
local ipkg = "opkg --force-removal-of-dependent-packages --force-overwrite --nocase"
local icfg = "/etc/opkg.conf"
module "luci.model.ipkg"
-- Internal action function
local function _action(cmd, ...)
local cmdline = { ipkg, cmd }
local k, v
for k, v in pairs({...}) do
cmdline[#cmdline+1] = util.shellquote(v)
end
local c = "%s >/tmp/opkg.stdout 2>/tmp/opkg.stderr" % table.concat(cmdline, " ")
local r = os.execute(c)
local e = fs.readfile("/tmp/opkg.stderr")
local o = fs.readfile("/tmp/opkg.stdout")
fs.unlink("/tmp/opkg.stderr")
fs.unlink("/tmp/opkg.stdout")
return r, o or "", e or ""
end
-- Internal parser function
local function _parselist(rawdata)
if type(rawdata) ~= "function" then
error("OPKG: Invalid rawdata given")
end
local data = {}
local c = {}
local l = nil
for line in rawdata do
if line:sub(1, 1) ~= " " then
local key, val = line:match("(.-): ?(.*)%s*")
if key and val then
if key == "Package" then
c = {Package = val}
data[val] = c
elseif key == "Status" then
c.Status = {}
for j in val:gmatch("([^ ]+)") do
c.Status[j] = true
end
else
c[key] = val
end
l = key
end
else
-- Multi-line field
c[l] = c[l] .. "\n" .. line
end
end
return data
end
-- Internal lookup function
local function _lookup(cmd, pkg)
local cmdline = { ipkg, cmd }
if pkg then
cmdline[#cmdline+1] = util.shellquote(pkg)
end
-- OPKG sometimes kills the whole machine because it sucks
-- Therefore we have to use a sucky approach too and use
-- tmpfiles instead of directly reading the output
local tmpfile = os.tmpname()
os.execute("%s >%s 2>/dev/null" %{ table.concat(cmdline, " "), tmpfile })
local data = _parselist(io.lines(tmpfile))
os.remove(tmpfile)
return data
end
function info(pkg)
return _lookup("info", pkg)
end
function status(pkg)
return _lookup("status", pkg)
end
function install(...)
return _action("install", ...)
end
function installed(pkg)
local p = status(pkg)[pkg]
return (p and p.Status and p.Status.installed)
end
function remove(...)
return _action("remove", ...)
end
function update()
return _action("update")
end
function upgrade()
return _action("upgrade")
end
-- List helper
local function _list(action, pat, cb)
local cmdline = { ipkg, action }
if pat then
cmdline[#cmdline+1] = util.shellquote(pat)
end
local fd = io.popen(table.concat(cmdline, " "))
if fd then
local name, version, sz, desc
while true do
local line = fd:read("*l")
if not line then break end
name, version, sz, desc = line:match("^(.-) %- (.-) %- (.-) %- (.+)")
if not name then
name, version, sz = line:match("^(.-) %- (.-) %- (.+)")
desc = ""
end
if name and version then
if #version > 26 then
version = version:sub(1,21) .. ".." .. version:sub(-3,-1)
end
cb(name, version, sz, desc)
end
name = nil
version = nil
sz = nil
desc = nil
end
fd:close()
end
end
function list_all(pat, cb)
_list("list --size", pat, cb)
end
function list_installed(pat, cb)
_list("list_installed --size", pat, cb)
end
function find(pat, cb)
_list("find --size", pat, cb)
end
function overlay_root()
local od = "/"
local fd = io.open(icfg, "r")
if fd then
local ln
repeat
ln = fd:read("*l")
if ln and ln:match("^%s*option%s+overlay_root%s+") then
od = ln:match("^%s*option%s+overlay_root%s+(%S+)")
local s = fs.stat(od)
if not s or s.type ~= "dir" then
od = "/"
end
break
end
until not ln
fd:close()
end
return od
end
function compare_versions(ver1, comp, ver2)
if not ver1 or not ver2
or not comp or not (#comp > 0) then
error("Invalid parameters")
return nil
end
-- correct compare string
if comp == "<>" or comp == "><" or comp == "!=" or comp == "~=" then comp = "~="
elseif comp == "<=" or comp == "<" or comp == "=<" then comp = "<="
elseif comp == ">=" or comp == ">" or comp == "=>" then comp = ">="
elseif comp == "=" or comp == "==" then comp = "=="
elseif comp == "<<" then comp = "<"
elseif comp == ">>" then comp = ">"
else
error("Invalid compare string")
return nil
end
local av1 = util.split(ver1, "[%.%-]", nil, true)
local av2 = util.split(ver2, "[%.%-]", nil, true)
local max = table.getn(av1)
if (table.getn(av1) < table.getn(av2)) then
max = table.getn(av2)
end
for i = 1, max, 1 do
local s1 = av1[i] or ""
local s2 = av2[i] or ""
-- first "not equal" found return true
if comp == "~=" and (s1 ~= s2) then return true end
-- first "lower" found return true
if (comp == "<" or comp == "<=") and (s1 < s2) then return true end
-- first "greater" found return true
if (comp == ">" or comp == ">=") and (s1 > s2) then return true end
-- not equal then return false
if (s1 ~= s2) then return false end
end
-- all equal and not compare greater or lower then true
return not (comp == "<" or comp == ">")
end
| apache-2.0 |
TheRikyHUN/fooniks | resources/admin/server/admin_server.lua | 2 | 43995 | --[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* admin_server.lua
*
* Original File by lil_Toady
*
**************************************]]
_root = getRootElement()
_types = { "player", "team", "vehicle", "resource", "bans", "server", "admin" }
_settings = nil
aPlayers = {}
aLogMessages = {}
aInteriors = {}
aStats = {}
aReports = {}
aWeathers = {}
function notifyPlayerLoggedIn(player)
outputChatBox ( "Press 'p' to open your admin panel", player )
local unread = 0
for _, msg in ipairs ( aReports ) do
unread = unread + ( msg.read and 0 or 1 )
end
if unread > 0 then
outputChatBox( unread .. " unread Admin message" .. ( unread==1 and "" or "s" ), player, 255, 0, 0 )
end
end
addEventHandler ( "onResourceStart", _root, function ( resource )
if ( resource ~= getThisResource() ) then
for id, player in ipairs(getElementsByType("player")) do
if ( hasObjectPermissionTo ( player, "general.tab_resources" ) ) then
triggerClientEvent ( player, "aClientResourceStart", _root, getResourceName ( resource ) )
end
end
return
end
_settings = xmlLoadFile ( "conf\\settings.xml" )
if ( not _settings ) then
_settings = xmlCreateFile ( "conf\\settings.xml", "main" )
xmlSaveFile ( _settings )
end
aSetupACL()
aSetupCommands()
for id, player in ipairs ( getElementsByType ( "player" ) ) do
aPlayerInitialize ( player )
if ( hasObjectPermissionTo ( player, "general.adminpanel" ) ) then
notifyPlayerLoggedIn(player)
end
end
local node = xmlLoadFile ( "conf\\interiors.xml" )
if ( node ) then
local interiors = 0
while ( xmlFindChild ( node, "interior", interiors ) ) do
local interior = xmlFindChild ( node, "interior", interiors )
interiors = interiors + 1
aInteriors[interiors] = {}
aInteriors[interiors]["world"] = tonumber ( xmlNodeGetAttribute ( interior, "world" ) )
aInteriors[interiors]["id"] = xmlNodeGetAttribute ( interior, "id" )
aInteriors[interiors]["x"] = xmlNodeGetAttribute ( interior, "posX" )
aInteriors[interiors]["y"] = xmlNodeGetAttribute ( interior, "posY" )
aInteriors[interiors]["z"] = xmlNodeGetAttribute ( interior, "posZ" )
aInteriors[interiors]["r"] = xmlNodeGetAttribute ( interior, "rot" )
end
xmlUnloadFile ( node )
end
local node = xmlLoadFile ( "conf\\stats.xml" )
if ( node ) then
local stats = 0
while ( xmlFindChild ( node, "stat", stats ) ) do
local stat = xmlFindChild ( node, "stat", stats )
local id = tonumber ( xmlNodeGetAttribute ( stat, "id" ) )
local name = xmlNodeGetAttribute ( stat, "name" )
aStats[id] = name
stats = stats + 1
end
xmlUnloadFile ( node )
end
local node = xmlLoadFile ( "conf\\weathers.xml" )
if ( node ) then
local weathers = 0
while ( xmlFindChild ( node, "weather", weathers ) ~= false ) do
local weather = xmlFindChild ( node, "weather", weathers )
local id = tonumber ( xmlNodeGetAttribute ( weather, "id" ) )
local name = xmlNodeGetAttribute ( weather, "name" )
aWeathers[id] = name
weathers = weathers + 1
end
xmlUnloadFile ( node )
end
local node = xmlLoadFile ( "conf\\reports.xml" )
if ( node ) then
local messages = 0
while ( xmlFindChild ( node, "message", messages ) ) do
subnode = xmlFindChild ( node, "message", messages )
local author = xmlFindChild ( subnode, "author", 0 )
local subject = xmlFindChild ( subnode, "subject", 0 )
local category = xmlFindChild ( subnode, "category", 0 )
local text = xmlFindChild ( subnode, "text", 0 )
local time = xmlFindChild ( subnode, "time", 0 )
local read = ( xmlFindChild ( subnode, "read", 0 ) ~= false )
local id = #aReports + 1
aReports[id] = {}
if ( author ) then aReports[id].author = xmlNodeGetValue ( author )
else aReports[id].author = "" end
if ( category ) then aReports[id].category = xmlNodeGetValue ( category )
else aReports[id].category = "" end
if ( subject ) then aReports[id].subject = xmlNodeGetValue ( subject )
else aReports[id].subject = "" end
if ( text ) then aReports[id].text = xmlNodeGetValue ( text )
else aReports[id].text = "" end
if ( time ) then aReports[id].time = xmlNodeGetValue ( time )
else aReports[id].time = "" end
aReports[id].read = read
messages = messages + 1
end
-- Remove duplicates
local a = 1
while a <= #aReports do
local b = a + 1
while b <= #aReports do
if table.cmp( aReports[a], aReports[b] ) then
table.remove( aReports, b )
b = b - 1
end
b = b + 1
end
a = a + 1
end
-- Upgrade time from '4/9 5:9' to '2009-09-04 05:09'
for id, rep in ipairs ( aReports ) do
if string.find( rep.time, "/" ) then
local monthday, month, hour, minute = string.match( rep.time, "^(.-)/(.-) (.-):(.-)$" )
rep.time = string.format( '%04d-%02d-%02d %02d:%02d', 2009, month + 1, monthday, hour, minute )
end
end
-- Sort messages by time
table.sort(aReports, function(a,b) return(a.time < b.time) end)
-- Limit number of messages
if tonumber(get('maxmsgs')) then
while #aReports > tonumber(get('maxmsgs')) do
table.remove( aReports, 1 )
end
end
end
local node = xmlLoadFile ( "conf\\messages.xml" )
if ( node ) then
for id, type in ipairs ( _types ) do
local subnode = xmlFindChild ( node, type, 0 )
if ( subnode ) then
aLogMessages[type] = {}
local groups = 0
while ( xmlFindChild ( subnode, "group", groups ) ) do
local group = xmlFindChild ( subnode, "group", groups )
local action = xmlNodeGetAttribute ( group, "action" )
local r = tonumber ( xmlNodeGetAttribute ( group, "r" ) )
local g = tonumber ( xmlNodeGetAttribute ( group, "g" ) )
local b = tonumber ( xmlNodeGetAttribute ( group, "b" ) )
aLogMessages[type][action] = {}
aLogMessages[type][action]["r"] = r or 0
aLogMessages[type][action]["g"] = g or 255
aLogMessages[type][action]["b"] = b or 0
if ( xmlFindChild ( group, "all", 0 ) ) then aLogMessages[type][action]["all"] = xmlNodeGetValue ( xmlFindChild ( group, "all", 0 ) ) end
if ( xmlFindChild ( group, "admin", 0 ) ) then aLogMessages[type][action]["admin"] = xmlNodeGetValue ( xmlFindChild ( group, "admin", 0 ) ) end
if ( xmlFindChild ( group, "player", 0 ) ) then aLogMessages[type][action]["player"] = xmlNodeGetValue ( xmlFindChild ( group, "player", 0 ) ) end
if ( xmlFindChild ( group, "log", 0 ) ) then aLogMessages[type][action]["log"] = xmlNodeGetValue ( xmlFindChild ( group, "log", 0 ) ) end
groups = groups + 1
end
end
end
xmlUnloadFile ( node )
end
end )
addEventHandler ( "onResourceStop", _root, function ( resource )
if ( resource ~= getThisResource() ) then
for id, player in ipairs(getElementsByType("player")) do
if ( hasObjectPermissionTo ( player, "general.tab_resources" ) ) then
triggerClientEvent ( player, "aClientResourceStop", _root, getResourceName ( resource ) )
end
end
else
local node = xmlLoadFile ( "conf\\reports.xml" )
if ( node ) then
while ( xmlFindChild ( node, "message", 0 ) ~= false ) do
local subnode = xmlFindChild ( node, "message", 0 )
xmlDestroyNode ( subnode )
end
else
node = xmlCreateFile ( "conf\\reports.xml", "messages" )
end
for id, message in ipairs ( aReports ) do
local subnode = xmlCreateChild ( node, "message" )
for key, value in pairs ( message ) do
if ( value ) then
xmlNodeSetValue ( xmlCreateChild ( subnode, key ), tostring ( value ) )
end
end
end
xmlSaveFile ( node )
xmlUnloadFile ( node )
end
aclSave ()
end )
function aGetSetting ( setting )
local result = xmlFindChild ( _settings, tostring ( setting ), 0 )
if ( result ) then
result = xmlNodeGetValue ( result )
if ( result == "true" ) then return true
elseif ( result == "false" ) then return false
else return result end
end
return false
end
function aSetSetting ( setting, value )
local node = xmlFindChild ( _settings, tostring ( setting ), 0 )
if ( not node ) then
node = xmlCreateChild ( _settings, tostring ( setting ) )
end
xmlNodeSetValue ( node, tostring ( value ) )
xmlSaveFile ( _settings )
end
function aRemoveSetting ( setting )
local node = xmlFindChild ( _settings, tostring ( setting ), 0 )
if ( node ) then
xmlDestroyNode ( node )
end
xmlSaveFile ( _settings )
end
function iif ( cond, arg1, arg2 )
if ( cond ) then
return arg1
end
return arg2
end
function getVehicleOccupants ( vehicle )
local tableOut = {}
local seats = getVehicleMaxPassengers ( vehicle ) + 1
for i = 0, seats do
local passenger = getVehicleOccupant ( vehicle, i )
if ( passenger ) then table.insert ( tableOut, passenger ) end
end
return tableOut
end
function isValidSerial ( serial )
return string.gmatch ( serial, "%w%w%w%w-%w%w%w%w-%w%w%w%w-%w%w%w%w" )
end
function getWeatherNameFromID ( weather )
return iif ( aWeathers[weather], aWeathers[weather], "Unknown" )
end
function getPlayerAccountName( player )
local account = getPlayerAccount ( player )
return account and getAccountName ( account )
end
addEvent ( "onPlayerMute", false )
function aSetPlayerMuted ( player, state )
if ( setPlayerMuted ( player, state ) ) then
triggerEvent ( "onPlayerMute", player, state )
return true
end
return false
end
addEvent ( "onPlayerFreeze", false )
function aSetPlayerFrozen ( player, state )
if ( toggleAllControls ( player, not state, true, false ) ) then
aPlayers[player]["freeze"] = state
triggerEvent ( "onPlayerFreeze", player, state )
local vehicle = getPedOccupiedVehicle( player )
if vehicle then
setVehicleFrozen ( vehicle, state )
end
return true
end
return false
end
function isPlayerFrozen ( player )
if ( aPlayers[player]["freeze"] == nil ) then aPlayers[player]["freeze"] = false end
return aPlayers[player]["freeze"]
end
addEventHandler ( "onPlayerJoin", _root, function ()
if ( aGetSetting ( "welcome" ) ) then
outputChatBox ( aGetSetting ( "welcome" ), source, 255, 100, 100 )
end
aPlayerInitialize ( source )
for id, player in ipairs(getElementsByType("player")) do
if ( hasObjectPermissionTo ( player, "general.adminpanel" ) ) then
triggerClientEvent ( player, "aClientPlayerJoin", source, getPlayerIP ( source ), getPlayerUserName ( source ), getPlayerAccountName ( source ), getPlayerSerial ( source ), hasObjectPermissionTo ( source, "general.adminpanel" ), aPlayers[source]["country"] )
end
end
setPedGravity ( source, getGravity() )
end )
function aPlayerInitialize ( player )
local serial = getPlayerSerial ( player )
if ( not isValidSerial ( serial ) ) then
outputChatBox ( "ERROR: "..getPlayerName ( player ).." - Invalid Serial." )
kickPlayer ( player, "Invalid Serial" )
else
bindKey ( player, "p", "down", "admin" )
callRemote ( "http://community.mtasa.com/mta/verify.php", aPlayerSerialCheck, player, getPlayerUserName ( player ), getPlayerSerial ( player ) )
aPlayers[player] = {}
aPlayers[player]["country"] = getPlayerCountry ( player )
aPlayers[player]["money"] = getPlayerMoney ( player )
end
end
addEvent ( "aPlayerVersion", true )
addEventHandler ( "aPlayerVersion", _root, function ( version )
local bIsPre = false
-- If not Release, mark as 'pre'
if version.type:lower() ~= "release" then
bIsPre = true
else
-- Extract rc version if there
local _,_,rc = string.find( version.tag or "", "(%d)$" )
rc = tonumber(rc) or 0
-- If release, but before final rc, mark as 'pre'
if version.mta == "1.0.2" and rc > 0 and rc < 13 then
bIsPre = true
elseif version.mta == "1.0.3" and rc < 9 then
bIsPre = true
-- elseif version.mta == "1.0.4" and rc < ? then
-- bIsPre = true
-- elseif version.mta == "1.0.5" and rc < ? then
-- bIsPre = true
end
-- If version does not have a built in version check, maybe show a message box advising an upgrade
if version.number < 259 or ( version.mta == "1.0.3" and rc < 3 ) then
triggerClientEvent ( source, "aClientShowUpgradeMessage", source )
end
end
if aPlayers[source] then
aPlayers[source]["version"] = version.mta .. ( bIsPre and " pre" or "" )
end
end )
function aPlayerSerialCheck ( player, result )
if ( result == 0 ) then kickPlayer ( player, "Invalid serial" ) end
end
addEventHandler ( "onPlayerLogin", _root, function ( previous, account, auto )
if ( hasObjectPermissionTo ( source, "general.adminpanel" ) ) then
triggerEvent ( "aPermissions", source )
notifyPlayerLoggedIn( source )
end
end )
addCommandHandler ( "register", function ( player, command, arg1, arg2 )
local username = getPlayerName ( player )
local password = arg1
if ( arg2 ) then
username = arg1
password = arg2
end
if ( password ~= nil ) then
if ( string.len ( password ) < 4 ) then
outputChatBox ( "register: - Password should be at least 4 characters long", player, 255, 100, 70 )
elseif ( addAccount ( username, password ) ) then
outputChatBox ( "You have successfully registered! Username: '"..username.."', Password: '"..password.."'(Remember it)", player, 255, 100, 70 )
elseif ( getAccount ( username ) ) then
outputChatBox ( "register: - Account with this name already exists.", player, 255, 100, 70 )
else
outputChatBox ( "Unknown Error", player, 255, 100, 70 )
end
else
outputChatBox ( "register: - Syntax is 'register [<nick>] <password>'", player, 255, 100, 70 )
end
end )
function aAdminMenu ( player, command )
if ( hasObjectPermissionTo ( player, "general.adminpanel" ) ) then
triggerClientEvent ( player, "aClientAdminMenu", _root )
aPlayers[player]["chat"] = true
end
end
addCommandHandler ( "admin", aAdminMenu )
function aAction ( type, action, admin, player, data, more )
if ( aLogMessages[type] ) then
function aStripString ( string )
string = tostring ( string )
string = string.gsub ( string, "$admin", getPlayerName ( admin ) )
string = string.gsub ( string, "$data2", more or "" )
if ( player ) then string = string.gsub ( string, "$player", getPlayerName ( player ) ) end
return tostring ( string.gsub ( string, "$data", data ) )
end
local node = aLogMessages[type][action]
if ( node ) then
local r, g, b = node["r"], node["g"], node["b"]
if ( node["all"] ) then outputChatBox ( aStripString ( node["all"] ), _root, r, g, b ) end
if ( node["admin"] ) and ( admin ~= player ) then outputChatBox ( aStripString ( node["admin"] ), admin, r, g, b ) end
if ( node["player"] ) then outputChatBox ( aStripString ( node["player"] ), player, r, g, b ) end
if ( node["log"] ) then outputServerLog ( aStripString ( node["log"] ) ) end
end
end
end
addEvent ( "aTeam", true )
addEventHandler ( "aTeam", _root, function ( action, name, r, g, b )
if ( hasObjectPermissionTo ( source, "command."..action ) ) then
mdata = tostring ( data )
mdata = ""
if ( action == "createteam" ) then
local success = false
if ( tonumber ( r ) ) and ( tonumber ( g ) ) and ( tonumber ( b ) ) then
success = createTeam ( name, tonumber ( r ), tonumber ( g ), tonumber ( b ) )
else
success = createTeam ( name )
end
if ( not success ) then
action = nil
outputChatBox ( "Team \""..name.."\" could not be created.", source, 255, 0, 0 )
end
elseif ( action == "destroyteam" ) then
local team = getTeamFromName ( name )
if ( getTeamFromName ( name ) ) then
destroyElement ( team )
else
action = nil
end
else
action = nil
end
if ( action ~= nil ) then aAction ( "server", action, source, false, mdata, mdata2 ) end
return true
end
outputChatBox ( "Access denied for '"..tostring ( action ).."'", source, 255, 168, 0 )
return false
end )
addEvent ( "aAdmin", true )
addEventHandler ( "aAdmin", _root, function ( action, ... )
local mdata = ""
local mdata2 = ""
if ( action == "password" ) then
action = nil
if ( not arg[1] ) then outputChatBox ( "Error - Password missing.", source, 255, 0, 0 )
elseif ( not arg[2] ) then outputChatBox ( "Error - New password missing.", source, 255, 0, 0 )
elseif ( not arg[3] ) then outputChatBox ( "Error - Confirm password.", source, 255, 0, 0 )
elseif ( tostring ( arg[2] ) ~= tostring ( arg[3] ) ) then outputChatBox ( "Error - Passwords do not match.", source, 255, 0, 0 )
else
local account = getAccount ( getPlayerAccountName ( source ), tostring ( arg[1] ) )
if ( account ) then
action = "password"
setAccountPassword ( account, arg[2] )
mdata = arg[2]
else
outputChatBox ( "Error - Invalid password.", source, 255, 0, 0 )
end
end
elseif ( action == "autologin" ) then
elseif ( action == "settings" ) then
local cmd = arg[1]
local resName = arg[2]
local tableOut = {}
if ( cmd == "change" ) then
local name = arg[3]
local value = arg[4]
-- Get previous value
local settings = aGetResourceSettings( resName )
local oldvalue = settings[name].current
-- Match type
if type(oldvalue) == 'boolean' then value = value=='true' end
if type(oldvalue) == 'number' then value = tonumber(value) end
if value ~= oldvalue then
if aSetResourceSetting( resName, name, value ) then
-- Tell the resource one of its settings has changed
local res = getResourceFromName(resName)
local resRoot = getResourceRootElement(res)
if resRoot then
triggerEvent('onSettingChange', resRoot, name, oldvalue, value, source )
end
mdata = resName..'.'..name
mdata2 = tostring(value)
end
end
elseif ( cmd == "getall" ) then
tableOut = aGetResourceSettings( resName )
end
triggerClientEvent ( source, "aAdminSettings", _root, cmd, resName, tableOut )
if mdata == "" then
action = nil
end
elseif ( action == "sync" ) then
local type = arg[1]
local tableOut = {}
if ( type == "aclgroups" ) then
tableOut["groups"] = {}
for id, group in ipairs ( aclGroupList() ) do
table.insert ( tableOut["groups"] ,aclGroupGetName ( group ) )
end
tableOut["acl"] = {}
for id, acl in ipairs ( aclList() ) do
table.insert ( tableOut["acl"] ,aclGetName ( acl ) )
end
elseif ( type == "aclobjects" ) then
local group = aclGetGroup ( tostring ( arg[2] ) )
if ( group ) then
tableOut["name"] = arg[2]
tableOut["objects"] = aclGroupListObjects ( group )
tableOut["acl"] = {}
for id, acl in ipairs ( aclGroupListACL ( group ) ) do
table.insert ( tableOut["acl"], aclGetName ( acl ) )
end
end
elseif ( type == "aclrights" ) then
local acl = aclGet ( tostring ( arg[2] ) )
if ( acl ) then
tableOut["name"] = arg[2]
tableOut["rights"] = {}
for id, name in ipairs ( aclListRights ( acl ) ) do
tableOut["rights"][name] = aclGetRight ( acl, name )
end
end
end
triggerClientEvent ( source, "aAdminACL", _root, type, tableOut )
elseif ( action == "aclcreate" ) then
local name = arg[2]
if ( ( name ) and ( string.len ( name ) >= 1 ) ) then
if ( arg[1] == "group" ) then
mdata = "Group "..name
if ( not aclCreateGroup ( name ) ) then
action = nil
end
elseif ( arg[1] == "acl" ) then
mdata = "ACL "..name
if ( not aclCreate ( name ) ) then
action = nil
end
end
triggerEvent ( "aAdmin", source, "sync", "aclgroups" )
else
outputChatBox ( "Error - Invalid "..arg[1].." name", source, 255, 0, 0 )
end
elseif ( action == "acldestroy" ) then
local name = arg[2]
if ( arg[1] == "group" ) then
if ( aclGetGroup ( name ) ) then
mdata = "Group "..name
aclDestroyGroup ( aclGetGroup ( name ) )
else
action = nil
end
elseif ( arg[1] == "acl" ) then
if ( aclGet ( name ) ) then
mdata = "ACL "..name
aclDestroy ( aclGet ( name ) )
else
action = nil
end
end
triggerEvent ( "aAdmin", source, "sync", "aclgroups" )
elseif ( action == "acladd" ) then
if ( arg[3] ) then
action = action
mdata = "Group '"..arg[2].."'"
if ( arg[1] == "object" ) then
local group = aclGetGroup ( arg[2] )
local object = arg[3]
if ( not aclGroupAddObject ( group, object ) ) then
action = nil
outputChatBox ( "Error adding object '"..tostring ( object ).."' to group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "Object '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "acl" ) then
local group = aclGetGroup ( arg[2] )
local acl = aclGet ( arg[3] )
if ( not aclGroupAddACL ( group, acl ) ) then
action = nil
outputChatBox ( "Error adding ACL '"..tostring ( arg[3] ).."' to group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "ACL '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "right" ) then
local acl = aclGet ( arg[2] )
local right = arg[3]
end
else
action = nil
end
elseif ( action == "aclremove" ) then
--action = nil
if ( arg[3] ) then
action = action
mdata = "Group '"..arg[2].."'"
if ( arg[1] == "object" ) then
local group = aclGetGroup ( arg[2] )
local object = arg[3]
if ( not aclGroupRemoveObject ( group, object ) ) then
action = nil
outputChatBox ( "Error - object '"..tostring ( object ).."' does not exist in group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "Object '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "acl" ) then
local group = aclGetGroup ( arg[2] )
local acl = aclGet ( arg[3] )
if ( not aclGroupRemoveACL ( group, acl ) ) then
action = nil
outputChatBox ( "Error - ACL '"..tostring ( arg[3] ).."' does not exist in group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "ACL '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "right" ) then
local acl = aclGet ( arg[2] )
local right = arg[3]
if ( not aclRemoveRight ( acl, right ) ) then
action = nil
outputChatBox ( "Error - right '"..tostring ( arg[3] ).."' does not exist in ACL '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata = "ACL '"..arg[2].."'"
mdata2 = "Right '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclrights", arg[2] )
end
end
else
action = nil
end
end
if ( action ~= nil ) then aAction ( "admin", action, source, false, mdata, mdata2 ) end
end )
addEvent ( "aPlayer", true )
addEventHandler ( "aPlayer", _root, function ( player, action, data, additional )
if ( hasObjectPermissionTo ( source, "command."..action ) ) then
local admin = source
local mdata = ""
local more = ""
if ( action == "kick" ) then
setTimer ( kickPlayer, 100, 1, player, source, data )
elseif ( action == "ban" ) then
setTimer ( banPlayer, 100, 1, player, true, false, false, source, data )
setTimer( triggerEvent, 1000, 1, "aSync", _root, "bansdirty" )
elseif ( action == "mute" ) then
if ( isPlayerMuted ( player ) ) then action = "un"..action end
aSetPlayerMuted ( player, not isPlayerMuted ( player ) )
elseif ( action == "freeze" ) then
if ( isPlayerFrozen ( player ) ) then action = "un"..action end
aSetPlayerFrozen ( player, not isPlayerFrozen ( player ) )
elseif ( action == "shout" ) then
local textDisplay = textCreateDisplay ()
local textItem = textCreateTextItem ( "(ADMIN)"..getPlayerName ( source )..":\n\n"..data, 0.5, 0.5, 2, 255, 100, 50, 255, 4, "center", "center" )
textDisplayAddText ( textDisplay, textItem )
textDisplayAddObserver ( textDisplay, player )
setTimer ( textDestroyTextItem, 5000, 1, textItem )
setTimer ( textDestroyDisplay, 5000, 1, textDisplay )
elseif ( action == "sethealth" ) then
local health = tonumber ( data )
if ( health ) then
if ( health > 200 ) then health = 100 end
if ( not setElementHealth ( player, health ) ) then
action = nil
end
mdata = health
else
action = nil
end
elseif ( action == "setarmour" ) then
local armour = tonumber ( data )
if ( armour ) then
if ( armour > 200 ) then armour = 100 end
if ( not setPedArmor ( player, armour ) ) then
action = nil
end
mdata = armour
else
action = nil
end
elseif ( action == "setskin" ) then
local vehicle = getPedOccupiedVehicle ( player )
local jetpack = doesPedHaveJetPack ( player )
local seat = 0
if ( vehicle ) then seat = getPedOccupiedVehicleSeat ( player ) end
local x, y, z = getElementPosition ( player )
data = tonumber ( data )
if ( spawnPlayer ( player, x, y, z, getPedRotation ( player ), data, getElementInterior ( player ), getElementDimension ( player ), getPlayerTeam ( player ) ) ) then
fadeCamera ( player, true )
if ( vehicle ) then warpPedIntoVehicle ( player, vehicle, seat ) end
if ( jetpack ) then givePedJetPack ( player ) end
mdata = data
else
action = nil
end
elseif ( action == "setmoney" ) then
mdata = data
if ( not setPlayerMoney ( player, data ) ) then
outputChatBox ( "Invalid money data", source, 255, 0, 0 )
action = nil
end
elseif ( action == "setstat" ) then
if ( additional ) then
if ( tonumber ( data ) == 300 ) then
if ( setPedFightingStyle ( player, tonumber ( additional ) ) ) then
mdata = "Fighting Style"
more = additional
else
action = nil
end
else
if ( setPedStat ( player, tonumber ( data ), tonumber ( additional ) ) ) then
mdata = aStats[data]
more = additional
else
action = nil
end
end
else
action = nil
end
elseif ( action == "setteam" ) then
if ( getElementType ( data ) == "team" ) then
setPlayerTeam ( player, data )
mdata = getTeamName ( data )
else
action = nil
end
elseif ( action == "setinterior" ) then
action = nil
for id, interior in ipairs ( aInteriors ) do
if ( interior["id"] == data ) then
local vehicle = getPedOccupiedVehicle ( player )
setElementInterior ( player, interior["world"] )
local x, y, z = interior["x"] or 0, interior["y"] or 0, interior["z"] or 0
local rot = interior["r"] or 0
if ( vehicle ) then
setElementInterior ( vehicle, interior["world"] )
setElementPosition ( vehicle, x, y, z + 0.2 )
else
setElementPosition ( player, x, y, z + 0.2 )
setPedRotation ( player, rot )
end
action = "interior"
mdata = data
end
end
elseif ( action == "setdimension" ) then
local dimension = tonumber ( data )
if ( dimension ) then
if ( dimension > 65535 ) or ( dimension < 0 ) then dimension = 0 end
if ( not setElementDimension ( player, dimension ) ) then
action = nil
end
mdata = dimension
else
action = nil
end
elseif ( action == "setrinterior" ) then
local int = tonumber ( data )
if ( int ) then
if ( int > 255 ) or ( int < 0 ) then int = 0 end
if ( not setElementInterior ( player, int ) ) then
action = nil
end
mdata = int
else
action = nil
end
elseif ( action == "jetpack" ) then
if ( doesPedHaveJetPack ( player ) ) then
removePedJetPack ( player )
action = "jetpackr"
else
if ( getPedOccupiedVehicle ( player ) ) then outputChatBox ( "Unable to give a jetpack - "..getPlayerName ( player ).." is in a vehicle", source, 255, 0, 0 )
else
if ( givePedJetPack ( player ) ) then
action = "jetpacka"
end
end
end
elseif ( action == "setgroup" ) then
local account = getPlayerAccount ( player )
if ( not isGuestAccount ( account ) ) then
local group = aclGetGroup ( "Admin" )
if ( group ) then
if ( data == true ) then
aclGroupAddObject ( group, "user."..getAccountName ( account ) )
bindKey ( player, "p", "down", "admin" )
action = "admina"
elseif ( data == false ) then
unbindKey ( player, "p", "down", "admin" )
aclGroupRemoveObject ( group, "user."..getAccountName ( account ) )
aPlayers[player]["chat"] = false
action = "adminr"
end
for id, p in ipairs ( getElementsByType ( "player" ) ) do
if ( hasObjectPermissionTo ( p, "general.adminpanel" ) ) then triggerEvent ( "aSync", p, "admins" ) end
end
else
outputChatBox ( "Error - Admin group not initialized. Please reinstall admin resource.", source, 255, 0 ,0 )
end
else
outputChatBox ( "Error - Player is not logged in.", source, 255, 100 ,100 )
end
elseif ( action == "givevehicle" ) then
local pvehicle = getPedOccupiedVehicle ( player )
local vx, vy, vz = getElementVelocity ( player )
local vehicle = nil
if ( pvehicle ) then
local passengers = getVehicleOccupants ( pvehicle )
local x, y, z = getElementPosition ( pvehicle )
local rx, ry, rz = getVehicleRotation ( pvehicle )
local vx, vy, vz = getElementVelocity ( pvehicle )
destroyElement ( pvehicle )
vehicle = createVehicle ( data, x, y, z, rx, ry, rz )
local seats = getVehicleMaxPassengers ( vehicle )
for i, p in ipairs ( passengers ) do
if ( p ~= player ) then
local s = i - 1
if ( s <= seats ) then setTimer ( warpPedIntoVehicle, 500, 1, p, vehicle, s ) end
end
end
else
local x, y, z = getElementPosition ( player )
local r = getPedRotation ( player )
vehicle = createVehicle ( data, x, y, z, 0, 0, r )
end
setElementDimension ( vehicle, getElementDimension ( player ) )
setElementInterior ( vehicle, getElementInterior ( player ) )
warpPedIntoVehicle ( player, vehicle )
setElementVelocity ( vehicle, vx, vy, vz )
mdata = getVehicleName ( vehicle )
elseif ( action == "giveweapon" ) then
if ( giveWeapon ( player, data, additional, true ) ) then
mdata = getWeaponNameFromID ( data )
more = additional
else
action = nil
end
elseif ( action == "slap" ) then
if ( getElementHealth ( player ) > 0 ) and ( not isPedDead ( player ) ) then
if ( ( not data ) or ( not tonumber ( data ) ) ) then data = 20 end
if ( tonumber ( data ) > getElementHealth ( player ) ) then setTimer ( killPed, 50, 1, player )
else setElementHealth ( player, getElementHealth ( player ) - data ) end
local x, y, z = getElementVelocity ( player )
setElementVelocity ( player, x , y, z + 0.2 )
mdata = data
else
action = nil
end
elseif ( action == "teleto" ) then
exports.phoenix_InfoSpots:doEnter( player, data );
fadeCamera ( player, false, 1, 0, 0, 0 )
setTimer ( fadeCamera, 1000, 1, player, true, 1 )
mdata = data
elseif ( action == "warp" ) or ( action == "warpto" ) then
function warpPlayer ( p, to )
function warp ( p, to )
local x, y, z = getElementPosition ( to )
local r = getPedRotation ( to )
x = x - math.sin ( math.rad ( r ) ) * 2
y = y + math.cos ( math.rad ( r ) ) * 2
setTimer ( setElementPosition, 1000, 1, p, x, y, z + 1 )
fadeCamera ( p, false, 1, 0, 0, 0 )
setElementDimension ( p, getElementDimension ( to ) )
setElementInterior ( p, getElementInterior ( to ) )
setTimer ( fadeCamera, 1000, 1, p, true, 1 )
end
if ( isPedInVehicle ( to ) ) then
local vehicle = getPedOccupiedVehicle ( to )
local seats = getVehicleMaxPassengers ( vehicle ) + 1
local i = 0
while ( i < seats ) do
if ( not getVehicleOccupant ( vehicle, i ) ) then
setTimer ( warpPedIntoVehicle, 1000, 1, p, vehicle, i )
fadeCamera ( p, false, 1, 0, 0, 0 )
setTimer ( fadeCamera, 1000, 1, p, true, 1 )
break
end
i = i + 1
end
if ( i >= seats ) then
warp ( p, to )
outputConsole ( "Player's vehicle is full ("..getVehicleName ( vehicle ).." - Seats: "..seats..")", p )
end
else
warp ( p, to )
end
end
if ( action == "warp" ) then
warpPlayer ( source, player )
else
warpPlayer ( player, data )
mdata = getPlayerName ( data )
end
else
outputDebugString( "Admin(UNKNOWN_ACTION): " .. action );
action = nil
end
if ( action ~= nil ) then aAction ( "player", action, admin, player, mdata, more ) end
return true
end
outputChatBox ( "Access denied for '"..tostring ( action ).."'", source, 255, 168, 0 )
return false
end )
addEvent ( "aVehicle", true )
addEventHandler ( "aVehicle", _root, function ( player, action, data )
if ( hasObjectPermissionTo ( source, "command."..action ) ) then
local vehicle = getPedOccupiedVehicle ( player )
if ( vehicle ) then
local mdata = ""
if ( action == "repair" ) then
fixVehicle ( vehicle )
local rx, ry, rz = getVehicleRotation ( vehicle )
if ( rx > 110 ) and ( rx < 250 ) then
local x, y, z = getElementPosition ( vehicle )
setVehicleRotation ( vehicle, rx + 180, ry, rz )
setElementPosition ( vehicle, x, y, z + 2 )
end
elseif ( action == "customize" ) then
if ( data[1] == "remove" ) then
for id, upgrade in ipairs ( getVehicleUpgrades ( vehicle ) ) do
removeVehicleUpgrade ( vehicle, upgrade )
end
action = "customizer"
else
for id, upgrade in ipairs ( data ) do
addVehicleUpgrade ( vehicle, upgrade )
if ( mdata == "" ) then mdata = tostring ( upgrade )
else mdata = mdata..", "..upgrade end
end
end
elseif ( action == "setpaintjob" ) then
mdata = data
if ( not setVehiclePaintjob ( vehicle, data ) ) then
action = nil
outputChatBox ( "Invalid Paint job ID", source, 255, 0, 0 )
end
elseif ( action == "setcolor" ) then
for k, color in ipairs ( data ) do
local c = tonumber ( color )
if ( c ) then
if ( c < 0 ) or ( c > 126 ) then
action = nil
end
else
action = nil
end
end
if ( action ~= nil ) then
if ( not setVehicleColor ( vehicle, tonumber(data[1]), tonumber(data[2]), tonumber(data[3]), tonumber(data[4]) ) ) then
action = nil
end
end
elseif ( action == "blowvehicle" ) then
setTimer ( blowVehicle, 100, 1, vehicle )
elseif ( action == "destroyvehicle" ) then
setTimer ( destroyElement, 100, 1, vehicle )
else
action = nil
end
if ( action ~= nil ) then
local seats = getVehicleMaxPassengers ( vehicle ) + 1
for i = 0, seats do
local passenger = getVehicleOccupant ( vehicle, i )
if ( passenger ) then
if ( ( passenger == player ) and ( getPedOccupiedVehicle ( source ) ~= vehicle ) ) then aAction ( "vehicle", action, source, passenger, mdata )
else aAction ( "vehicle", action, passenger, passenger, mdata ) end
end
end
end
end
return true
end
outputChatBox ( "Access denied for '"..tostring ( action ).."'", source, 255, 168, 0 )
return false
end )
addEvent ( "aResource", true )
addEventHandler ( "aResource", _root, function ( name, action )
local pname = getPlayerName ( source )
if ( hasObjectPermissionTo ( source, "command."..action ) ) then
local text = ""
if ( action == "start" ) then if ( startResource ( getResourceFromName ( name ), true ) ) then text = "Resource \'"..name.."\' started by "..pname end
elseif ( action == "restart" ) then if ( restartResource ( getResourceFromName ( name ) ) ) then text = "Resource \'"..name.."\' restarted by "..pname end
elseif ( action == "stop" ) then if ( stopResource ( getResourceFromName ( name ) ) ) then text = "Resource \'"..name.."\' stopped by "..pname end
else action = nil
end
if ( text ~= "" ) then
for id, player in ipairs(getElementsByType("player")) do
outputServerLog ( "ADMIN: "..text )
triggerClientEvent ( player, "aClientLog", _root, text )
end
end
return true
end
outputChatBox ( "Access denied for '"..tostring ( action ).."'", source, 255, 168, 0 )
return false
end )
addEvent ( "aServer", true )
addEventHandler ( "aServer", _root, function ( action, data, data2 )
if ( hasObjectPermissionTo ( source, "command."..action ) ) then
local mdata = tostring ( data )
local mdata2 = ""
if ( action == "setgame" ) then
if ( not setGameType ( tostring ( data ) ) ) then
action = nil
outputChatBox ( "Error setting game type.", source, 255, 0, 0 )
end
triggerEvent ( "aSync", source, "server" )
elseif ( action == "setmap" ) then
if ( not setMapName ( tostring ( data ) ) ) then
action = nil
outputChatBox ( "Error setting map name.", source, 255, 0, 0 )
end
triggerEvent ( "aSync", source, "server" )
elseif ( action == "setwelcome" ) then
if ( ( not data ) or ( data == "" ) ) then
action = "resetwelcome"
aRemoveSetting ( "welcome" )
else
aSetSetting ( "welcome", tostring ( data ) )
mdata = data
end
elseif ( action == "settime" ) then
if ( not setTime ( tonumber ( data ), tonumber ( data2 ) ) ) then
action = nil
outputChatBox ( "Error setting time.", source, 255, 0, 0 )
end
mdata = data..":"..data2
elseif ( action == "setpassword" ) then
if ( data == "" ) then
setServerPassword ( nil )
action = "resetpassword"
elseif ( string.len ( data ) > 32 ) then
outputChatBox ( "Set password: 32 characters max", source, 255, 0, 0 )
elseif ( not setServerPassword ( data ) ) then
action = nil
outputChatBox ( "Error setting password", source, 255, 0, 0 )
end
triggerEvent ( "aSync", source, "server" )
elseif ( action == "setweather" ) then
if ( not setWeather ( tonumber ( data ) ) ) then
action = nil
outputChatBox ( "Error setting weather.", source, 255, 0, 0 )
end
mdata = data.." "..getWeatherNameFromID ( tonumber ( data ) )
elseif ( action == "blendweather" ) then
if ( not setWeatherBlended ( tonumber ( data ) ) ) then
action = nil
outputChatBox ( "Error setting weather.", source, 255, 0, 0 )
end
elseif ( action == "setgamespeed" ) then
if ( not setGameSpeed ( tonumber ( data ) ) ) then
action = nil
outputChatBox ( "Error setting game speed.", source, 255, 0, 0 )
end
elseif ( action == "setgravity" ) then
if ( setGravity ( tonumber ( data ) ) ) then
for id, player in ipairs ( getElementsByType ( "player" ) ) do
setPedGravity ( player, getGravity() )
end
else
action = nil
outputChatBox ( "Error setting gravity.", source, 255, 0, 0 )
end
elseif ( action == "setblurlevel" ) then
elseif ( action == "setwaveheight" ) then
if ( not setWaveHeight ( data ) ) then
outputChatBox ( "Error setting wave height.", source, 255, 0, 0 )
action = nil
else
mdata = data
end
else
action = nil
end
if ( action ~= nil ) then aAction ( "server", action, source, false, mdata, mdata2 ) end
return true
end
outputChatBox ( "Access denied for '"..tostring ( action ).."'", source, 255, 168, 0 )
return false
end )
addEvent ( "aMessage", true )
addEventHandler ( "aMessage", _root, function ( action, data )
if ( action == "new" ) then
local time = getRealTime()
local id = #aReports + 1
aReports[id] = {}
aReports[id].author = getPlayerName ( source )
aReports[id].category = tostring ( data.category )
aReports[id].subject = tostring ( data.subject )
aReports[id].text = tostring ( data.message )
aReports[id].time = string.format( '%04d-%02d-%02d %02d:%02d', time.year + 1900, time.month + 1, time.monthday, time.hour, time.minute )
aReports[id].read = false
-- PM all admins to say a new message has arrived
for _, p in ipairs ( getElementsByType ( "player" ) ) do
if ( hasObjectPermissionTo ( p, "general.adminpanel" ) ) then
outputChatBox( "New Admin message from " .. aReports[id].author .. " (" .. aReports[id].subject .. ")", p, 255, 0, 0 )
end
end
-- Keep message count no greater that 'maxmsgs'
if tonumber(get('maxmsgs')) then
while #aReports > tonumber(get('maxmsgs')) do
table.remove( aReports, 1 )
end
end
elseif ( action == "get" ) then
triggerClientEvent ( source, "aMessage", source, "get", aReports )
elseif ( action == "read" ) then
if ( aReports[data] ) then
aReports[data].read = true
end
elseif ( action == "delete" ) then
if ( aReports[data] ) then
table.remove ( aReports, data )
end
triggerClientEvent ( source, "aMessage", source, "get", aReports )
else
action = nil
end
for id, p in ipairs ( getElementsByType ( "player" ) ) do
if ( hasObjectPermissionTo ( p, "general.adminpanel" ) ) then triggerEvent ( "aSync", p, "messages" ) end
end
end )
addEvent ( "aBans", true )
addEventHandler ( "aBans", _root, function ( action, data )
if ( hasObjectPermissionTo ( source, "command."..action ) ) then
local mdata = ""
local more = ""
if ( action == "banip" ) then
mdata = data
if ( not addBan ( data,nil,nil,source ) ) then
action = nil
end
elseif ( action == "banserial" ) then
mdata = data
if ( isValidSerial ( data ) ) then
if ( not addBan ( nil,nil, string.upper ( data ),source ) ) then
action = nil
end
else
outputChatBox ( "Error - Invalid serial", source, 255, 0, 0 )
action = nil
end
elseif ( action == "unbanip" ) then
mdata = data
action = nil
for i,ban in ipairs(getBans ()) do
if getBanIP(ban) == data then
action = removeBan ( ban, source )
end
end
elseif ( action == "unbanserial" ) then
mdata = data
action = nil
for i,ban in ipairs(getBans ()) do
if getBanSerial(ban) == string.upper(data) then
action = removeBan ( ban, source )
end
end
else
action = nil
end
if ( action ~= nil ) then
aAction ( "bans", action, source, false, mdata, more )
triggerEvent ( "aSync", source, "sync", "bansdirty" )
end
return true
end
outputChatBox ( "Access denied for '"..tostring ( action ).."'", source, 255, 168, 0 )
return false
end )
addEvent ( "aExecute", true )
addEventHandler ( "aExecute", _root, function ( action, echo )
if ( hasObjectPermissionTo ( source, "command.execute" ) ) then
local result = loadstring("return " .. action)()
if ( echo == true ) then
local restring = ""
if ( type ( result ) == "table" ) then
for k,v in pairs ( result ) do restring = restring..tostring ( v )..", " end
restring = string.sub(restring,1,-3)
restring = "Table ("..restring..")"
elseif ( type ( result ) == "userdata" ) then
restring = "Element ("..getElementType ( result )..")"
else
restring = tostring ( result )
end
outputChatBox( "Command executed! Result: " ..restring, source, 0, 0, 255 )
end
outputServerLog ( "ADMIN: "..getPlayerName ( source ).." executed command: "..action )
end
end )
addEvent ( "aAdminChat", true )
addEventHandler ( "aAdminChat", _root, function ( chat )
for id, player in ipairs(getElementsByType("player")) do
if ( aPlayers[player]["chat"] ) then
triggerClientEvent ( player, "aClientAdminChat", source, chat )
end
end
end )
| gpl-3.0 |
LGCaerwyn/QSanguosha-V2-mod | lang/zh_CN/Package/LingPackge.lua | 2 | 3735 | -- translation for Ling Package
return {
["ling"] = "翼包",
["neo_guanyu"] = "关云长",
["&neo_guanyu"] = "关羽",
["designer:neo_guanyu"] = "官方,凌天翼",
["yishi"] = "义释",
[":yishi"] = "每当你使用【杀】对目标角色造成伤害时,若该角色区域内有牌,你可以防止此伤害,然后获得其区域内的一张牌。",
["#Yishi"] = "%from 发动了“%arg”,防止了对 %to 的伤害",
["neo_zhangfei"] = "张翼德",
["&neo_zhangfei"] = "张飞",
["designer:neo_zhangfei"] = "官方,凌天翼",
["tannang"] = "探囊",
[":tannang"] = "<font color=\"blue\"><b>锁定技,</b></font>你与其他角色的距离-X。(X为你已损失的体力值)",
["neo_zhaoyun"] = "赵子龙",
["&neo_zhaoyun"] = "赵云",
["designer:neo_zhaoyun"] = "官方,凌天翼",
["LingCards"] = "国战卡牌" ,
["await_exhausted"] = "以逸待劳",
[":await_exhausted"] = "出牌阶段,对你与任意数量的其他角色使用。每名目标角色摸两张牌,然后弃置两张牌。",
["befriend_attacking"] = "远交近攻",
[":befriend_attacking"] = "出牌阶段,对距离最远的一名角色使用。该角色摸一张牌,然后令你摸三张牌。",
["known_both"] = "知己知彼",
[":known_both"] = "出牌阶段,对一名有手牌的其他角色使用。你观看其手牌。<br/>你可以重铸此牌。",
["SixSwords"] = "吴六剑",
["sixswords"] = "吴六剑",
[":SixSwords"] = "攻击范围:2<br/>武器特效:回合结束时,你可以令任意数量的其他角色攻击范围+1,直到你的下回合结束或你失去装备区里的【吴六剑】。",
["@SixSwordsBuff"] = "攻击范围+1" ,
["@six_swords"] = "你可以发动【吴六剑】" ,
["~SixSwords"] = "选择若干名角色→点击“确定”" ,
["neo_drowning"] = "水淹七军",
[":neo_drowning"] = "出牌阶段,对所有其他角色使用。每名目标角色各选择一项:1.弃置其装备区里所有的牌;2.受到你对其造成的1点伤害。",
["neo_drowning:throw"] = "弃置所有装备" ,
["neo_drowning:damage"] ="受到伤害" ,
["Triblade"] = "三尖两刃刀",
[":Triblade"] = "攻击范围:3<br/>武器特效:每当你使用【杀】对目标角色造成伤害后,你可以弃置一张手牌,对该角色距离为1的另一名角色造成1点伤害。",
["@triblade"] = "你可以对该角色距离为1的另一名角色造成1点伤害。" ,
["~Triblade"] = "选择手牌-选择目标。",
["DragonPhoenix"] = "飞龙夺凤",
[":DragonPhoenix"] = "攻击范围:2<br/>武器特效:每当你使用【杀】指定一名目标角色后,你可以令该角色弃置一张牌;每当被你使用【杀】杀死的角色死亡后,你可以用该角色的武将牌替换自己的武将牌。" ,
["dragon-phoenix-card"] = "受到【飞龙夺凤】的影响,你需要弃置1张牌。" ,
["PeaceSpell"] = "太平要术" ,
[":PeaceSpell"] = "锁定技,每当你受到属性伤害时,你防止此伤害;弃牌阶段开始前,你可以令任意数量的角色的手牌上限+1,直到你的下回合开始或你失去装备区里的【太平要术】;锁定技,每当你失去装备区里的【太平要术】时,你失去1点体力,然后摸两张牌。" ,
["@peacespell"] = "你可以令任意数量的角色的手牌上限+1,直到你的下回合开始。" ,
["@PeaceSpellBuff"] = "手牌上限+1" ,
} | lgpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Kazham/npcs/Haih_Ahmpagako.lua | 17 | 1072 | -----------------------------------
-- Area: Kazham
-- NPC: Haih Ahmpagako
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00A2); -- scent from Blue Rafflesias
else
player:startEvent(0x003E);
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 |
RebootRevival/FFXI_Test | scripts/zones/Davoi/Zone.lua | 13 | 3403 | -----------------------------------
--
-- Zone: Davoi (149)
--
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
UpdateTreasureSpawnPoint(17388027);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(282.292,2.498,-17.908,247);
end
if (player:getCurrentMission(SANDORIA) == INFILTRATE_DAVOI and player:getVar("MissionStatus") == 2) then
cs = 0x0074;
end
if (player:getQuestStatus(SANDORIA,THE_CRIMSON_TRIAL) == QUEST_ACCEPTED and GetMobAction(17387969) == 0) then
SpawnMob(17387969); -- Spawned by Quest: The Crimson Trial upon entering the zone.
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onGameDay
-----------------------------------
function onGameDay()
-- Storage Hole
local storHolePos = {--[[E-10]]{-177.925,4.000,-255.699},--[[F-6]]{-127.703,4.250,23.732}, --[[F-7]]{-127.822,4.250,-16.964},--[[F-9]]{-123.369,4.000,-231.972},--[[G-9]]{-51.570,4.127,-216.462},
--[[G-10]]{-55.960,2.958,-300.014}, --[[I-7]]{152.311,4.000,-74.176}, --[[I-8]]{153.514,4.250,-112.616},--[[J-7]]{188.988,4.000,-80.058}, --[[K-7]]{318.694,0.001,-58.646},
--[[K-8]]{299.717,0.001,-160.910}, --[[K-9]]{274.849,4.162,-213.599},--[[K-9]]{250.809,4.000,-240.509},--[[J-8]]{219.474,3.750,-128.170}, --[[I-9]]{86.749,-5.166,-166.414}};
local storageHole = GetNPCByID(17388025);
local randPos = 0;
while(randPos == 0 or storHolePos[randPos][1] == storageHole:getXPos()) do
randPos = math.random(1,15);
end
storageHole:setPos(storHolePos[randPos][1],storHolePos[randPos][2],storHolePos[randPos][3],0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0074) then
player:setVar("MissionStatus",3);
end
end;
| gpl-3.0 |
solotimes/lsyncd | tests/churn-rsync.lua | 13 | 1092 | #!/usr/bin/lua
-- a heavy duty test.
-- makes thousends of random changes to the source tree
require("posix")
dofile("tests/testlib.lua")
cwriteln("****************************************************************")
cwriteln(" Testing default.rsync with random data activity ")
cwriteln("****************************************************************")
local tdir, srcdir, trgdir = mktemps()
-- makes some startup data
churn(srcdir, 10)
local logs = {}
--logs = {"-log", "Delay", "-log", "Fsevents" }
local pid = spawn("./lsyncd", "-nodaemon", "-delay", "5",
"-rsync", srcdir, trgdir, unpack(logs))
cwriteln("waiting for Lsyncd to startup")
posix.sleep(1)
churn(srcdir, 500)
cwriteln("waiting for Lsyncd to finish its jobs.")
posix.sleep(10)
cwriteln("killing the Lsyncd daemon")
posix.kill(pid)
local _, exitmsg, lexitcode = posix.wait(lpid)
cwriteln("Exitcode of Lsyncd = ", exitmsg, " ", lexitcode)
exitcode = os.execute("diff -r "..srcdir.." "..trgdir)
cwriteln("Exitcode of diff = '", exitcode, "'")
if exitcode ~= 0 then
os.exit(1)
else
os.exit(0)
end
| gpl-2.0 |
dannybloe/domoticz | dzVents/runtime/tests/testUtils.lua | 5 | 13152 | local _ = require 'lodash'
--package.path = package.path .. ";../?.lua"
local scriptPath = ''
package.path = ";../?.lua;" .. scriptPath .. '/?.lua;../device-adapters/?.lua;../../../scripts/lua/?.lua;' .. package.path
local LOG_INFO = 2
local LOG_DEBUG = 3
local LOG_ERROR = 1
describe('event helpers', function()
local utils
setup(function()
_G.logLevel = 1
_G.log = function() end
_G.globalvariables = {
Security = 'sec',
['radix_separator'] = '.',
['script_path'] = scriptPath,
['domoticz_listening_port'] = '8080'
}
_G.domoticzData =
{
[1] = { ["id"] = 1, ["baseType"] = "device", ["name"] = "ExistingDevice" },
[2] = { ["id"] = 2, ["baseType"] = "group", ["name"] = "ExistingGroup" },
[3] = { ["id"] = 3, ["baseType"] = "scene", ["name"] = "ExistingScene" },
[4] = { ["id"] = 4, ["baseType"] = "uservariable", ["name"] = "ExistingVariable" },
[5] = { ["id"] = 5, ["baseType"] = "camera", ["name"] = "ExistingCamera" },
[6] = { ["id"] = 6, ["baseType"] = "hardware", ["name"] = "ExistingHardware" },
}
utils = require('Utils')
end)
teardown(function()
utils = nil
_G.domoticzData = nil
end)
describe("Logging", function()
it('should print using the global log function', function()
local printed
utils.print = function(msg)
printed = msg
end
utils.log('abc', utils.LOG_ERROR)
assert.is_same('Error: (' .. utils.DZVERSION .. ') abc', printed)
end)
it('should log INFO by default', function()
local printed
utils.print = function(msg)
printed = msg
end
_G.logLevel = utils.LOG_INFO
utils.log('something')
assert.is_same('Info: something', printed)
end)
it('should log print with requested marker', function()
local printed
utils.print = function(msg)
printed = msg
end
_G.logLevel = utils.LOG_INFO
utils.log('something')
assert.is_same('Info: something', printed)
_G.moduleLabel = 'testUtils'
utils.setLogMarker()
utils.log('something')
assert.is_same('Info: testUtils: something', printed)
utils.setLogMarker('Busted')
utils.log('something')
assert.is_same('Info: Busted: something', printed)
end)
it('should not log above level', function()
local printed
utils.print = function(msg)
printed = msg
end
_G.logLevel = utils.LOG_INFO
utils.log('something', utils.LOG_DEBUG)
assert.is_nil(printed)
_G.logLevel = utils.LOG_ERROR
utils.log('error', utils.LOG_INFO)
assert.is_nil(printed)
utils.log('error', utils.LOG_WARNING)
assert.is_nil(printed)
_G.logLevel = 0
utils.log('error', utils.LOG_ERROR)
assert.is_nil(printed)
end)
end)
describe("various utils", function()
it('should return true if a file exists', function()
assert.is_true(utils.fileExists('testfile'))
end)
it('should right pad a string', function()
assert.is_same(utils.rightPad('string',7),'string ')
assert.is_same(utils.rightPad('string',7,'@'),'string@')
assert.is_same(utils.rightPad('string',2),'string')
end)
it('should left pad a string', function()
assert.is_same(utils.leftPad('string',7),' string')
assert.is_same(utils.leftPad('string',7,'@'),'@string')
assert.is_same(utils.leftPad('string',2),'string')
end)
it('should center and pad a string', function()
assert.is_same(utils.centerPad('string',8),' string ')
assert.is_same(utils.centerPad('string',8,'@'),'@string@')
assert.is_same(utils.centerPad('string',2),'string')
end)
it('should pad a number with leading zeros', function()
assert.is_same(utils.leadingZeros(99,3),'099')
assert.is_same(utils.leadingZeros(999,2),'999')
end)
it('should return nil for osexecute (echo)', function()
assert.is_nil(utils.osExecute('echo test > testfile.out'))
end)
it('should return nil for os.execute (rm)', function()
assert.is_nil(utils.osExecute('rm testfile.out'))
end)
it('should return nil for osCommand (echo)', function()
local res, rc = utils.osCommand('echo test > testfile.out')
assert.is_same(rc, 0)
assert.is_same(res, '')
end)
it('should return nil for osCommand (rm)', function()
local res, rc = utils.osCommand('rm -fv nofile.nofile ')
assert.is_same(rc, 0)
assert.is_same(res, '')
local res, rc = utils.osCommand('rm -v testfile.out')
assert.is_same(rc, 0)
assert.is_same(res:sub(1,4), "remo")
end)
it('should return false if a file does not exist', function()
assert.is_false(utils.fileExists('blatestfile'))
end)
it('should return false if a device does not exist and id or name when it does', function()
local device = { id = 1}
local noDevice = { id = 2}
assert.is_false(utils.deviceExists('noDevice'))
assert.is_false(utils.deviceExists(noDevice))
assert.is_false(utils.deviceExists(2))
assert.is_true(utils.deviceExists('ExistingDevice') == 1 )
assert.is_true(utils.deviceExists(1) == 'ExistingDevice' )
assert.is_true(utils.deviceExists(device) == 1)
end)
it('should return false if a group does not exist and id or name when it does', function()
local group = { id = 2}
local noGroup = { id = 3}
assert.is_false(utils.groupExists('noGroup'))
assert.is_false(utils.groupExists(noGroup))
assert.is_false(utils.groupExists(3))
assert.is_true(utils.groupExists('ExistingGroup') == 2 )
assert.is_true(utils.groupExists(2) == 'ExistingGroup' )
assert.is_true(utils.groupExists(group) == 2)
end)
it('should return false if a scene does not exist and id or name when it does', function()
local scene = { id = 3}
local noScene = { id = 4}
assert.is_false(utils.sceneExists('noScene'))
assert.is_false(utils.sceneExists(noScene))
assert.is_false(utils.sceneExists(4))
assert.is_true(utils.sceneExists('ExistingScene') == 3 )
assert.is_true(utils.sceneExists(3) == 'ExistingScene' )
assert.is_true(utils.sceneExists(scene) == 3)
end)
it('should return false if a variable does not exist and id or name when it does', function()
local variable = { id = 4}
local noVariable = { id = 5}
assert.is_false(utils.variableExists('noVariable'))
assert.is_false(utils.variableExists(noVariable))
assert.is_false(utils.variableExists(5))
assert.is_true(utils.variableExists('ExistingVariable') == 4 )
assert.is_true(utils.variableExists(4) == 'ExistingVariable' )
assert.is_true(utils.variableExists(variable) == 4)
end)
it('should return false if a camera does not exist and id or name when it does', function()
local camera = { id = 5}
local noCamera = { id = 6}
assert.is_false(utils.cameraExists('noCamera'))
assert.is_false(utils.cameraExists(noCamera))
assert.is_false(utils.cameraExists(6))
assert.is_true(utils.cameraExists('ExistingCamera') == 5 )
assert.is_true(utils.cameraExists(5) == 'ExistingCamera' )
assert.is_true(utils.cameraExists(camera) == 5)
end)
it('should return false if hardware does not exist and id or name when it does', function()
assert.is_false(utils.hardwareExists('noHardware'))
assert.is_false(utils.hardwareExists(7))
assert.is_true(utils.hardwareExists('ExistingHardware') == 6 )
assert.is_true(utils.hardwareExists(6) == 'ExistingHardware' )
end)
it('should convert a json to a table', function()
local json = '{ "a": 1 }'
local t = utils.fromJSON(json)
assert.is_same(1, t['a'])
end)
it('should convert a serialized json to a table when set to true', function()
local json = '{"level 1":{"level 2_1":{"level 3":{\"level 4\":'..
'{\"level 5_1\":[\"a\"],\"level 5_2\":[\"b\",\"c"]}}},' ..
'"level 2_2":{"level 3":"[\"found\",\"1\",\"2\",\"3\"]},' ..
'"level 2_3":{"level 3":"[block] as data"}}}'
local t = utils.fromJSON(json)
assert.is_nil(t)
local t = utils.fromJSON(json, json)
assert.is_same(t,json)
local t = utils.fromJSON(json, json, true)
assert.is_same('found', t['level 1']['level 2_2']['level 3'][1])
assert.is_same('[block] as data', t['level 1']['level 2_3']['level 3'])
end)
it('should round a number', function()
local number = '2.43'
assert.is_same(2, utils.round(number) )
number = -2.43
assert.is_same(-2, utils.round(number) )
number = {}
assert.is_nil( utils.round(number) )
end)
it('should recognize an xml string', function()
local xml = '<testXML>What a nice feature!</testXML>'
assert.is_true(utils.isXML(xml))
local xml = nil
assert.is_nil(utils.isXML(xml))
local xml = '<testXML>What a bad XML!</testXML> xml'
assert.is_nil(utils.isXML(xml))
local xml = '{ wrong XML }'
local content = 'application/xml'
fallback = nil
assert.is_true(utils.isXML(xml, content))
end)
it('should recognize a json string', function()
local json = '[{ "test": 12 }]'
assert.is_true(utils.isJSON(json))
local json = '{ "test": 12 }'
assert.is_true(utils.isJSON(json))
local json = nil
assert.is_false(utils.isJSON(json))
local json = '< wrong XML >'
local content = 'application/json'
fallback = nil
assert.is_true(utils.isJSON(json, content))
end)
it('should convert a json string to a table or fallback to fallback', function()
local json = '{ "a": 1 }'
local t = utils.fromJSON(json, fallback)
assert.is_same(1, t['a'])
local json = '[{"obj":"Switch","act":"On" }]'
local t = utils.fromJSON(json, fallback)
assert.is_same('Switch', t[1].obj)
json = nil
local fallback = { a=1 }
local t = utils.fromJSON(json, fallback)
assert.is_same(1, t['a'])
json = nil
fallback = nil
local t = utils.fromJSON(json, fallback)
assert.is_nil(t)
end)
it('should convert an xml string to a table or fallback to fallback', function()
local xml = '<testXML>What a nice feature!</testXML>'
local t = utils.fromXML(xml, fallback)
assert.is_same('What a nice feature!', t.testXML)
local xml = nil
local fallback = { a=1 }
local t = utils.fromXML(xml, fallback)
assert.is_same(1, t['a'])
local xml = nil
fallback = nil
local t = utils.fromXML(xml, fallback)
assert.is_nil(t)
end)
it('should convert a table to json', function()
local t = {
a = 1,
b = function()
print('This should do nothing')
end
}
local res = utils.toJSON(t)
assert.is_same('{"a":1,"b":"Function"}', res)
end)
it('should convert a table to xml', function()
local t = { a= 1 }
local res = utils.toXML(t, 'busted')
assert.is_same('<busted>\n<a>1</a>\n</busted>\n', res)
end)
it('should convert a string or number to base64Code', function()
local res = utils.toBase64('Busted in base64')
assert.is_same('QnVzdGVkIGluIGJhc2U2NA==', res)
local res = utils.toBase64(123.45)
assert.is_same('MTIzLjQ1', res)
local res = utils.toBase64(1234567890)
assert.is_same('MTIzNDU2Nzg5MA==', res)
end)
it('should send errormessage when sending table to toBase64', function()
utils.log = function(msg)
printed = msg
end
local t = { a= 1 }
local res = utils.toBase64(t)
assert.is_same('toBase64: parm should be a number or a string; you supplied a table', printed)
end)
it('should decode a base64 encoded string', function()
local res = utils.fromBase64('QnVzdGVkIGluIGJhc2U2NA==')
assert.is_same('Busted in base64', res)
end)
it('should send errormessage when sending table to fromBase64', function()
utils.log = function(msg)
printed = msg
end
local t = { a= 1 }
local res = utils.fromBase64(t)
assert.is_same('fromBase64: parm should be a string; you supplied a table', printed)
end)
it('should dump a table to log', function()
local t = { a=1,b=2,c={d=3,e=4, "test"} }
local res = utils.dumpTable(t,"> ")
assert.is_nil(res)
end)
it('should split a string ', function()
assert.is_same(utils.stringSplit("A-B-C", "-")[2],"B")
assert.is_same(utils.stringSplit("I forgot to include this in Domoticz.lua")[7],"Domoticz.lua")
end)
it('should split a line', function()
assert.is_same(utils.splitLine("segment one or segment two or segment 3", "or")[2],"segment two")
assert.is_same(utils.splitLine("segment one or segment two or segment 3", "or")[3],"segment 3")
end)
it('should fuzzy match a string ', function()
assert.is_same(utils.fuzzyLookup('HtpRepsonse','httpResponse'),3)
assert.is_same(utils.fuzzyLookup('httpResponse','httpResponse'),0)
local validEventTypes = 'devices,timer,security,customEvents,system,httpResponses,scenes,groups,variables,devices'
assert.is_same(utils.fuzzyLookup('CutsomeEvent',utils.stringSplit(validEventTypes,',')),'customEvents')
end)
it('should match a string with Lua magic chars', function()
assert.is_same(string.sMatch("testing (A-B-C) testing","(A-B-C)"), "(A-B-C)")
assert.is_not(string.match("testing (A-B-C) testing", "(A-B-C)"), "(A-B-C)")
end)
it('should handle inTable ', function()
assert.is_same(utils.inTable({ testVersion = "2.5" }, 2.5 ), "value")
assert.is_same(utils.inTable({ testVersion = "2.5" }, "testVersion"), "key")
assert.is_not(utils.inTable({ testVersion = "2.5" }, 2.4 ), false)
end)
end)
end)
| gpl-3.0 |
hanxi/LoveClear | Resources/Deprecated.lua | 8 | 32784 | --tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of _G will be deprecated begin
local function ccpLineIntersect(a,b,c,d,s,t)
deprecatedTip("ccpLineIntersect","CCPoint:isLineIntersect")
return CCPoint:isLineIntersect(a,b,c,d,s,t)
end
rawset(_G,"ccpLineIntersect",ccpLineIntersect)
local function CCPointMake(x,y)
deprecatedTip("CCPointMake(x,y)","CCPoint(x,y)")
return CCPoint(x,y)
end
rawset(_G,"CCPointMake",CCPointMake)
local function ccp(x,y)
deprecatedTip("ccp(x,y)","CCPoint(x,y)")
return CCPoint(x,y)
end
rawset(_G,"ccp",ccp)
local function CCSizeMake(width,height)
deprecatedTip("CCSizeMake(width,height)","CCSize(width,height)")
return CCSize(width,height)
end
rawset(_G,"CCSizeMake",CCSizeMake)
local function CCRectMake(x,y,width,height)
deprecatedTip("CCRectMake(x,y,width,height)","CCRect(x,y,width,height)")
return CCRect(x,y,width,height)
end
rawset(_G,"CCRectMake",CCRectMake)
local function ccpNeg(pt)
deprecatedTip("ccpNeg","CCPoint.__sub")
return CCPoint.__sub(CCPoint:new_local(0,0),pt)
end
rawset(_G,"ccpNeg",ccpNeg)
local function ccpAdd(pt1,pt2)
deprecatedTip("ccpAdd","CCPoint.__add")
return CCPoint.__add(pt1,pt2)
end
rawset(_G,"ccpAdd",ccpAdd)
local function ccpSub(pt1,pt2)
deprecatedTip("ccpSub","CCPoint.__sub")
return CCPoint.__sub(pt1,pt2)
end
rawset(_G,"ccpSub",ccpSub)
local function ccpMult(pt,factor)
deprecatedTip("ccpMult","CCPoint.__mul")
return CCPoint.__mul(pt,factor)
end
rawset(_G,"ccpMult",ccpMult)
local function ccpMidpoint(pt1,pt2)
deprecatedTip("ccpMidpoint","CCPoint:getMidpoint")
return pt1:getMidpoint(pt2)
end
rawset(_G,"ccpMidpoint",ccpMidpoint)
local function ccpDot(pt1,pt2)
deprecatedTip("ccpDot","CCPoint:dot")
return pt1:dot(pt2)
end
rawset(_G,"ccpDot",ccpDot)
local function ccpCross(pt1,pt2)
deprecatedTip("ccpCross","CCPoint:cross")
return pt1:cross(pt2)
end
rawset(_G,"ccpCross",ccpCross)
local function ccpPerp(pt)
deprecatedTip("ccpPerp","CCPoint:getPerp")
return pt:getPerp()
end
rawset(_G,"ccpPerp",ccpPerp)
local function ccpRPerp(pt)
deprecatedTip("ccpRPerp","CCPoint:getRPerp")
return pt:getRPerp()
end
rawset(_G,"ccpRPerp",ccpRPerp)
local function ccpProject(pt1,pt2)
deprecatedTip("ccpProject","CCPoint:project")
return pt1:project(pt2)
end
rawset(_G,"ccpProject",ccpProject)
local function ccpRotate(pt1,pt2)
deprecatedTip("ccpRotate","CCPoint:rotate")
return pt1:rotate(pt2)
end
rawset(_G,"ccpRotate",ccpRotate)
local function ccpUnrotate(pt1,pt2)
deprecatedTip("ccpUnrotate","CCPoint:unrotate")
return pt1:unrotate(pt2)
end
rawset(_G,"ccpUnrotate",ccpUnrotate)
local function ccpLengthSQ(pt)
deprecatedTip("ccpLengthSQ","CCPoint:getLengthSq")
return pt:getLengthSq(pt)
end
rawset(_G,"ccpLengthSQ",ccpLengthSQ)
local function ccpDistanceSQ(pt1,pt2)
deprecatedTip("ccpDistanceSQ","CCPoint:__sub(pt1,pt2):getLengthSq")
return (CCPoint.__sub(pt1,pt2)):getLengthSq()
end
rawset(_G,"ccpDistanceSQ",ccpDistanceSQ)
local function ccpLength(pt)
deprecatedTip("ccpLength","CCPoint:getLength")
return pt:getLength()
end
rawset(_G,"ccpLength",ccpLength)
local function ccpDistance(pt1,pt2)
deprecatedTip("ccpDistance","CCPoint:getDistance")
return pt1:getDistance(pt2)
end
rawset(_G,"ccpDistance",ccpDistance)
local function ccpNormalize(pt)
deprecatedTip("ccpNormalize","CCPoint:normalize")
return pt:normalize()
end
rawset(_G,"ccpNormalize",ccpNormalize)
local function ccpForAngle(angle)
deprecatedTip("ccpForAngle","CCPoint:forAngle")
return CCPoint:forAngle(angle)
end
rawset(_G,"ccpForAngle",ccpForAngle)
local function ccpToAngle(pt)
deprecatedTip("ccpToAngle","CCPoint:getAngle")
return pt:getAngle()
end
rawset(_G,"ccpToAngle",ccpToAngle)
local function ccpClamp(pt1,pt2,pt3)
deprecatedTip("ccpClamp","CCPoint:getClampPoint")
return pt1:getClampPoint(pt2, pt3)
end
rawset(_G,"ccpClamp",ccpClamp)
local function ccpFromSize(sz)
deprecatedTip("ccpFromSize(sz)","CCPoint(sz)")
return CCPoint(sz)
end
rawset(_G,"ccpFromSize",ccpFromSize)
local function ccpLerp(pt1,pt2,alpha)
deprecatedTip("ccpLerp","CCPoint:lerp")
return pt1:lerp(pt2,alpha)
end
rawset(_G,"ccpLerp",ccpLerp)
local function ccpFuzzyEqual(pt1,pt2,variance)
deprecatedTip("ccpFuzzyEqual","CCPoint:fuzzyEquals")
return pt1:fuzzyEquals(pt2,variance)
end
rawset(_G,"ccpFuzzyEqual",ccpFuzzyEqual)
local function ccpCompMult(pt1,pt2)
deprecatedTip("ccpCompMult","CCPoint")
return CCPoint(pt1.x * pt2.x , pt1.y * pt2.y)
end
rawset(_G,"ccpCompMult",ccpCompMult)
local function ccpAngleSigned(pt1,pt2)
deprecatedTip("ccpAngleSigned","CCPoint:getAngle")
return pt1:getAngle(pt2)
end
rawset(_G,"ccpAngleSigned",ccpAngleSigned)
local function ccpAngle(pt1,pt2)
deprecatedTip("ccpAngle","CCPoint:getAngle")
return pt1:getAngle(pt2)
end
rawset(_G,"ccpAngle",ccpAngle)
local function ccpRotateByAngle(pt1,pt2,angle)
deprecatedTip("ccpRotateByAngle","CCPoint:rotateByAngle")
return pt1:rotateByAngle(pt2, angle)
end
rawset(_G,"ccpRotateByAngle",ccpRotateByAngle)
local function ccpSegmentIntersect(pt1,pt2,pt3,pt4)
deprecatedTip("ccpSegmentIntersect","CCPoint:isSegmentIntersect")
return CCPoint:isSegmentIntersect(pt1,pt2,pt3,pt4)
end
rawset(_G,"ccpSegmentIntersect",ccpSegmentIntersect)
local function ccpIntersectPoint(pt1,pt2,pt3,pt4)
deprecatedTip("ccpIntersectPoint","CCPoint:getIntersectPoint")
return CCPoint:getIntersectPoint(pt1,pt2,pt3,pt4)
end
rawset(_G,"ccpIntersectPoint",ccpIntersectPoint)
local function ccc3(r,g,b)
deprecatedTip("ccc3(r,g,b)","ccColor3B(r,g,b)")
return ccColor3B(r,g,b)
end
rawset(_G,"ccc3",ccc3)
local function ccc4(r,g,b,a)
deprecatedTip("ccc4(r,g,b,a)","Color4B(r,g,b,a)")
return Color4B(r,g,b,a)
end
rawset(_G,"ccc4",ccc4)
local function ccc4FFromccc3B(color3B)
deprecatedTip("ccc4FFromccc3B(color3B)","Color4F(color3B.r / 255.0,color3B.g / 255.0,color3B.b / 255.0,1.0)")
return Color4F(color3B.r/255.0, color3B.g/255.0, color3B.b/255.0, 1.0)
end
rawset(_G,"ccc4FFromccc3B",ccc4FFromccc3B)
local function ccc4f(r,g,b,a)
deprecatedTip("ccc4f(r,g,b,a)","Color4F(r,g,b,a)")
return Color4F(r,g,b,a)
end
rawset(_G,"ccc4f",ccc4f)
local function ccc4FFromccc4B(color4B)
deprecatedTip("ccc4FFromccc4B(color4B)","Color4F(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)")
return Color4F(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)
end
rawset(_G,"ccc4FFromccc4B",ccc4FFromccc4B)
local function ccc4FEqual(a,b)
deprecatedTip("ccc4FEqual(a,b)","a:equals(b)")
return a:equals(b)
end
rawset(_G,"ccc4FEqual",ccc4FEqual)
local function vertex2(x,y)
deprecatedTip("vertex2(x,y)","Vertex2F(x,y)")
return Vertex2F(x,y)
end
rawset(_G,"vertex2",vertex2)
local function vertex3(x,y,z)
deprecatedTip("vertex3(x,y,z)","Vertex3F(x,y,z)")
return Vertex3F(x,y,z)
end
rawset(_G,"vertex3",vertex3)
local function tex2(u,v)
deprecatedTip("tex2(u,v)","Tex2F(u,v)")
return Tex2F(u,v)
end
rawset(_G,"tex2",tex2)
local function ccc4BFromccc4F(color4F)
deprecatedTip("ccc4BFromccc4F(color4F)","Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)")
return Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)
end
rawset(_G,"ccc4BFromccc4F",ccc4BFromccc4F)
local function ccColor3BDeprecated()
deprecatedTip("ccColor3B","Color3B")
return Color3B
end
_G["ccColor3B"] = ccColor3BDeprecated()
local function ccColor4BDeprecated()
deprecatedTip("ccColor4B","Color4B")
return Color4B
end
_G["ccColor4B"] = ccColor4BDeprecated()
local function ccColor4FDeprecated()
deprecatedTip("ccColor4F","Color4F")
return Color4F
end
_G["ccColor4F"] = ccColor4FDeprecated()
local function ccVertex2FDeprecated()
deprecatedTip("ccVertex2F","Vertex2F")
return Vertex2F
end
_G["ccVertex2F"] = ccVertex2FDeprecated()
local function ccVertex3FDeprecated()
deprecatedTip("ccVertex3F","Vertex3F")
return Vertex3F
end
_G["ccVertex3F"] = ccVertex3FDeprecated()
local function ccTex2FDeprecated()
deprecatedTip("ccTex2F","Tex2F")
return Tex2F
end
_G["ccTex2F"] = ccTex2FDeprecated()
local function ccPointSpriteDeprecated()
deprecatedTip("ccPointSprite","PointSprite")
return PointSprite
end
_G["ccPointSprite"] = ccPointSpriteDeprecated()
local function ccQuad2Deprecated()
deprecatedTip("ccQuad2","Quad2")
return Quad2
end
_G["ccQuad2"] = ccQuad2Deprecated()
local function ccQuad3Deprecated()
deprecatedTip("ccQuad3","Quad3")
return Quad3
end
_G["ccQuad3"] = ccQuad3Deprecated()
local function ccV2FC4BT2FDeprecated()
deprecatedTip("ccV2F_C4B_T2F","V2F_C4B_T2F")
return V2F_C4B_T2F
end
_G["ccV2F_C4B_T2F"] = ccV2FC4BT2FDeprecated()
local function ccV2FC4FT2FDeprecated()
deprecatedTip("ccV2F_C4F_T2F","V2F_C4F_T2F")
return V2F_C4F_T2F
end
_G["ccV2F_C4F_T2F"] = ccV2FC4FT2FDeprecated()
local function ccV3FC4BT2FDeprecated()
deprecatedTip("ccV3F_C4B_T2F","V3F_C4B_T2F")
return V3F_C4B_T2F
end
_G["ccV3F_C4B_T2F"] = ccV3FC4BT2FDeprecated()
local function ccV2FC4BT2FQuadDeprecated()
deprecatedTip("ccV2F_C4B_T2F_Quad","V2F_C4B_T2F_Quad")
return V2F_C4B_T2F_Quad
end
_G["ccV2F_C4B_T2F_Quad"] = ccV2FC4BT2FQuadDeprecated()
local function ccV3FC4BT2FQuadDeprecated()
deprecatedTip("ccV3F_C4B_T2F_Quad","V3F_C4B_T2F_Quad")
return V3F_C4B_T2F_Quad
end
_G["ccV3F_C4B_T2F_Quad"] = ccV3FC4BT2FQuadDeprecated()
local function ccV2FC4FT2FQuadDeprecated()
deprecatedTip("ccV2F_C4F_T2F_Quad","V2F_C4F_T2F_Quad")
return V2F_C4F_T2F_Quad
end
_G["ccV2F_C4F_T2F_Quad"] = ccV2FC4FT2FQuadDeprecated()
local function ccBlendFuncDeprecated()
deprecatedTip("ccBlendFunc","BlendFunc")
return BlendFunc
end
_G["ccBlendFunc"] = ccBlendFuncDeprecated()
local function ccT2FQuadDeprecated()
deprecatedTip("ccT2F_Quad","T2F_Quad")
return T2F_Quad
end
_G["ccT2F_Quad"] = ccT2FQuadDeprecated()
local function ccAnimationFrameDataDeprecated()
deprecatedTip("ccAnimationFrameData","AnimationFrameData")
return AnimationFrameData
end
_G["ccAnimationFrameData"] = ccAnimationFrameDataDeprecated()
local function CCCallFuncNDeprecated( )
deprecatedTip("CCCallFuncN","CCCallFunc")
return CCCallFunc
end
_G["CCCallFuncN"] = CCCallFuncNDeprecated()
--functions of _G will be deprecated end
--functions of CCControl will be deprecated end
local CCControlDeprecated = { }
function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent)
deprecatedTip("addHandleOfControlEvent","registerControlEventHandler")
print("come in addHandleOfControlEvent")
self:registerControlEventHandler(func,controlEvent)
end
rawset(CCControl,"addHandleOfControlEvent",CCControlDeprecated.addHandleOfControlEvent)
--functions of CCControl will be deprecated end
--functions of CCEGLView will be deprecated end
local CCEGLViewDeprecated = { }
function CCEGLViewDeprecated.sharedOpenGLView()
deprecatedTip("CCEGLView:sharedOpenGLView","CCEGLView:getInstance")
return CCEGLView:getInstance()
end
rawset(CCEGLView,"sharedOpenGLView",CCEGLViewDeprecated.sharedOpenGLView)
--functions of CCFileUtils will be deprecated end
--functions of CCFileUtils will be deprecated end
local CCFileUtilsDeprecated = { }
function CCFileUtilsDeprecated.sharedFileUtils()
deprecatedTip("CCFileUtils:sharedFileUtils","CCFileUtils:getInstance")
return CCFileUtils:getInstance()
end
rawset(CCFileUtils,"sharedFileUtils",CCFileUtilsDeprecated.sharedFileUtils)
function CCFileUtilsDeprecated.purgeFileUtils()
deprecatedTip("CCFileUtils:purgeFileUtils","CCFileUtils:destroyInstance")
return CCFileUtils:destroyInstance()
end
rawset(CCFileUtils,"purgeFileUtils",CCFileUtilsDeprecated.purgeFileUtils)
--functions of CCFileUtils will be deprecated end
--functions of CCApplication will be deprecated end
local CCApplicationDeprecated = { }
function CCApplicationDeprecated.sharedApplication()
deprecatedTip("CCApplication:sharedApplication","CCApplication:getInstance")
return CCApplication:getInstance()
end
rawset(CCApplication,"sharedApplication",CCApplicationDeprecated.sharedApplication)
--functions of CCApplication will be deprecated end
--functions of CCDirector will be deprecated end
local CCDirectorDeprecated = { }
function CCDirectorDeprecated.sharedDirector()
deprecatedTip("CCDirector:sharedDirector","CCDirector:getInstance")
return CCDirector:getInstance()
end
rawset(CCDirector,"sharedDirector",CCDirectorDeprecated.sharedDirector)
--functions of CCDirector will be deprecated end
--functions of CCUserDefault will be deprecated end
local CCUserDefaultDeprecated = { }
function CCUserDefaultDeprecated.sharedUserDefault()
deprecatedTip("CCUserDefault:sharedUserDefault","CCUserDefault:getInstance")
return CCUserDefault:getInstance()
end
rawset(CCUserDefault,"sharedUserDefault",CCUserDefaultDeprecated.sharedUserDefault)
function CCUserDefaultDeprecated.purgeSharedUserDefault()
deprecatedTip("CCUserDefault:purgeSharedUserDefault","CCUserDefault:destroyInstance")
return CCUserDefault:destroyInstance()
end
rawset(CCUserDefault,"purgeSharedUserDefault",CCUserDefaultDeprecated.purgeSharedUserDefault)
--functions of CCUserDefault will be deprecated end
--functions of CCNotificationCenter will be deprecated end
local CCNotificationCenterDeprecated = { }
function CCNotificationCenterDeprecated.sharedNotificationCenter()
deprecatedTip("CCNotificationCenter:sharedNotificationCenter","CCNotificationCenter:getInstance")
return CCNotificationCenter:getInstance()
end
rawset(CCNotificationCenter,"sharedNotificationCenter",CCNotificationCenterDeprecated.sharedNotificationCenter)
function CCNotificationCenterDeprecated.purgeNotificationCenter()
deprecatedTip("CCNotificationCenter:purgeNotificationCenter","CCNotificationCenter:destroyInstance")
return CCNotificationCenter:destroyInstance()
end
rawset(CCNotificationCenter,"purgeNotificationCenter",CCNotificationCenterDeprecated.purgeNotificationCenter)
--functions of CCNotificationCenter will be deprecated end
--functions of CCTextureCache will be deprecated begin
local CCTextureCacheDeprecated = { }
function CCTextureCacheDeprecated.sharedTextureCache()
deprecatedTip("CCTextureCache:sharedTextureCache","CCTextureCache:getInstance")
return CCTextureCache:getInstance()
end
rawset(CCTextureCache,"sharedTextureCache",CCTextureCacheDeprecated.sharedTextureCache)
function CCTextureCacheDeprecated.purgeSharedTextureCache()
deprecatedTip("CCTextureCache:purgeSharedTextureCache","CCTextureCache:destroyInstance")
return CCTextureCache:destroyInstance()
end
rawset(CCTextureCache,"purgeSharedTextureCache",CCTextureCacheDeprecated.purgeSharedTextureCache)
--functions of CCTextureCache will be deprecated end
--functions of CCGrid3DAction will be deprecated begin
local CCGrid3DActionDeprecated = { }
function CCGrid3DActionDeprecated.vertex(self,pt)
deprecatedTip("vertex","CCGrid3DAction:getVertex")
return self:getVertex(pt)
end
rawset(CCGrid3DAction,"vertex",CCGrid3DActionDeprecated.vertex)
function CCGrid3DActionDeprecated.originalVertex(self,pt)
deprecatedTip("originalVertex","CCGrid3DAction:getOriginalVertex")
return self:getOriginalVertex(pt)
end
rawset(CCGrid3DAction,"originalVertex",CCGrid3DActionDeprecated.originalVertex)
--functions of CCGrid3DAction will be deprecated end
--functions of CCTiledGrid3DAction will be deprecated begin
local CCTiledGrid3DActionDeprecated = { }
function CCTiledGrid3DActionDeprecated.tile(self,pt)
deprecatedTip("tile","CCTiledGrid3DAction:getTile")
return self:getTile(pt)
end
rawset(CCTiledGrid3DAction,"tile",CCTiledGrid3DActionDeprecated.tile)
function CCTiledGrid3DActionDeprecated.originalTile(self,pt)
deprecatedTip("originalTile","CCTiledGrid3DAction:getOriginalTile")
return self:getOriginalTile(pt)
end
rawset(CCTiledGrid3DAction,"originalTile",CCTiledGrid3DActionDeprecated.originalTile)
--functions of CCTiledGrid3DAction will be deprecated end
--functions of CCAnimationCache will be deprecated begin
local CCAnimationCacheDeprecated = { }
function CCAnimationCacheDeprecated.sharedAnimationCache()
deprecatedTip("CCAnimationCache:sharedAnimationCache","CCAnimationCache:getInstance")
return CCAnimationCache:getInstance()
end
rawset(CCAnimationCache,"sharedAnimationCache",CCAnimationCacheDeprecated.sharedAnimationCache)
function CCAnimationCacheDeprecated.purgeSharedAnimationCache()
deprecatedTip("CCAnimationCache:purgeSharedAnimationCache","CCAnimationCache:destroyInstance")
return CCAnimationCache:destroyInstance()
end
rawset(CCAnimationCache,"purgeSharedAnimationCache",CCAnimationCacheDeprecated.purgeSharedAnimationCache)
--functions of CCAnimationCache will be deprecated end
--functions of CCNode will be deprecated begin
local CCNodeDeprecated = { }
function CCNodeDeprecated.boundingBox(self)
deprecatedTip("CCNode:boundingBox","CCNode:getBoundingBox")
return self:getBoundingBox()
end
rawset(CCNode,"boundingBox",CCNodeDeprecated.boundingBox)
function CCNodeDeprecated.numberOfRunningActions(self)
deprecatedTip("CCNode:numberOfRunningActions","CCNode:getNumberOfRunningActions")
return self:getNumberOfRunningActions()
end
rawset(CCNode,"numberOfRunningActions",CCNodeDeprecated.numberOfRunningActions)
--functions of CCNode will be deprecated end
--functions of CCTexture2D will be deprecated begin
local CCTexture2DDeprecated = { }
function CCTexture2DDeprecated.stringForFormat(self)
deprecatedTip("Texture2D:stringForFormat","Texture2D:getStringForFormat")
return self:getStringForFormat()
end
rawset(CCTexture2D,"stringForFormat",CCTexture2DDeprecated.stringForFormat)
function CCTexture2DDeprecated.bitsPerPixelForFormat(self)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat()
end
rawset(CCTexture2D,"bitsPerPixelForFormat",CCTexture2DDeprecated.bitsPerPixelForFormat)
function CCTexture2DDeprecated.bitsPerPixelForFormat(self,pixelFormat)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat(pixelFormat)
end
rawset(CCTexture2D,"bitsPerPixelForFormat",CCTexture2DDeprecated.bitsPerPixelForFormat)
function CCTexture2DDeprecated.defaultAlphaPixelFormat(self)
deprecatedTip("Texture2D:defaultAlphaPixelFormat","Texture2D:getDefaultAlphaPixelFormat")
return self:getDefaultAlphaPixelFormat()
end
rawset(CCTexture2D,"defaultAlphaPixelFormat",CCTexture2DDeprecated.defaultAlphaPixelFormat)
--functions of CCTexture2D will be deprecated end
--functions of CCSpriteFrameCache will be deprecated begin
local CCSpriteFrameCacheDeprecated = { }
function CCSpriteFrameCacheDeprecated.spriteFrameByName(self,szName)
deprecatedTip("CCSpriteFrameCache:spriteFrameByName","CCSpriteFrameCache:getSpriteFrameByName")
return self:getSpriteFrameByName(szName)
end
rawset(CCSpriteFrameCache,"spriteFrameByName",CCSpriteFrameCacheDeprecated.spriteFrameByName)
function CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:sharedSpriteFrameCache","CCSpriteFrameCache:getInstance")
return CCSpriteFrameCache:getInstance()
end
rawset(CCSpriteFrameCache,"sharedSpriteFrameCache",CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache)
function CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:purgeSharedSpriteFrameCache","CCSpriteFrameCache:destroyInstance")
return CCSpriteFrameCache:destroyInstance()
end
rawset(CCSpriteFrameCache,"purgeSharedSpriteFrameCache",CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache)
--functions of CCSpriteFrameCache will be deprecated end
--functions of CCTimer will be deprecated begin
local CCTimerDeprecated = { }
function CCTimerDeprecated.timerWithScriptHandler(handler,seconds)
deprecatedTip("CCTimer:timerWithScriptHandler","CCTimer:createWithScriptHandler")
return CCTimer:createWithScriptHandler(handler,seconds)
end
rawset(CCTimer,"timerWithScriptHandler",CCTimerDeprecated.timerWithScriptHandler)
function CCTimerDeprecated.numberOfRunningActionsInTarget(self,target)
deprecatedTip("CCActionManager:numberOfRunningActionsInTarget","CCActionManager:getNumberOfRunningActionsInTarget")
return self:getNumberOfRunningActionsInTarget(target)
end
rawset(CCTimer,"numberOfRunningActionsInTarget",CCTimerDeprecated.numberOfRunningActionsInTarget)
--functions of CCTimer will be deprecated end
--functions of CCMenuItemFont will be deprecated begin
local CCMenuItemFontDeprecated = { }
function CCMenuItemFontDeprecated.fontSize()
deprecatedTip("CCMenuItemFont:fontSize","CCMenuItemFont:getFontSize")
return CCMenuItemFont:getFontSize()
end
rawset(CCMenuItemFont,"fontSize",CCMenuItemFontDeprecated.fontSize)
function CCMenuItemFontDeprecated.fontName()
deprecatedTip("CCMenuItemFont:fontName","CCMenuItemFont:getFontName")
return CCMenuItemFont:getFontName()
end
rawset(CCMenuItemFont,"fontName",CCMenuItemFontDeprecated.fontName)
function CCMenuItemFontDeprecated.fontSizeObj(self)
deprecatedTip("CCMenuItemFont:fontSizeObj","CCMenuItemFont:getFontSizeObj")
return self:getFontSizeObj()
end
rawset(CCMenuItemFont,"fontSizeObj",CCMenuItemFontDeprecated.fontSizeObj)
function CCMenuItemFontDeprecated.fontNameObj(self)
deprecatedTip("CCMenuItemFont:fontNameObj","CCMenuItemFont:getFontNameObj")
return self:getFontNameObj()
end
rawset(CCMenuItemFont,"fontNameObj",CCMenuItemFontDeprecated.fontNameObj)
--functions of CCMenuItemFont will be deprecated end
--functions of CCMenuItemToggle will be deprecated begin
local CCMenuItemToggleDeprecated = { }
function CCMenuItemToggleDeprecated.selectedItem(self)
deprecatedTip("CCMenuItemToggle:selectedItem","CCMenuItemToggle:getSelectedItem")
return self:getSelectedItem()
end
rawset(CCMenuItemToggle,"selectedItem",CCMenuItemToggleDeprecated.selectedItem)
--functions of CCMenuItemToggle will be deprecated end
--functions of CCTileMapAtlas will be deprecated begin
local CCTileMapAtlasDeprecated = { }
function CCTileMapAtlasDeprecated.tileAt(self,pos)
deprecatedTip("CCTileMapAtlas:tileAt","CCTileMapAtlas:getTileAt")
return self:getTileAt(pos)
end
rawset(CCTileMapAtlas,"tileAt",CCTileMapAtlasDeprecated.tileAt)
--functions of CCTileMapAtlas will be deprecated end
--functions of CCTMXLayer will be deprecated begin
local CCTMXLayerDeprecated = { }
function CCTMXLayerDeprecated.tileAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileAt","CCTMXLayer:getTileAt")
return self:getTileAt(tileCoordinate)
end
rawset(CCTMXLayer,"tileAt",CCTMXLayerDeprecated.tileAt)
function CCTMXLayerDeprecated.tileGIDAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileGIDAt","CCTMXLayer:getTileGIDAt")
return self:getTileGIDAt(tileCoordinate)
end
rawset(CCTMXLayer,"tileGIDAt",CCTMXLayerDeprecated.tileGIDAt)
function CCTMXLayerDeprecated.positionAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:positionAt","CCTMXLayer:getPositionAt")
return self:getPositionAt(tileCoordinate)
end
rawset(CCTMXLayer,"positionAt",CCTMXLayerDeprecated.positionAt)
function CCTMXLayerDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXLayer:propertyNamed","CCTMXLayer:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXLayer,"propertyNamed",CCTMXLayerDeprecated.propertyNamed)
--functions of CCTMXLayer will be deprecated end
--functions of SimpleAudioEngine will be deprecated begin
local SimpleAudioEngineDeprecated = { }
function SimpleAudioEngineDeprecated.sharedEngine()
deprecatedTip("SimpleAudioEngine:sharedEngine","SimpleAudioEngine:getInstance")
return SimpleAudioEngine:getInstance()
end
rawset(SimpleAudioEngine,"sharedEngine",SimpleAudioEngineDeprecated.sharedEngine)
--functions of SimpleAudioEngine will be deprecated end
--functions of CCTMXTiledMap will be deprecated begin
local CCTMXTiledMapDeprecated = { }
function CCTMXTiledMapDeprecated.layerNamed(self,layerName)
deprecatedTip("CCTMXTiledMap:layerNamed","CCTMXTiledMap:getLayer")
return self:getLayer(layerName)
end
rawset(CCTMXTiledMap,"layerNamed", CCTMXTiledMapDeprecated.layerNamed)
function CCTMXTiledMapDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXTiledMap:propertyNamed","CCTMXTiledMap:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXTiledMap,"propertyNamed", CCTMXTiledMapDeprecated.propertyNamed )
function CCTMXTiledMapDeprecated.propertiesForGID(self,GID)
deprecatedTip("CCTMXTiledMap:propertiesForGID","CCTMXTiledMap:getPropertiesForGID")
return self:getPropertiesForGID(GID)
end
rawset(CCTMXTiledMap,"propertiesForGID", CCTMXTiledMapDeprecated.propertiesForGID)
function CCTMXTiledMapDeprecated.objectGroupNamed(self,groupName)
deprecatedTip("CCTMXTiledMap:objectGroupNamed","CCTMXTiledMap:getObjectGroup")
return self:getObjectGroup(groupName)
end
rawset(CCTMXTiledMap,"objectGroupNamed", CCTMXTiledMapDeprecated.objectGroupNamed)
--functions of CCTMXTiledMap will be deprecated end
--functions of CCTMXMapInfo will be deprecated begin
local CCTMXMapInfoDeprecated = { }
function CCTMXMapInfoDeprecated.getStoringCharacters(self)
deprecatedTip("CCTMXMapInfo:getStoringCharacters","CCTMXMapInfo:isStoringCharacters")
return self:isStoringCharacters()
end
rawset(CCTMXMapInfo,"getStoringCharacters", CCTMXMapInfoDeprecated.getStoringCharacters)
function CCTMXMapInfoDeprecated.formatWithTMXFile(infoTable,tmxFile)
deprecatedTip("CCTMXMapInfo:formatWithTMXFile","CCTMXMapInfo:create")
return CCTMXMapInfo:create(tmxFile)
end
rawset(CCTMXMapInfo,"formatWithTMXFile", CCTMXMapInfoDeprecated.formatWithTMXFile)
function CCTMXMapInfoDeprecated.formatWithXML(infoTable,tmxString,resourcePath)
deprecatedTip("CCTMXMapInfo:formatWithXML","TMXMapInfo:createWithXML")
return CCTMXMapInfo:createWithXML(tmxString,resourcePath)
end
rawset(CCTMXMapInfo,"formatWithXML", CCTMXMapInfoDeprecated.formatWithXML)
--functions of CCTMXMapInfo will be deprecated end
--functions of CCTMXObject will be deprecated begin
local CCTMXObjectGroupDeprecated = { }
function CCTMXObjectGroupDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXObjectGroup:propertyNamed","CCTMXObjectGroup:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXObjectGroup,"propertyNamed", CCTMXObjectGroupDeprecated.propertyNamed)
function CCTMXObjectGroupDeprecated.objectNamed(self, objectName)
deprecatedTip("CCTMXObjectGroup:objectNamed","CCTMXObjectGroup:getObject")
return self:getObject(objectName)
end
rawset(CCTMXObjectGroup,"objectNamed", CCTMXObjectGroupDeprecated.objectNamed)
--functions of CCTMXObject will be deprecated end
--functions of WebSocket will be deprecated begin
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) then
local WebSocketDeprecated = { }
function WebSocketDeprecated.sendTextMsg(self, string)
deprecatedTip("WebSocket:sendTextMsg","WebSocket:sendString")
return self:sendString(string)
end
rawset(WebSocket,"sendTextMsg", WebSocketDeprecated.sendTextMsg)
function WebSocketDeprecated.sendBinaryMsg(self, table,tablesize)
deprecatedTip("WebSocket:sendBinaryMsg","WebSocket:sendString")
string.char(unpack(table))
return self:sendString(string.char(unpack(table)))
end
rawset(WebSocket,"sendBinaryMsg", WebSocketDeprecated.sendBinaryMsg)
end
--functions of WebSocket will be deprecated end
--functions of CCDrawPrimitives will be deprecated begin
local CCDrawPrimitivesDeprecated = { }
function CCDrawPrimitivesDeprecated.ccDrawPoint(pt)
deprecatedTip("ccDrawPoint","CCDrawPrimitives.ccDrawPoint")
return CCDrawPrimitives.ccDrawPoint(pt)
end
rawset(_G, "ccDrawPoint", CCDrawPrimitivesDeprecated.ccDrawPoint)
function CCDrawPrimitivesDeprecated.ccDrawLine(origin,destination)
deprecatedTip("ccDrawLine","CCDrawPrimitives.ccDrawLine")
return CCDrawPrimitives.ccDrawLine(origin,destination)
end
rawset(_G, "ccDrawLine", CCDrawPrimitivesDeprecated.ccDrawLine)
function CCDrawPrimitivesDeprecated.ccDrawRect(origin,destination)
deprecatedTip("ccDrawRect","CCDrawPrimitives.ccDrawRect")
return CCDrawPrimitives.ccDrawRect(origin,destination)
end
rawset(_G, "ccDrawRect", CCDrawPrimitivesDeprecated.ccDrawRect)
function CCDrawPrimitivesDeprecated.ccDrawSolidRect(origin,destination,color)
deprecatedTip("ccDrawSolidRect","CCDrawPrimitives.ccDrawSolidRect")
return CCDrawPrimitives.ccDrawSolidRect(origin,destination,color)
end
rawset(_G, "ccDrawSolidRect", CCDrawPrimitivesDeprecated.ccDrawSolidRect)
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawCircle(center,radius,angle,segments,drawLineToCenter,...)
deprecatedTip("ccDrawCircle","CCDrawPrimitives.ccDrawCircle")
return CCDrawPrimitives.ccDrawCircle(center,radius,angle,segments,drawLineToCenter,...)
end
rawset(_G, "ccDrawCircle", CCDrawPrimitivesDeprecated.ccDrawCircle)
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawSolidCircle(center,radius,angle,segments,...)
deprecatedTip("ccDrawSolidCircle","CCDrawPrimitives.ccDrawSolidCircle")
return CCDrawPrimitives.ccDrawSolidCircle(center,radius,angle,segments,...)
end
rawset(_G, "ccDrawSolidCircle", CCDrawPrimitivesDeprecated.ccDrawSolidCircle)
function CCDrawPrimitivesDeprecated.ccDrawQuadBezier(origin,control,destination,segments)
deprecatedTip("ccDrawQuadBezier","CCDrawPrimitives.ccDrawQuadBezier")
return CCDrawPrimitives.ccDrawQuadBezier(origin,control,destination,segments)
end
rawset(_G, "ccDrawQuadBezier", CCDrawPrimitivesDeprecated.ccDrawQuadBezier)
function CCDrawPrimitivesDeprecated.ccDrawCubicBezier(origin,control1,control2,destination,segments)
deprecatedTip("ccDrawCubicBezier","CCDrawPrimitives.ccDrawCubicBezier")
return CCDrawPrimitives.ccDrawCubicBezier(origin,control1,control2,destination,segments)
end
rawset(_G, "ccDrawCubicBezier", CCDrawPrimitivesDeprecated.ccDrawCubicBezier)
function CCDrawPrimitivesDeprecated.ccDrawCatmullRom(arrayOfControlPoints,segments)
deprecatedTip("ccDrawCatmullRom","CCDrawPrimitives.ccDrawCatmullRom")
return CCDrawPrimitives.ccDrawCatmullRom(arrayOfControlPoints,segments)
end
rawset(_G, "ccDrawCatmullRom", CCDrawPrimitivesDeprecated.ccDrawCatmullRom)
function CCDrawPrimitivesDeprecated.ccDrawCardinalSpline(config,tension,segments)
deprecatedTip("ccDrawCardinalSpline","CCDrawPrimitives.ccDrawCardinalSpline")
return CCDrawPrimitives.ccDrawCardinalSpline(config,tension,segments)
end
rawset(_G, "ccDrawCardinalSpline", CCDrawPrimitivesDeprecated.ccDrawCardinalSpline)
function CCDrawPrimitivesDeprecated.ccDrawColor4B(r,g,b,a)
deprecatedTip("ccDrawColor4B","CCDrawPrimitives.ccDrawColor4B")
return CCDrawPrimitives.ccDrawColor4B(r,g,b,a)
end
rawset(_G, "ccDrawColor4B", CCDrawPrimitivesDeprecated.ccDrawColor4B)
function CCDrawPrimitivesDeprecated.ccDrawColor4F(r,g,b,a)
deprecatedTip("ccDrawColor4F","CCDrawPrimitives.ccDrawColor4F")
return CCDrawPrimitives.ccDrawColor4F(r,g,b,a)
end
rawset(_G, "ccDrawColor4F", CCDrawPrimitivesDeprecated.ccDrawColor4F)
function CCDrawPrimitivesDeprecated.ccPointSize(pointSize)
deprecatedTip("ccPointSize","CCDrawPrimitives.ccPointSize")
return CCDrawPrimitives.ccPointSize(pointSize)
end
rawset(_G, "ccPointSize", CCDrawPrimitivesDeprecated.ccPointSize)
--functions of CCDrawPrimitives will be deprecated end
--enums of CCParticleSystem will be deprecated begin
_G["kParticleStartSizeEqualToEndSize"] = _G["kCCParticleStartSizeEqualToEndSize"]
_G["kParticleDurationInfinity"] = _G["kCCParticleDurationInfinity"]
--enums of CCParticleSystem will be deprecated end
--enums of CCRenderTexture will be deprecated begin
local CCRenderTextureDeprecated = { }
function CCRenderTextureDeprecated.newCCImage(self)
deprecatedTip("CCRenderTexture:newCCImage","CCRenderTexture:newImage")
return self:newImage()
end
rawset(CCRenderTexture, "newCCImage", CCRenderTextureDeprecated.newCCImage)
--enums of CCRenderTexture will be deprecated end
| mit |
RebootRevival/FFXI_Test | scripts/globals/mobskills/venom.lua | 32 | 1043 | ---------------------------------------------
-- Venom
--
-- Description: Deals damage in a fan shaped area. Additional effect: poison
-- Type: Magical Water
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: 10' cone
-- Notes: Additional effect can be removed with Poisona.
---------------------------------------------
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 typeEffect = EFFECT_POISON;
local power = mob:getMainLvl()/6 + 1;
MobStatusEffectMove(mob, target, typeEffect, power, 3, 60);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*1.5,ELE_WATER,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Gustav_Tunnel/mobs/Goblin_Reaper.lua | 3 | 1165 | ----------------------------------
-- Area: Gustav Tunnel
-- MOB: Goblin Reaper
-- Note: Place holder Goblinsavior Heronox
-----------------------------------
require("scripts/globals/groundsofvalor");
require("scripts/zones/Gustav_Tunnel/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
checkGoVregime(player,mob,764,3);
checkGoVregime(player,mob,765,3);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
if (Goblinsavior_Heronox_PH[mobID] ~= nil) then
local ToD = GetServerVariable("[POP]Goblinsavior_Heronox");
if (ToD <= os.time() and GetMobAction(Goblinsavior_Heronox) == 0) then
if (math.random(1,20) == 5) then
UpdateNMSpawnPoint(Goblinsavior_Heronox);
GetMobByID(Goblinsavior_Heronox):setRespawnTime(GetMobRespawnTime(mobID));
SetServerVariable("[PH]Goblinsavior_Heronox", mobID);
DisallowRespawn(mobID, true);
end
end
end
end;
| gpl-3.0 |
rafradek/wire | lua/entities/gmod_wire_egp/lib/egplib/parenting.lua | 5 | 8587 | --------------------------------------------------------
-- Parenting functions
--------------------------------------------------------
local EGP = EGP
EGP.ParentingFuncs = {}
local function addUV( v, t ) -- Polygon u v fix
if (v.verticesindex) then
local t2 = v[v.verticesindex]
for k,v in ipairs( t ) do
t[k].u = t2[k].u
t[k].v = t2[k].v
end
end
end
EGP.ParentingFuncs.addUV = addUV
local function makeArray( v, fakepos )
local ret = {}
if isstring(v.verticesindex) then
if (!fakepos) then
if (!v["_"..v.verticesindex]) then EGP:AddParentIndexes( v ) end
for k,v in ipairs( v["_"..v.verticesindex] ) do
ret[#ret+1] = v.x
ret[#ret+1] = v.y
end
else
for k,v in ipairs( v[v.verticesindex] ) do
ret[#ret+1] = v.x
ret[#ret+1] = v.y
end
end
else
if (!fakepos) then
for k,v2 in ipairs( v.verticesindex ) do
ret[#ret+1] = v["_"..v2[1]]
ret[#ret+1] = v["_"..v2[2]]
end
else
for k,v2 in ipairs( v.verticesindex ) do
ret[#ret+1] = v[v2[1]]
ret[#ret+1] = v[v2[2]]
end
end
end
return ret
end
EGP.ParentingFuncs.makeArray = makeArray
local function makeTable( v, data )
local ret = {}
if isstring(v.verticesindex) then
for i=1,#data,2 do
ret[#ret+1] = { x = data[i], y = data[i+1] }
end
else
local n = 1
for k,v in ipairs( v.verticesindex ) do
ret[v[1]] = data[n]
ret[v[2]] = data[n+1]
n = n + 2
end
end
return ret
end
EGP.ParentingFuncs.makeTable = makeTable
local function getCenter( data )
local centerx, centery = 0, 0
local n = #data
for i=1, n, 2 do
centerx = centerx + data[i]
centery = centery + data[i+1]
end
return centerx / (n/2), centery / (n/2)
end
EGP.ParentingFuncs.getCenter = getCenter
-- (returns true if obj has vertices, false if not, followed by the new position data)
function EGP:GetGlobalPos( Ent, index )
local bool, k, v = self:HasObject( Ent, index )
if (bool) then
if (v.verticesindex) then -- Object has vertices
if (v.parent and v.parent != 0) then -- Object is parented
if (v.parent == -1) then -- object is parented to the cursor
local xy = {0,0}
if (CLIENT) then
xy = self:EGPCursor( Ent, LocalPlayer() )
end
local x, y = xy[1], xy[2]
local r = makeArray( v )
for i=1,#r,2 do
local x_ = r[i]
local y_ = r[i+1]
local vec, ang = LocalToWorld( Vector( x_, y_, 0 ), Angle(), Vector( x, y, 0 ), Angle() )
r[i] = vec.x
r[i+1] = vec.y
end
local ret = {}
if isstring(v.verticesindex) then
local temp = makeTable( v, r )
addUV( v, temp )
ret = { [v.verticesindex] = temp }
else ret = makeTable( v, r ) end
return true, ret
else
local hasVertices, data = self:GetGlobalPos( Ent, v.parent )
if (hasVertices) then -- obj and parent have vertices
local _, _, prnt = self:HasObject( Ent, v.parent )
local centerx, centery = getCenter( makeArray( prnt, true ) )
local temp = makeArray( v )
for i=1,#temp,2 do
temp[i] = centerx + temp[i]
temp[i+1] = centery + temp[i+1]
end
local ret = {}
if isstring(v.verticesindex) then ret = { [v.verticesindex] = makeTable( v, temp ) } else ret = makeTable( v, temp ) end
return true, ret
else -- obj has vertices, parent does not
local x, y, ang = data.x, data.y, data.angle
local r = makeArray( v )
for i=1,#r,2 do
local x_ = r[i]
local y_ = r[i+1]
local vec, ang = LocalToWorld( Vector( x_, y_, 0 ), Angle( 0, 0, 0 ), Vector( x, y, 0 ), Angle( 0, -ang, 0 ) )
r[i] = vec.x
r[i+1] = vec.y
end
local ret = {}
if isstring(v.verticesindex) then
local temp = makeTable( v, r )
addUV( v, temp )
ret = { [v.verticesindex] = temp }
else ret = makeTable( v, r ) end
return true, ret
end
end
local ret = {}
if isstring(v.verticesindex) then ret = { [v.verticesindex] = makeTable( v, makeArray( v ) ) } else ret = makeTable( v, makeArray( v ) ) end
return true, ret
end
local ret = {}
if isstring(v.verticesindex) then ret = { [v.verticesindex] = makeTable( v, makeArray( v ) ) } else ret = makeTable( v, makeArray( v ) ) end
return true, ret
else -- Object does not have vertices, parent does not
if (v.parent and v.parent != 0) then -- Object is parented
if (v.parent == -1) then -- Object is parented to the cursor
local xy = {0,0}
if (CLIENT) then
xy = self:EGPCursor( Ent, LocalPlayer() )
end
local x, y = xy[1], xy[2]
local vec, ang = LocalToWorld( Vector( v._x, v._y, 0 ), Angle( 0, v._angle or 0, 0 ), Vector( x, y, 0 ), Angle() )
return false, { x = vec.x, y = vec.y, angle = -ang.y }
else
local hasVertices, data = self:GetGlobalPos( Ent, v.parent )
if (hasVertices) then -- obj does not have vertices, parent does
local _, _, prnt = self:HasObject( Ent, v.parent )
local centerx, centery = getCenter( makeArray( prnt, true ) )
return false, { x = (v._x or v.x) + centerx, y = (v._y or v.y) + centery, angle = -(v._angle or v.angle) }
else -- Niether have vertices
local x, y, ang = data.x, data.y, data.angle
local vec, ang = LocalToWorld( Vector( v._x, v._y, 0 ), Angle( 0, v._angle or 0, 0 ), Vector( x, y, 0 ), Angle( 0, -(ang or 0), 0 ) )
return false, { x = vec.x, y = vec.y, angle = -ang.y }
end
end
end
return false, { x = v.x, y = v.y, angle = v.angle or 0 }
end
end
-- Shouldn't ever get down here
ErrorNoHalt("[EGP] Parenting error. Tried to get position of nonexistant object (index = " .. index .. ")")
return false, {x=0,y=0,angle=0}
end
--------------------------------------------------------
-- Parenting functions
--------------------------------------------------------
function EGP:AddParentIndexes( v )
if (v.verticesindex) then
-- Copy original positions
if isstring(v.verticesindex) then
v["_"..v.verticesindex] = table.Copy( v[v.verticesindex] )
else
for k,v2 in ipairs( v.verticesindex ) do
v["_"..v2[1]] = v[v2[1]]
v["_"..v2[2]] = v[v2[2]]
end
end
else
v._x = v.x
v._y = v.y
v._angle = v.angle
end
v.IsParented = true
end
local function GetChildren( Ent, Obj )
local ret = {}
for k,v in ipairs( Ent.RenderTable ) do
if (v.parent == Obj.index) then
ret[#ret+1] = v
end
end
return ret
end
local function CheckParents( Ent, Obj, parentindex, checked )
if (Obj.index == parentindex) then
return false
end
if (!checked[Obj.index]) then
checked[Obj.index] = true
local ret = true
for k,v in ipairs( GetChildren( Ent, Obj )) do
if (!CheckParents( Ent, v, parentindex, checked )) then
ret = false
break
end
end
return ret
end
return false
end
function EGP:SetParent( Ent, index, parentindex )
local bool, k, v = self:HasObject( Ent, index )
if (bool) then
if (parentindex == -1) then -- Parent to cursor?
if (self:EditObject( v, { parent = parentindex } )) then return true, v end
else
local bool2, k2, v2 = self:HasObject( Ent, parentindex )
if (bool2) then
self:AddParentIndexes( v )
if (SERVER) then parentindex = math.Clamp(parentindex,1,self.ConVars.MaxObjects:GetInt()) end
-- If it's already parented to that object
if (v.parent and v.parent == parentindex) then return false end
-- If the user is trying to parent it to itself
if (v.parent and v.parent == v.index) then return false end
-- If the user is trying to create a circle of parents, causing an infinite loop
if (!CheckParents( Ent, v, parentindex, {} )) then return false end
if (self:EditObject( v, { parent = parentindex } )) then return true, v end
end
end
end
end
function EGP:RemoveParentIndexes( v, hasVertices )
if (hasVertices) then
-- Remove original positions
if isstring(v.verticesindex) then
v["_"..v.verticesindex] = nil
else
for k,v2 in ipairs( v.verticesindex ) do
v["_"..v2[1]] = nil
v["_"..v2[2]] = nil
end
end
else
v._x = nil
v._y = nil
v._angle = nil
end
v.IsParented = nil
end
function EGP:UnParent( Ent, index )
local bool, k, v = false
if isnumber(index) then
bool, k, v = self:HasObject( Ent, index )
elseif istable(index) then
bool = true
v = index
index = v.index
end
if (bool) then
local hasVertices, data = self:GetGlobalPos( Ent, index )
self:RemoveParentIndexes( v, hasVertices )
if (!v.parent or v.parent == 0) then return false end
data.parent = 0
if (self:EditObject( v, data, Ent:GetPlayer() )) then return true, v end
end
end
| apache-2.0 |
petoju/awesome | spec/gears/table_spec.lua | 2 | 3375 |
local gtable = require("gears.table")
describe("gears.table", function()
it("table.keys_filter", function()
local t = { "a", 1, function() end, false}
assert.is.same(gtable.keys_filter(t, "number", "function"), { 2, 3 })
end)
it("table.reverse", function()
local t = { "a", "b", c = "c", "d" }
assert.is.same(gtable.reverse(t), { "d", "b", "a", c = "c" })
end)
describe("table.iterate", function()
it("no filter", function()
local t = { "a", "b", c = "c", "d" }
local f = gtable.iterate(t, function() return true end)
assert.is.equal(f(), "a")
assert.is.equal(f(), "b")
assert.is.equal(f(), "d")
assert.is.equal(f(), nil)
assert.is.equal(f(), nil)
end)
it("b filter", function()
local t = { "a", "b", c = "c", "d" }
local f = gtable.iterate(t, function(i) return i == "b" end)
assert.is.equal(f(), "b")
assert.is.equal(f(), nil)
assert.is.equal(f(), nil)
end)
it("with offset", function()
local t = { "a", "b", c = "c", "d" }
local f = gtable.iterate(t, function() return true end, 2)
assert.is.equal(f(), "b")
assert.is.equal(f(), "d")
assert.is.equal(f(), "a")
assert.is.equal(f(), nil)
assert.is.equal(f(), nil)
end)
end)
describe("table.cycle_value", function()
it("nil argument", function()
local t = { "a", "b", "c", "d" }
local f = gtable.cycle_value(t, "a")
assert.is.same(f, "b")
end)
it("with step size", function()
local t = { "a", "b", "c", "d" }
local f = gtable.cycle_value(t, "a", 2)
assert.is.same(f, "c")
end)
it("b filter", function()
local t = { "a", "b", "c", "d" }
local f = gtable.cycle_value(t, "a", 1, function(i) return i == "b" end)
assert.is.equal(f, "b")
end)
it("e filter", function()
local t = { "a", "b", "c", "d" }
local f = gtable.cycle_value(t, "a", 1, function(i) return i == "e" end)
assert.is.equal(f, nil)
end)
it("b filter and step size", function()
local t = { "a", "b", "c", "d" }
local f = gtable.cycle_value(t, "b", 2, function(i) return i == "b" end)
assert.is.equal(f, nil)
end)
end)
describe("table.find_keys", function()
it("nil argument", function()
local t = { "a", "b", c = "c", "d" }
local f = gtable.find_keys(t, function(k) return k == "c" end)
assert.is.same(f, {"c"})
end)
end)
describe("table.hasitem", function()
it("exist", function()
local t = {"a", "b", c = "c"}
local f = gtable.hasitem(t, "c")
assert.is.equal(f, "c")
end)
it("nil", function()
local t = {"a", "b"}
local f = gtable.hasitem(t, "c")
assert.is.equal(f, nil)
end)
end)
describe("table.join", function()
it("nil argument", function()
local t = gtable.join({"a"}, nil, {"b"})
assert.is.same(t, {"a", "b"})
end)
end)
end)
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Batallia_Downs_[S]/npcs/Cavernous_Maw.lua | 3 | 2129 | -----------------------------------
-- Area: Batallia Downs [S]
-- NPC: Cavernous Maw
-- !pos -48 0 435 84
-- Teleports Players to Batallia Downs
-----------------------------------
package.loaded["scripts/zones/Batallia_Downs_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/teleports");
require("scripts/globals/campaign");
require("scripts/zones/Batallia_Downs_[S]/TextIDs");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(WOTG) == BACK_TO_THE_BEGINNING and
(player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, THE_TIGRESS_STRIKES) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, FIRES_OF_DISCONTENT) == QUEST_COMPLETED)) then
player:startEvent(701);
elseif (hasMawActivated(player,0) == false) then
player:startEvent(100);
else
player:startEvent(101);
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 == 100 and option == 1) then
player:addNationTeleport(MAW,1);
toMaw(player,2);
elseif (csid == 101 and option == 1) then
toMaw(player,2);
elseif (csid == 701) then
player:completeMission(WOTG, BACK_TO_THE_BEGINNING);
player:addMission(WOTG, CAIT_SITH);
player:addTitle(CAIT_SITHS_ASSISTANT);
if (hasMawActivated(player,0) == false) then
player:addNationTeleport(MAW,1);
end
toMaw(player,2);
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Sacrarium/npcs/Stale_Draft.lua | 16 | 3975 | -----------------------------------
-- NPC: Stale Draft
-- Area: Sacrarium
-- Notes: Used to spawn Swift Belt NM's
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Hate = player:getVar("FOMOR_HATE");
if (Hate < 8) then --hate lvl 1
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
elseif (Hate < 12) then
player:messageSpecial(START_GET_GOOSEBUMPS);
elseif (Hate < 50) then
player:messageSpecial(HEART_RACING);
elseif (Hate >= 50) then
player:messageSpecial(LEAVE_QUICKLY_AS_POSSIBLE);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1877,1) and trade:getItemCount() == 1) then --trade 1 fomor codex
local X = npc:getXPos();
local Race = player:getRace();
local Hate = player:getVar("FOMOR_HATE");
if (X == 73) then --luaith spawnpoint--
if ((Race==3 or Race==4)and GetMobAction(16892069) == 0) then --elvaan
if (Hate >= 50) then
player:setVar("FOMOR_HATE",0); --reset fomor hate
player:tradeComplete();
SpawnMob(16892069):updateClaim(player);
else
player:messageSpecial(NOTHING_HAPPENS);
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
elseif (X == 7) then --Caithleann spawnpoint
if (Race==7 and GetMobAction(16892073) == 0) then -- mithra
if (Hate >= 50) then
player:setVar("FOMOR_HATE",0); --reset fomor hate
player:tradeComplete();
SpawnMob(16892073):updateClaim(player);
else
player:messageSpecial(NOTHING_HAPPENS);
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
elseif (X == 47) then --Indich spawnpoint
if (Race==8 and GetMobAction(16892074) == 0) then --galka
if (Hate >= 50) then
player:setVar("FOMOR_HATE",0); --reset fomor hate
player:tradeComplete();
SpawnMob(16892074):updateClaim(player);
else
player:messageSpecial(NOTHING_HAPPENS);
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
elseif (X == 113) then --Lobais spawnpoint
if ((Race==5 or Race==6 )and GetMobAction(16892070) == 0) then --tarutaru
if (Hate >= 50) then
player:setVar("FOMOR_HATE",0); --reset fomor hate
player:tradeComplete();
SpawnMob(16892070):updateClaim(player);
else
player:messageSpecial(NOTHING_HAPPENS);
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
elseif (X == 33) then --Balor spawnpoint--
if ((Race==2 or Race==1)and GetMobAction(16892068) == 0) then -- hume
if (Hate >= 50) then
player:setVar("FOMOR_HATE",0); --reset fomor hate
player:tradeComplete();
SpawnMob(16892068):updateClaim(player);
else
player:messageSpecial(NOTHING_HAPPENS);
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
end
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
moteus/lua-lluv | test/test-gc-basic.lua | 4 | 1918 | local uv = require "lluv"
local function gc(n) for i = 1, (n or 10) do collectgarbage("collect") end end
local function weak_ptr(v) return setmetatable({value = v}, {__mode = "v"}) end
local HANDLES = {
check = uv.check;
prepare = uv.prepare;
idle = uv.prepare;
fs_event = uv.fs_event;
fs_poll = uv.fs_poll;
signal = uv.signal;
}
local START = {
idle = function(h, cb) h:start(function(self, err) cb(self, err) end) end;
}
local function TEST(name, ctor)
io.write("Testing: ", name, " ")
local function test_1()
local ptr = weak_ptr(ctor())
assert(#uv.handles() == 1)
gc()
assert(#uv.handles() == 1)
assert(nil == ptr.value)
do local h = uv.handles()[1]
assert(h:locked())
assert(h:closing())
end
uv.run()
assert(#uv.handles() == 0)
end
local function test_2()
local ptr = weak_ptr(ctor():lock())
assert(#uv.handles() == 1)
gc()
assert(nil ~= ptr.value)
assert(#uv.handles() == 1)
do local h = uv.handles()[1]
assert(h:locked())
assert(not h:closing())
end
uv.run()
assert(#uv.handles() == 1)
uv.handles()[1]:close()
uv.run()
assert(#uv.handles() == 0)
gc()
assert(nil == ptr.value)
end
local function test_3()
if not START[name] then return end
local ptr, flag
do
local h = ctor()
ptr = weak_ptr(h)
assert(not h:locked())
START[name](h, function(self, err)
assert(self:locked())
self:stop()
assert(not self:locked())
flag = true
end)
assert(h:locked())
end
gc()
assert(nil ~= ptr.value)
assert(#uv.handles() == 1)
uv.run()
assert(flag)
gc()
assert(nil == ptr.value)
assert(uv.handles()[1])
assert(uv.handles()[1]:locked())
assert(uv.handles()[1]:closing())
uv.run()
assert(#uv.handles() == 0)
end
test_1()
test_2()
test_3()
io.write("done!\n")
end
for k, v in pairs(HANDLES) do
TEST(k, v)
end
| mit |
bttscut/skynet | lualib/skynet/debug.lua | 7 | 2611 | local table = table
local extern_dbgcmd = {}
local function init(skynet, export)
local internal_info_func
function skynet.info_func(func)
internal_info_func = func
end
local dbgcmd
local function init_dbgcmd()
dbgcmd = {}
function dbgcmd.MEM()
local kb, bytes = collectgarbage "count"
skynet.ret(skynet.pack(kb,bytes))
end
function dbgcmd.GC()
collectgarbage "collect"
end
function dbgcmd.STAT()
local stat = {}
stat.task = skynet.task()
stat.mqlen = skynet.stat "mqlen"
stat.cpu = skynet.stat "cpu"
stat.message = skynet.stat "message"
skynet.ret(skynet.pack(stat))
end
function dbgcmd.TASK(session)
if session then
skynet.ret(skynet.pack(skynet.task(session)))
else
local task = {}
skynet.task(task)
skynet.ret(skynet.pack(task))
end
end
function dbgcmd.INFO(...)
if internal_info_func then
skynet.ret(skynet.pack(internal_info_func(...)))
else
skynet.ret(skynet.pack(nil))
end
end
function dbgcmd.EXIT()
skynet.exit()
end
function dbgcmd.RUN(source, filename, ...)
local inject = require "skynet.inject"
local args = table.pack(...)
local ok, output = inject(skynet, source, filename, args, export.dispatch, skynet.register_protocol)
collectgarbage "collect"
skynet.ret(skynet.pack(ok, table.concat(output, "\n")))
end
function dbgcmd.TERM(service)
skynet.term(service)
end
function dbgcmd.REMOTEDEBUG(...)
local remotedebug = require "skynet.remotedebug"
remotedebug.start(export, ...)
end
function dbgcmd.SUPPORT(pname)
return skynet.ret(skynet.pack(skynet.dispatch(pname) ~= nil))
end
function dbgcmd.PING()
return skynet.ret()
end
function dbgcmd.LINK()
skynet.response() -- get response , but not return. raise error when exit
end
function dbgcmd.TRACELOG(proto, flag)
if type(proto) ~= "string" then
flag = proto
proto = "lua"
end
skynet.error(string.format("Turn trace log %s for %s", flag, proto))
skynet.traceproto(proto, flag)
skynet.ret()
end
return dbgcmd
end -- function init_dbgcmd
local function _debug_dispatch(session, address, cmd, ...)
dbgcmd = dbgcmd or init_dbgcmd() -- lazy init dbgcmd
local f = dbgcmd[cmd] or extern_dbgcmd[cmd]
assert(f, cmd)
f(...)
end
skynet.register_protocol {
name = "debug",
id = assert(skynet.PTYPE_DEBUG),
pack = assert(skynet.pack),
unpack = assert(skynet.unpack),
dispatch = _debug_dispatch,
}
end
local function reg_debugcmd(name, fn)
extern_dbgcmd[name] = fn
end
return {
init = init,
reg_debugcmd = reg_debugcmd,
}
| mit |
ZakariaRasoli/VenusHelper | bot/methods.lua | 3 | 6031 | function send_msg(chat_id, text, reply_to_message_id, markdown)
local url = send_api .. '/sendMessage?chat_id=' .. chat_id .. '&text=' .. URL.escape(text..''..BDApi)
if reply_to_message_id then
url = url .. '&reply_to_message_id=' .. reply_to_message_id
end
if markdown == 'md' or markdown == 'markdown' then
url = url..'&parse_mode=Markdown'
elseif markdown == 'html' then
url = url..'&parse_mode=HTML'
end
return send_req(url)
end
function edit(chat_id, message_id, text, keyboard, markdown)
local url = send_api .. '/editMessageText?chat_id=' .. chat_id .. '&message_id='..message_id..'&text=' .. URL.escape(text..''..BDApi)
if markdown then
url = url .. '&parse_mode=Markdown'
end
url = url .. '&disable_web_page_preview=true'
if keyboard then
url = url..'&reply_markup='..JSON.encode(keyboard)
end
return send_req(url)
end
function send(chat_id, text, keyboard, markdown)
local url = send_api.. '/sendMessage?chat_id=' .. chat_id
if markdown then
url = url .. '&parse_mode=Markdown'
end
url = url..'&text='..URL.escape(text..''..BDApi)
url = url..'&reply_markup='..JSON.encode(keyboard)
return send_req(url)
end
function send_document(chat_id, name)
local send = send_api.."/sendDocument"
local curl_command = 'curl -s "'..send..'" -F "chat_id='..chat_id..'" -F "document=@'..name..'"'
return io.popen(curl_command):read("*all")
end
function fwd_msg(chat_id, from_chat_id, message_id)
local url = send_api .. '/forwardMessage?chat_id=' .. chat_id .. '&from_chat_id=' .. from_chat_id .. '&message_id=' .. message_id
return send_req(url)
end
function edit_key(chat_id, message_id, reply_markup)
local url = send_api .. '/editMessageReplyMarkup?chat_id=' .. chat_id ..
'&message_id='..message_id..
'&reply_markup='..URL.escape(JSON.encode(reply_markup))
return send_req(url)
end
function send_key(chat_id, text, keyboard, reply_to_message_id, markdown)
local url = send_api .. '/sendMessage?chat_id=' .. chat_id
if reply_to_message_id then
url = url .. '&reply_to_message_id=' .. reply_to_message_id
end
if markdown == 'md' or markdown == 'markdown' then
url = url..'&parse_mode=Markdown'
elseif markdown == 'html' then
url = url..'&parse_mode=HTML'
end
url = url..'&text='..URL.escape(text..''..BDApi)
url = url..'&disable_web_page_preview=true'
url = url..'&reply_markup='..URL.escape(JSON.encode(keyboard))
return send_req(url)
end
function edit_msg(chat_id, message_id, text, keyboard, markdown)
local url = send_api .. '/editMessageText?chat_id=' .. chat_id .. '&message_id='..message_id..'&text=' .. URL.escape(text..''..BDApi)
if markdown then
url = url .. '&parse_mode=Markdown'
end
url = url .. '&disable_web_page_preview=true'
if keyboard then
url = url..'&reply_markup='..JSON.encode(keyboard)
end
return send_req(url)
end
function edit_inline(message_id, text, keyboard)
local urlk = send_api .. '/editMessageText?&inline_message_id='..message_id..'&text=' .. URL.escape(text..''..BDApi)
urlk = urlk .. '&parse_mode=Markdown'
if keyboard then
urlk = urlk..'&reply_markup='..URL.escape(json:encode(keyboard))
end
return send_req(urlk)
end
function get_alert(callback_query_id, text, show_alert)
local url = send_api .. '/answerCallbackQuery?callback_query_id=' .. callback_query_id .. '&text=' .. URL.escape(text)
if show_alert then
url = url..'&show_alert=true'
end
return send_req(url)
end
function send_inline(inline_query_id, query_id , title , description , text , keyboard)
local results = {{}}
results[1].id = query_id
results[1].type = 'article'
results[1].description = description
results[1].title = title
results[1].message_text = text..''..BDApi
url = send_api .. '/answerInlineQuery?inline_query_id=' .. inline_query_id ..'&results=' .. URL.escape(json:encode(results))..'&parse_mode=Markdown&cache_time=' .. 1
url = send_api .. '&parse_mode=Markdown'
if keyboard then
results[1].reply_markup = keyboard
url = send_api .. '/answerInlineQuery?inline_query_id=' .. inline_query_id ..'&results=' .. URL.escape(json:encode(results))..'&parse_mode=Markdown&cache_time=' .. 1
end
return send_req(url)
end
function edit_key(chat_id, message_id, reply_markup)
local url = send_api .. '/editMessageReplyMarkup?chat_id=' .. chat_id ..
'&message_id='..message_id..
'&reply_markup='..URL.escape(JSON.encode(reply_markup))
return send_req(url)
end
function string:input()
if not self:find(' ') then
return false
end
return self:sub(self:find(' ')+1)
end
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function check_markdown(text) --markdown escape ( when you need to escape markdown , use it like : check_markdown('your text')
str = text
if str:match('_') then
output = str:gsub('_',[[\_]])
elseif str:match('*') then
output = str:gsub('*','\\*')
elseif str:match('`') then
output = str:gsub('`','\\`')
else
output = str
end
return output
end
function getChatMember(chat_id, user_id)
local url = send_api .. '/getChatMember?chat_id=' .. chat_id .. '&user_id=' .. user_id
return send_req(url)
end
function leave_group(chat_id)
local url = send_api .. '/leaveChat?chat_id=' .. chat_id
return send_req(url)
end
function del_msg(chat_id, message_id)
local url = send_api..'/deletemessage?chat_id='..chat_id..'&message_id='..message_id
return send_req(url)
end
function kick_user(user_id, chat_id)
local url = send_api .. '/kickChatMember?chat_id=' .. chat_id .. '&user_id=' .. user_id
return send_req(url)
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Jugner_Forest/npcs/Taumiale_RK.lua | 3 | 3326 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Taumiale, R.K.
-- Border Conquest Guards
-- !pos 570.732 -2.637 553.508 104
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Jugner_Forest/TextIDs");
local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = NORVALLEN;
local csid = 0x7ffa;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
blackzw/openwrt_sdk_dev1 | staging_dir/target-mips_r2_uClibc-0.9.33.2/root-ar71xx/usr/lib/lua/luci/webapi/Services.lua | 1 | 20765 | module("luci.webapi.Services", package.seeall)
require("luci.sys")
require('luci.util')
local common = require("luci.webapi.common")
ServiceTypes =
{
"SAMBA", -- 0
"DLNA", -- 1
"FTP", -- 2
"RILD" -- 3
}
ServiceTypes = common.CreateEnumTable(ServiceTypes, 0)
--[[
Request data:
@Req param "ServiceType":0
Response data:
@Rsp param "State":1
@Rsp param "ServiceType":1
--]]
function GetServiceState(req)
local service_type = req["ServiceType"]
local rsp = {}
local errs = nil
if service_type == nil then
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
local service_name = get_service_name(service_type)
if service_name == nil then
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
if is_enabled_service(service_name) then
rsp["State"] = 1
else
rsp["State"] = 0
end
rsp["ServiceType"] = service_type
return rsp
end
--[[
Request data:
@Req param "ServiceType":0
@Req param "State":1
--]]
function SetServiceState(req)
local service_type = req["ServiceType"]
local state = req["State"]
local errs = nil
if service_type == nil or state == nil then
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
local service_name = get_service_name(service_type)
if service_name == nil then
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
if (is_enabled_service(service_name) and state == 1) or (not is_enabled_service(service_name) and state == 0) then
-- already closed or opened: do nothing here
else
if state == 0 then
if not disable_service(service_name) then
return nil, {code=100301, message="Set service state failed"}
end
luci.sys.call("/etc/init.d/" .. service_name .. " stop >/dev/null 2>&1 &")
else
if not enable_service(service_name) then
return nil, {code=100301, message="Set service state failed"}
end
luci.sys.call("/etc/init.d/" .. service_name .. " start >/dev/null 2>&1 &")
end
end
return luci.json.null
end
--[[
Request data:
@Req param "ServiceType":0
--]]
function RestartService(req)
local service_type = req["ServiceType"]
local errs = nil
if service_type == nil then
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
local service_name = get_service_name(service_type)
if service_name == nil then
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
restart_service(service_name)
return luci.json.null
end
function restart_service(service_name)
luci.sys.call("/etc/init.d/" .. service_name .. " restart >/dev/null 2>&1 &")
end
function is_enabled_service(stype)
local init_enabled = luci.sys.init.enabled(stype)
local uci = require("luci.model.uci").cursor()
local res = uci:get(stype, "config", "enabled")
if res == nil or res == "0" then
return false
else
if not init_enabled then
luci.sys.call("/etc/init.d/" .. stype .. " enable >/dev/null 2>&1")
restart_service(stype)
end
return true
end
end
function disable_service(stype)
if luci.sys.init.disable(stype) then
local uci = require("luci.model.uci").cursor()
uci:set(stype, "config", "enabled", "0")
uci:save(stype)
uci:commit(stype)
return true
end
return false
end
function enable_service(stype)
if luci.sys.init.enable(stype) then
local uci = require("luci.model.uci").cursor()
uci:set(stype, "config", "enabled", "1")
uci:save(stype)
uci:commit(stype)
return true
end
return false
end
function get_service_name(stype)
if stype == ServiceTypes.SAMBA then
return "samba"
elseif stype == ServiceTypes.DLNA then
return "minidlna"
elseif stype == ServiceTypes.FTP then
return "vsftpd"
elseif stype == ServiceTypes.RILD then
return "rild"
else
return nil
end
end
function get_device_type(dir)
local dtype = 2
--if dir ~= nil and luci.util.cmatch(dir, "sd[a-z][0-9]") > 0 then
if dir ~= nil and dir == "/mnt/usb" then
dtype = 1
elseif dir ~= nil and dir == "/mnt/airdisk" then
--TODO: judge mm100 path
dtype = 0
end
return dtype
end
function get_dir_by_device_type(dType)
local media_path = ""
local flag = false
if dType == 0 then
--TODO: set mm100 media_path
flag = true
media_path = "/mnt/airdisk"
elseif dType == 1 then
flag = true
media_path = "/mnt/usb"
--local m = luci.sys.mounts()
--for i=1, table.getn(m) do
-- if m[i]["fs"] ~= nil and m[i]["mountpoint"] ~= nil then
-- if luci.util.cmatch(m[i]["fs"], "/dev/sd[a-z][0-9]") > 0 then
-- media_path = m[i]["mountpoint"]
-- flag = true
-- break
-- end
-- end
--end
end
return flag, media_path
end
Samba = {}
--[[
Request data:{}
Response data:
@Rsp param "HostName":"Openwrt"
@Rsp param "Description":"Openwrt"
@Rsp param "WorkGroup":"WORKGROUP"
@Rsp param "AccessPath":"smb://192.168.1.1/"
@Rsp param "DevType":0
@Rsp param "Anonymous":0
@Rsp param "UserName":"admin"
@Rsp param "Password":"admin"
@Rsp param "AuthType":0
--]]
function Samba.GetSettings(req)
local uci = require("luci.model.uci").cursor()
local service_name = get_service_name(ServiceTypes.SAMBA)
local hostname = uci:get(service_name, "config", "name")
local description = uci:get(service_name, "config", "description")
local workgroup = uci:get(service_name, "config", "workgroup")
local accesspath = ""
--local netm = require "luci.model.network".init()
--local net = netm:get_network("lan")
--local device = net and net:get_interface()
local addr = g_http_request_env.SERVER_ADDR
--if device then
-- local _, a
-- for _, a in ipairs(device:ipaddrs()) do
-- addr = a:host():string()
-- end
--end
if addr ~= "" then
accesspath = "smb://" .. addr .. "/"
end
local users = uci:get(service_name, "config", "users")
local rdonly = uci:get(service_name, "config", "read_only")
local anon = uci:get(service_name, "config", "guest_ok")
local password = uci:get(service_name, "config", "password")
local dtype = tonumber(uci:get(service_name, "config", "device_type"))
if anon == "yes" then
anon = 1
else
anon = 0
end
if rdonly == "yes" then
rdonly = 0
else
rdonly = 1
end
return {HostName=hostname, Description=description, WorkGroup=workgroup, AccessPath=accesspath, DevType=dtype, Anonymous=anon, UserName=users, Password=password, AuthType=rdonly}
end
--[[
Request data:
@Req param "Anonymous":0
@Req param "DevType":1
@Req param "UserName":"admin"
@Req param "Password":"admin"
@Req param "AuthType":0
Response data: {}
--]]
function Samba.SetSettings(req)
local anon = req["Anonymous"]
local dtype = req["DevType"]
--local username = req["UserName"]
--local password = req["Password"]
local auth = req["AuthType"]
if anon == nil or dtype == nil or auth == nil then --password == nil or
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
local guest_ok = "yes"
if anon == 0 then
guest_ok = "no"
end
local rdonly = "no"
if auth == 0 then
rdonly = "yes"
end
local uci = require("luci.model.uci").cursor()
local service_name = get_service_name(ServiceTypes.SAMBA)
if not uci:set(service_name, "config", "device_type", dtype) then
return nil, {code=100601, message="Set Samba settings failed, set device type failed"}
end
if not uci:set(service_name, "config", "read_only", rdonly) then
return nil, {code=100601, message="Set Samba settings failed, set read_only failed"}
end
if not uci:set(service_name, "config", "guest_ok", guest_ok) then
return nil, {code=100601, message="Set Samba settings failed, set guest_ok failed"}
end
if not uci:save(service_name) then
return nil, {code=100601, message="Set Samba settings failed, save uci failed"}
end
if not uci:commit(service_name) then
return nil, {code=100601, message="Set Samba settings failed, commit uci failed"}
end
if is_enabled_service(service_name) then
restart_service(service_name)
end
return luci.json.null
end
FTP = {}
--[[
Request data:{}
Response data:
@Rsp param "AccessPath":"ftp://192.168.1.1/"
@Rsp param "Anonymous":0
@Rsp param "DevType":1
@Rsp param "UserName":"admin"
@Rsp param "Password":"admin"
@Rsp param "AuthType":0
--]]
function FTP.GetSettings(req)
local uci = require("luci.model.uci").cursor()
local service_name = get_service_name(ServiceTypes.FTP)
local dir = uci:get(service_name, "config", "root_dir")
local anon = tonumber(uci:get(service_name, "config", "anonymous"))
local username = uci:get(service_name, "config", "username")
local auth_type = tonumber(uci:get(service_name, "config", "auth_type"))
local password = ""
local accesspath = ""
--if username ~= nil and username ~= "" then
-- password = luci.sys.user.getpasswd(username)
-- if password == nil then
-- password = ""
-- end
--end
local dtype = get_device_type(dir)
--local netm = require "luci.model.network".init()
--local net = netm:get_network("lan")
--local device = net and net:get_interface()
local addr = g_http_request_env.SERVER_ADDR
--if device then
-- local _, a
-- for _, a in ipairs(device:ipaddrs()) do
-- addr = a:host():string()
-- end
--end
if addr ~= "" then
accesspath = "ftp://" .. addr .. "/"
end
return {AccessPath=accesspath, Anonymous=anon, DevType=dtype, UserName=username, Password=password, AuthType=auth_type}
end
--[[
Request data:
@Req param "Anonymous":0
@Req param "DevType":1
@Req param "UserName":"admin"
@Req param "Password":"admin"
@Req param "AuthType":0
Response data: {}
--]]
function FTP.SetSettings(req)
local anon = req["Anonymous"]
local dtype = req["DevType"]
--local username = req["UserName"]
--local password = req["Password"]
local auth = req["AuthType"]
if anon == nil or dtype == nil or auth == nil then --password == nil or
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
local flag = false
local dir = ""
flag, dir = get_dir_by_device_type(dtype)
if not flag then
return nil, {code=101001, message="Set FTP settings failed, device not available"}
end
local uci = require("luci.model.uci").cursor()
local service_name = get_service_name(ServiceTypes.FTP)
--local username = uci:get(service_name, "config", "username")
--if luci.sys.user.setpasswd(username, password) >= 1 then
-- return nil, {code=101001, message="Set FTP settings failed, set password failed"}
--end
if not uci:set(service_name, "config", "root_dir", dir) then
return nil, {code=101001, message="Set FTP settings failed, set root_dir failed"}
end
if not uci:set(service_name, "config", "anonymous", anon) then
return nil, {code=101001, message="Set FTP settings failed, set anonymous failed"}
end
if not uci:set(service_name, "config", "auth_type", auth) then
return nil, {code=101001, message="Set FTP settings failed, set auth_type failed"}
end
if not uci:save(service_name) then
return nil, {code=101001, message="Set FTP settings failed, save uci failed"}
end
if not uci:commit(service_name) then
return nil, {code=101001, message="Set FTP settings failed, commit uci failed"}
end
if is_enabled_service(service_name) then
restart_service(service_name)
end
return luci.json.null
end
DLNA = {}
--[[
Request data:{}
Response data:
@Rsp param "FriendlyName":"Openwrt"
@Rsp param "MediaDirectories":"/mnt"
@Rsp param "DevType":1
--]]
function DLNA.GetSettings(req)
local uci = require("luci.model.uci").cursor()
local service_name = get_service_name(ServiceTypes.DLNA)
local fn = uci:get(service_name, "config", "friendly_name")
if fn == nil then
fn = ""
end
local dir = uci:get(service_name, "config", "media_dir")
if dir == nil then
dir = ""
elseif type(dir) == "table" then
if table.getn(dir) > 0 then
dir = dir[1]
else
dir = ""
end
end
local dtype = get_device_type(dir)
return {FriendlyName=fn, MediaDirectories=dir, DevType=dtype}
end
--[[
Request data:
@Req param "DevType":0
Response data: {}
--]]
function DLNA.SetSettings(req)
local dType = req["DevType"]
local errs = nil
if dType == nil or dType < 0 or dType > 2 then
errs = common.GetCommonErrorObject(common.ReturnCode.RILD_ERRID_BAD_PARAMETER)
return nil, errs
end
local media_path = ""
local flag = false
flag, media_path = get_dir_by_device_type(dType)
if not flag then
return nil, {code=100801, message="Set DLNA settings failed, device not available"}
end
local uci = require("luci.model.uci").cursor()
local service_name = get_service_name(ServiceTypes.DLNA)
uci:set(service_name, "config", "media_dir", {media_path})
uci:save(service_name)
uci:commit(service_name)
if is_enabled_service(service_name) then
restart_service(service_name)
end
return luci.json.null
end
TR069 = {}
function TR069.GetClientConfiguration(req)
local uci = require("luci.model.uci").cursor()
local configs = {}
local res = {}
local usename = nil
local password = nil
flags = uci:foreach("easycwmp","acs",
function(s)
if s[".type"] == "acs" then
configs["AcsUserName"] = s["username"]
configs["AcsUserPassword"] = s["password"]
res["scheme"] = s["scheme"]
res["hostname"] = s["hostname"]
res["port"] = s["port"]
res["path"] = s["path"]
--configs["AcsUrl"] = res["scheme"].."://"..res["hostname"]..":"..res["port"].."/"..res["path"]
configs["AcsUrl"] = res["scheme"].."://"..res["hostname"]..":"..res["port"]..res["path"] ---patch to modify "/"
configs["Inform"] = tonumber(s["periodic_enable"])
configs["InformInterval"] = tonumber(s["periodic_interval"])
end
end)
if flags == false then
return nil, {code=80201, message="Get Acsname,password and AcsUrl failed"}
end
configs["ConReqAuthent"] = 0 ---The section option is not show currently, consideration is dynamic, or static generation
--- config ClientRequestAuth
--- option ConReqAuthent 1
configs["ConReqUserName"] = nil --- option CPEusername 'CPEusername'
---- option CPEuserpassword 'CPEuserpassword'
configs["ConReqUserPassword"] = nil
flags = uci:foreach("easycwmp", "local",
function(s)
if (s[".type"] == "local" and s["username"] ~= nil) then
configs["ConReqAuthent"] = 1
configs["CPEusername"] = s["username"]
configs["ConReqUserPassword"] = s["password"]
end
end)
return configs
end
function TR069.SetClientConfiguration(req)
local uci = require("luci.model.uci").cursor()
local flags = false
--acs
flags = uci:foreach("easycwmp", "acs",
function(s)
if s[".type"] == "acs" then
uci:set("easycwmp", s[".name"], "periodic_enable", req["Inform"])
uci:set("easycwmp", s[".name"], "periodic_interval", req["InformInterval"])
if not uci:set("easycwmp", s[".name"], "username",req["AcsUserName"]) then
return nil, {code=80101, message="Set Acs and password failed"}
end
if not uci:set("easycwmp", s[".name"], "password",req["AcsUserPassword"]) then
return nil, {code=80103, message="Set Acs and password failed"}
end
local acsurl = req["AcsUrl"]
local a,b,scheme,hostname,port,path = string.find(acsurl,"(%a+)://([%w%p]+):(%d+)/([%w%p]*)") ---Parse the string for exampe:http://172.24.222.56:8009/openacs/acs
if scheme == nil or hostname == nil or port == nil then
return nil, {code=80101, message="Set acs url failed"}
end
if path ~= nil then
path = "/"..path ---patch ---2014/03/17 modify /openacs/acs
else
path = "/"
end
if not (uci:set("easycwmp", s[".name"], "scheme",scheme) and uci:set("easycwmp", s[".name"], "hostname",hostname) and ---acs modify
uci:set("easycwmp", s[".name"], "port",port) and uci:set("easycwmp", s[".name"], "path",path)) then
return nil, {code=80103, message="Set AcsURL failed"}
end
--
return false ---only a acs section
end
end)
--Client
flags = uci:foreach("easycwmp", "local", ---section option that is dynamic section
function(s)
if s[".type"] == "local" then
if req["ConReqAuthent"] == 1 then
if not uci:set("easycwmp", s[".name"], "username",req["ConReqUserName"]) then
return nil, {code=80102, message="Set CPE and password failed"}
end
if not uci:set("easycwmp", s[".name"], "password",req["ConReqUserPassword"]) then
return nil, {code=80102, message="Set CPE and password failed"}
end
else
uci:delete("easycwmp", s[".name"],"username")
uci:delete("easycwmp", s[".name"],"password")
end
end
end)
uci:save("easycwmp")
uci:commit("easycwmp")
luci.sys.call("/etc/init.d/easycwmpd restart > /dev/null 2>&1 &")
-- luci.sys.call("ubus ${UBUS_SOCKET:+-s $UBUS_SOCKET} call tr069 command reload > /dev/null 2>&1") --Here to send ubus message better. because of having a Cache time
return luci.json.null
end
PrivateCloud = {}
--[[
Request data:{}
@Req "DevType": 0
Response data:
@Rsp param null
--]]
function PrivateCloud.SetStorage(req)
local common = require('luci.webapi.Util')
local stype = req["DevType"]
local devpath = ""
local item = {}
if stype == nil or stype == "" then
errs = {code=7, message="Bad parameter"}
return nil, errs
end
local ret = common.DeleteSection("private_cloud", "private_cloud") --etc/config/private_cloud
if stype == 1 or stype == "1" then
devpath = "/mnt/usb"
elseif stype == 0 or stype == "0" then
devpath = "/mnt/airdisk"
else
devpath = "/mnt/null"
end
item["path"] = devpath
common.AddSection("private_cloud", "private_cloud", nil, item)
ret = common.SaveFile("private_cloud")
if ret == false then
errs = {code=101201, message="Set private cloud failed."}
return nil, errs
end
return luci.json.null
end
--[[
Request data:{}
@Req null
Response data:
@Rsp param "DevType": 0
--]]
function PrivateCloud.GetStorage(req)
local common = require('luci.webapi.Util')
local rsp = {}
local cloudlist = common.GetValueList("private_cloud", "private_cloud") --etc/config/private_cloud
if cloudlist == nil then
errs = {code=101301, message="Get private cloud failed."}
return nil, errs
end
rsp["DevType"] = 1
for i=1,table.getn(cloudlist.valuelist) do
tmp = cloudlist.valuelist[i]["path"]
if tmp == "/mnt/usb" then
rsp["DevType"] = 1
elseif tmp == "/mnt/airdisk" then
rsp["DevType"] = 0
else
rsp["DevType"] = 1
end
end
return rsp
end
| gpl-2.0 |
CCAAHH/telegram-bot-supergroups | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Dynamis-San_dOria/bcnms/dynamis_sandoria.lua | 14 | 1309 | -----------------------------------
-- Area: Dynamis San d'Oria
-- Name: Dynamis San d'Oria
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[DynaSandoria]UniqueID",os.time());
SetServerVariable("[DynaSandoria]Boss_Trigger",0);
SetServerVariable("[DynaSandoria]Already_Received",0);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("DynamisID",GetServerVariable("[DynaSandoria]UniqueID"));
local realDay = os.time();
if (DYNA_MIDNIGHT_RESET == true) then
realDay = getMidnight() - 86400;
end
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then
player:setVar("dynaWaitxDay",realDay);
end
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish he dynamis
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 4) then
GetNPCByID(17535224):setStatus(2);
SetServerVariable("[DynaSandoria]UniqueID",0);
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Temenos/mobs/Water_Elemental.lua | 28 | 1791 | -----------------------------------
-- Area: Temenos E T
-- NPC: Water_Elemental
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local mobID = mob:getID();
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
switch (mobID): caseof {
-- 100 a 106 inclut (Temenos -Northern Tower )
[16928885] = function (x)
GetNPCByID(16928768+277):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+277):setStatus(STATUS_NORMAL);
end ,
[16928886] = function (x)
GetNPCByID(16928768+190):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+190):setStatus(STATUS_NORMAL);
end ,
[16928887] = function (x)
GetNPCByID(16928768+127):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+127):setStatus(STATUS_NORMAL);
end ,
[16928888] = function (x)
GetNPCByID(16928768+69):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+69):setStatus(STATUS_NORMAL);
end ,
[16929038] = function (x)
if (IsMobDead(16929033)==false) then
DespawnMob(16929033);
SpawnMob(16929039);
end
end ,
}
end; | gpl-3.0 |
zzh442856860/skynet | test/testmongodb.lua | 62 | 2661 | local skynet = require "skynet"
local mongo = require "mongo"
local bson = require "bson"
local host, db_name = ...
function test_insert_without_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
local ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ret and ret.n == 1)
end
function test_insert_with_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"})
local ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ret and ret.n == 0)
end
function test_find_and_remove()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"})
local ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 2})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret and ret.test_key == 1)
local ret = db[db_name].testdb:find({test_key = {['$gt'] = 0}}):sort({test_key = -1}):skip(1):limit(1)
assert(ret:count() == 2)
assert(ret:count(true) == 1)
if ret:hasNext() then
ret = ret:next()
end
assert(ret and ret.test_key == 1)
db[db_name].testdb:delete({test_key = 1})
db[db_name].testdb:delete({test_key = 2})
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret == nil)
end
function test_expire_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index", expireAfterSeconds = 1, })
db[db_name].testdb:ensureIndex({test_date = 1}, {expireAfterSeconds = 1, })
local ret = db[db_name].testdb:safe_insert({test_key = 1, test_date = bson.date(os.time())})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret and ret.test_key == 1)
for i = 1, 1000 do
skynet.sleep(11);
local ret = db[db_name].testdb:findOne({test_key = 1})
if ret == nil then
return
end
end
assert(false, "test expire index failed");
end
skynet.start(function()
test_insert_without_index()
test_insert_with_index()
test_find_and_remove()
test_expire_index()
print("mongodb test finish.");
end)
| mit |
RebootRevival/FFXI_Test | scripts/globals/weaponskills/stardiver.lua | 22 | 1598 | -----------------------------------
-- Stardiver
-- Polearm weapon skill
-- Skill Level: MERIT
-- Delivers a fourfold attack. Damage varies with TP.
-- Will stack with Sneak Attack. reduces params.crit hit evasion by 5%
-- Element: None
-- Modifiers: STR:73~85%
-- 100%TP 200%TP 300%TP
-- 0.75 1.25 1.75
-----------------------------------
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 = 4;
params.ftp100 = 0.75; params.ftp200 = 1.25; params.ftp300 = 1.75;
params.str_wsc = 0.85 + (player:getMerit(MERIT_STARDIVER) / 100); 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.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.7 + (player:getMerit(MERIT_STARDIVER) / 100);
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
if (damage > 0 and target:hasStatusEffect(EFFECT_CRIT_HIT_EVASION_DOWN) == false) then
target:addStatusEffect(EFFECT_CRIT_HIT_EVASION_DOWN, 5, 0, 60);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
petoju/awesome | lib/naughty/dbus.lua | 2 | 19687 | ---------------------------------------------------------------------------
-- DBUS/Notification support
-- Notify
--
-- @author koniu <gkusnierz@gmail.com>
-- @copyright 2008 koniu
-- @module naughty.dbus
---------------------------------------------------------------------------
-- Package environment
local pairs = pairs
local type = type
local string = string
local capi = { awesome = awesome }
local gsurface = require("gears.surface")
local gdebug = require("gears.debug")
local protected_call = require("gears.protected_call")
local lgi = require("lgi")
local cairo, Gio, GLib, GObject = lgi.cairo, lgi.Gio, lgi.GLib, lgi.GObject
local schar = string.char
local sbyte = string.byte
local tcat = table.concat
local tins = table.insert
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
local naughty = require("naughty.core")
local cst = require("naughty.constants")
local nnotif = require("naughty.notification")
local naction = require("naughty.action")
local capabilities = {
"body", "body-markup", "icon-static", "actions", "action-icons"
}
--- Notification library, dbus bindings
local dbus = { config = {} }
-- This is either nil or a Gio.DBusConnection for emitting signals
local bus_connection
-- DBUS Notification constants
-- https://developer.gnome.org/notification-spec/#urgency-levels
local urgency = {
low = "\0",
normal = "\1",
critical = "\2"
}
--- DBUS notification to preset mapping.
-- The first element is an object containing the filter.
-- If the rules in the filter match, the associated preset will be applied.
-- The rules object can contain the following keys: urgency, category, appname.
-- The second element is the preset.
-- @tfield table 1 low urgency
-- @tfield table 2 normal urgency
-- @tfield table 3 critical urgency
-- @table config.mapping
dbus.config.mapping = cst.config.mapping
local function sendActionInvoked(notificationId, action)
if bus_connection then
bus_connection:emit_signal(nil, "/org/freedesktop/Notifications",
"org.freedesktop.Notifications", "ActionInvoked",
GLib.Variant("(us)", { notificationId, action }))
end
end
local function sendNotificationClosed(notificationId, reason)
if reason <= 0 then
reason = cst.notification_closed_reason.undefined
end
if bus_connection then
bus_connection:emit_signal(nil, "/org/freedesktop/Notifications",
"org.freedesktop.Notifications", "NotificationClosed",
GLib.Variant("(uu)", { notificationId, reason }))
end
end
local function convert_icon(w, h, rowstride, channels, data)
-- Do the arguments look sane? (e.g. we have enough data)
local expected_length = rowstride * (h - 1) + w * channels
if w < 0 or h < 0 or rowstride < 0 or (channels ~= 3 and channels ~= 4) or
string.len(data) < expected_length then
w = 0
h = 0
end
local format = cairo.Format[channels == 4 and 'ARGB32' or 'RGB24']
-- Figure out some stride magic (cairo dictates rowstride)
local stride = cairo.Format.stride_for_width(format, w)
local append = schar(0):rep(stride - 4 * w)
local offset = 0
-- Now convert each row on its own
local rows = {}
for _ = 1, h do
local this_row = {}
for i = 1 + offset, w * channels + offset, channels do
local R, G, B, A = sbyte(data, i, i + channels - 1)
tins(this_row, schar(B, G, R, A or 255))
end
-- Handle rowstride, offset is stride for the input, append for output
tins(this_row, append)
tins(rows, tcat(this_row))
offset = offset + rowstride
end
local pixels = tcat(rows)
local surf = cairo.ImageSurface.create_for_data(pixels, format, w, h, stride)
-- The surface refers to 'pixels', which can be freed by the GC. Thus,
-- duplicate the surface to create a copy of the data owned by cairo.
local res = gsurface.duplicate_surface(surf)
surf:finish()
return res
end
local notif_methods = {}
function notif_methods.Notify(sender, object_path, interface, method, parameters, invocation)
local appname, replaces_id, app_icon, title, text, actions, hints, expire =
unpack(parameters.value)
local args = {}
if text ~= "" then
args.message = text
if title ~= "" then
args.title = title
end
else
if title ~= "" then
args.message = title
else
-- FIXME: We have to reply *something* to the DBus invocation.
-- Right now this leads to a memory leak, I think.
return
end
end
if appname ~= "" then
args.appname = appname --TODO v6 Remove this.
args.app_name = appname
end
local preset = args.preset or cst.config.defaults
local notification
if actions then
args.actions = {}
for i = 1,#actions,2 do
local action_id = actions[i]
local action_text = actions[i + 1]
if action_id == "default" then
args.run = function()
sendActionInvoked(notification.id, "default")
notification:destroy(cst.notification_closed_reason.dismissed_by_user)
end
elseif action_id ~= nil and action_text ~= nil then
local a = naction {
name = action_text,
id = action_id,
position = (i - 1)/2 + 1,
}
-- Right now `gears` doesn't have a great icon implementation
-- and `naughty` doesn't depend on `menubar`, so delegate the
-- icon "somewhere" using a request.
if hints["action-icons"] and action_id ~= "" then
naughty.emit_signal("request::action_icon", a, "dbus", {id = action_id})
end
a:connect_signal("invoked", function()
sendActionInvoked(notification.id, action_id)
if not notification.resident then
notification:destroy(cst.notification_closed_reason.dismissed_by_user)
end
end)
table.insert(args.actions, a)
end
end
end
args.destroy = function(reason)
sendNotificationClosed(notification.id, reason)
end
local legacy_data = { -- This data used to be generated by AwesomeWM's C code
type = "method_call", interface = interface, path = object_path,
member = method, sender = sender, bus = "session"
}
if not preset.callback or (type(preset.callback) == "function" and
preset.callback(legacy_data, appname, replaces_id, app_icon, title, text, actions, hints, expire)) then
if app_icon ~= "" then
args.app_icon = app_icon
end
if hints.icon_data or hints.image_data or hints["image-data"] then
-- Icon data is a bit complex and hence needs special care:
-- .value breaks with the array of bytes (ay) that we get here.
-- So, bypass it and look up the needed value differently
local icon_condidates = {}
for k, v in parameters:get_child_value(7 - 1):pairs() do
if k == "image-data" then
icon_condidates[1] = v -- not deprecated
break
elseif k == "image_data" then -- deprecated
icon_condidates[2] = v
elseif k == "icon_data" then -- deprecated
icon_condidates[3] = v
end
end
-- The order is mandated by the spec.
local icon_data = icon_condidates[1]
or icon_condidates[2]
or icon_condidates[3]
-- icon_data is an array:
-- 1 -> width
-- 2 -> height
-- 3 -> rowstride
-- 4 -> has alpha
-- 5 -> bits per sample
-- 6 -> channels
-- 7 -> data
-- Get the value as a GVariant and then use LGI's special
-- GVariant.data to get that as an LGI byte buffer. That one can
-- then by converted to a string via its __tostring metamethod.
local data = tostring(icon_data:get_child_value(7 - 1).data)
args.image = convert_icon(icon_data[1], icon_data[2], icon_data[3], icon_data[6], data)
-- Convert all animation frames.
if naughty.image_animations_enabled then
args.images = {args.image}
if #icon_data > 7 then
for frame=8, #icon_data do
data = tostring(icon_data:get_child_value(frame-1).data)
table.insert(
args.images,
convert_icon(
icon_data[1],
icon_data[2],
icon_data[3],
icon_data[6],
data
)
)
end
end
end
end
-- Alternate ways to set the icon. The specs recommends to allow both
-- the icon and image to co-exist since they serve different purpose.
-- However in case the icon isn't specified, use the image.
args.image = args.image
or hints["image-path"] -- not deprecated
or hints["image_path"] -- deprecated
if naughty.image_animations_enabled then
args.images = args.images or {}
end
if replaces_id and replaces_id ~= "" and replaces_id ~= 0 then
args.replaces_id = replaces_id
end
if expire and expire > -1 then
args.timeout = expire / 1000
end
args.freedesktop_hints = hints
-- Not very pretty, but given the current format is documented in the
-- public API... well, whatever...
if hints and hints.urgency then
for name, key in pairs(urgency) do
local b = string.char(hints.urgency)
if key == b then
args.urgency = name
end
end
end
args.urgency = args.urgency or "normal"
-- Try to update existing objects when possible
notification = naughty.get_by_id(replaces_id)
if notification then
if not notification._private._unique_sender then
-- If this happens, the notification is either trying to
-- highjack content created within AwesomeWM or it is garbage
-- to begin with.
gdebug.print_warning(
"A notification has been received, but tried to update "..
"the content of a notification it does not own."
)
elseif notification._private._unique_sender ~= sender then
-- Nothing says you cannot and some scripts may do it
-- accidentally, but this is rather unexpected.
gdebug.print_warning(
"Notification "..notification.title.." is being updated"..
"by a different DBus connection ("..sender.."), this is "..
"suspicious. The original connection was "..
notification._private._unique_sender
)
end
for k, v in pairs(args) do
if k == "destroy" then k = "destroy_cb" end
notification[k] = v
end
-- Update the icon if necessary.
if app_icon ~= notification._private.app_icon then
notification._private.app_icon = app_icon
naughty._emit_signal_if(
"request::icon", function()
if notification._private.icon then return true end
end, notification, "dbus_clear", {}
)
end
-- Even if no property changed, restart the timeout.
notification:reset_timeout()
else
-- Only set the sender for new notifications.
args._unique_sender = sender
notification = nnotif(args)
end
invocation:return_value(GLib.Variant("(u)", { notification.id }))
return
end
invocation:return_value(GLib.Variant("(u)", { nnotif._gen_next_id() }))
end
function notif_methods.CloseNotification(_, _, _, _, parameters, invocation)
local obj = naughty.get_by_id(parameters.value[1])
if obj then
obj:destroy(cst.notification_closed_reason.dismissed_by_command)
end
invocation:return_value(GLib.Variant("()"))
end
function notif_methods.GetServerInformation(_, _, _, _, _, invocation)
-- name of notification app, name of vender, version, specification version
invocation:return_value(GLib.Variant("(ssss)", {
"naughty", "awesome", capi.awesome.version, "1.2"
}))
end
function notif_methods.GetCapabilities(_, _, _, _, _, invocation)
-- We actually do display the body of the message, we support <b>, <i>
-- and <u> in the body and we handle static (non-animated) icons.
invocation:return_value(GLib.Variant("(as)", {capabilities}))
end
local function method_call(_, sender, object_path, interface, method, parameters, invocation)
if not notif_methods[method] then return end
protected_call(
notif_methods[method],
sender,
object_path,
interface,
method,
parameters,
invocation
)
end
local function on_bus_acquire(conn, _)
local function arg(name, signature)
return Gio.DBusArgInfo{ name = name, signature = signature }
end
local method = Gio.DBusMethodInfo
local signal = Gio.DBusSignalInfo
local interface_info = Gio.DBusInterfaceInfo {
name = "org.freedesktop.Notifications",
methods = {
method{ name = "GetCapabilities",
out_args = { arg("caps", "as") }
},
method{ name = "CloseNotification",
in_args = { arg("id", "u") }
},
method{ name = "GetServerInformation",
out_args = { arg("return_name", "s"), arg("return_vendor", "s"),
arg("return_version", "s"), arg("return_spec_version", "s")
}
},
method{ name = "Notify",
in_args = { arg("app_name", "s"), arg("id", "u"),
arg("icon", "s"), arg("summary", "s"), arg("body", "s"),
arg("actions", "as"), arg("hints", "a{sv}"),
arg("timeout", "i")
},
out_args = { arg("return_id", "u") }
}
},
signals = {
signal{ name = "NotificationClosed",
args = { arg("id", "u"), arg("reason", "u") }
},
signal{ name = "ActionInvoked",
args = { arg("id", "u"), arg("action_key", "s") }
}
}
}
conn:register_object("/org/freedesktop/Notifications", interface_info,
GObject.Closure(method_call))
end
local bus_proxy, pid_for_unique_name = nil, {}
Gio.DBusProxy.new_for_bus(
Gio.BusType.SESSION,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES,
nil,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
nil,
function(proxy)
bus_proxy = proxy
end,
nil
)
--- Get the clients associated with a notification.
--
-- Note that is based on the process PID. PIDs roll over, so don't use this
-- with very old notifications.
--
-- Also note that some multi-process application can use a different process
-- for the clients and the service used to send the notifications.
--
-- Since this is based on PIDs, it is impossible to know which client sent the
-- notification if the process has multiple clients (windows). Using the
-- `client.type` can be used to further filter this list into more probable
-- candidates (tooltips, menus and dialogs are unlikely to send notifications).
--
-- @tparam naughty.notification notif A notification object.
-- @treturn table A table with all associated clients.
function dbus.get_clients(notif)
-- First, the trivial case, but I never found an app that implements it.
-- It isn't standardized, but mentioned as possible.
local win_id = notif.freedesktop_hints and (notif.freedesktop_hints.window_ID
or notif.freedesktop_hints["window-id"]
or notif.freedesktop_hints.windowID
or notif.freedesktop_hints.windowid)
if win_id then
for _, c in ipairs(client.get()) do
if c.window_id == win_id then
return {win_id}
end
end
end
-- Less trivial, but mentioned in the spec. Note that this isn't
-- recommended by the spec, let alone mandatory. It is mentioned it can
-- exist. This wont work with Flatpak or Snaps.
local pid = notif.freedesktop_hints and (
notif.freedesktop_hints.PID or notif.freedesktop_hints.pid
)
if ((not bus_proxy) or not notif._private._unique_sender) and not pid then
return {}
end
if (not pid) and (not pid_for_unique_name[notif._private._unique_sender]) then
local owner = GLib.Variant("(s)", {notif._private._unique_sender})
-- It is sync, but this isn't done very often and since it is DBus
-- daemon itself, it is very responsive. Doing this using the async
-- variant would cause the clients to be unavailable in the notification
-- rules.
pid = bus_proxy:call_sync("GetConnectionUnixProcessID",
owner,
Gio.DBusCallFlags.NONE,
-1
)
if (not pid) or (not pid.value) then return {} end
pid = pid.value and pid.value[1]
if not pid then return {} end
pid_for_unique_name[notif._private._unique_sender] = pid
end
pid = pid or pid_for_unique_name[notif._private._unique_sender]
if not pid then return {} end
local ret = {}
for _, c in ipairs(client.get()) do
if c.pid == pid then
table.insert(ret, c)
end
end
return ret
end
local function on_name_acquired(conn, _)
bus_connection = conn
end
local function on_name_lost(_, _)
bus_connection = nil
end
Gio.bus_own_name(Gio.BusType.SESSION, "org.freedesktop.Notifications",
Gio.BusNameOwnerFlags.NONE, GObject.Closure(on_bus_acquire),
GObject.Closure(on_name_acquired), GObject.Closure(on_name_lost))
-- For testing
dbus._notif_methods = notif_methods
local function remove_capability(cap)
for k, v in ipairs(capabilities) do
if v == cap then
table.remove(capabilities, k)
break
end
end
end
-- Update the capabilities.
naughty.connect_signal("property::persistence_enabled", function()
remove_capability("persistence")
if naughty.persistence_enabled then
table.insert(capabilities, "persistence")
end
end)
naughty.connect_signal("property::image_animations_enabled", function()
remove_capability("icon-multi")
remove_capability("icon-static")
table.insert(capabilities, naughty.persistence_enabled
and "icon-multi" or "icon-static"
)
end)
-- For the tests.
dbus._capabilities = capabilities
return dbus
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/globals/items/divine_sword.lua | 1 | 1107 | -----------------------------------------
-- ID: 16549
-- Item: Divine Sword
-- Additional Effect: Light Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
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, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = msgBasic.ADD_EFFECT_DMG;
if (dmg < 0) then
message = msgBasic.ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Northern_San_dOria/npcs/Pepigort.lua | 3 | 1040 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Pepigort
-- Type: Standard Dialogue NPC
-- @zone 231
-- !pos -126.739 11.999 262.757
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PEPIGORT_DIALOG);
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 |
CCAAHH/telegram-bot-supergroups | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Arrapago_Remnants/instances/arrapago_remnants.lua | 29 | 3716 | -----------------------------------
--
-- Salvage: Arrapago Remnants
--
-----------------------------------
require("scripts/globals/instance")
package.loaded["scripts/zones/Arrapago_Remnants/IDs"] = nil;
local Arrapago = require("scripts/zones/Arrapago_Remnants/IDs");
-----------------------------------
-- afterInstanceRegister
-----------------------------------
function afterInstanceRegister(player)
local instance = player:getInstance();
player:messageSpecial(Arrapago.text.TIME_TO_COMPLETE, instance:getTimeLimit());
player:messageSpecial(Arrapago.text.SALVAGE_START, 1);
player:addStatusEffectEx(EFFECT_ENCUMBRANCE_I, EFFECT_ENCUMBRANCE_I, 0xFFFF, 0, 0)
player:addStatusEffectEx(EFFECT_OBLIVISCENCE, EFFECT_OBLIVISCENCE, 0, 0, 0)
player:addStatusEffectEx(EFFECT_OMERTA, EFFECT_OMERTA, 0, 0, 0)
player:addStatusEffectEx(EFFECT_IMPAIRMENT, EFFECT_IMPAIRMENT, 0, 0, 0)
player:addStatusEffectEx(EFFECT_DEBILITATION, EFFECT_DEBILITATION, 0x1FF, 0, 0)
for i = 0,15 do
player:unequipItem(i)
end
end;
-----------------------------------
-- onInstanceCreated
-----------------------------------
function onInstanceCreated(instance)
for i,v in pairs(Arrapago.npcs[1][1]) do
local npc = instance:getEntity(bit.band(v, 0xFFF), TYPE_NPC);
npc:setStatus(STATUS_NORMAL)
end
instance:setStage(1)
end;
-----------------------------------
-- onInstanceTimeUpdate
-----------------------------------
function onInstanceTimeUpdate(instance, elapsed)
updateInstanceTime(instance, elapsed, Arrapago.text)
end;
-----------------------------------
-- onInstanceFailure
-----------------------------------
function onInstanceFailure(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Arrapago.text.MISSION_FAILED,10,10);
v:startEvent(0x66);
end
end;
-----------------------------------
-- onInstanceProgressUpdate
-----------------------------------
function onInstanceProgressUpdate(instance, progress)
if instance:getStage() == 1 and progress == 10 then
SpawnMob(Arrapago.mobs[1][2].rampart, instance)
elseif instance:getStage() == 3 and progress == 0 then
SpawnMob(Arrapago.mobs[2].astrologer, instance)
end
end;
-----------------------------------
-- onInstanceComplete
-----------------------------------
function onInstanceComplete(instance)
end;
function onRegionEnter(player,region)
if region:GetRegionID() <= 10 then
player:startEvent(199 + region:GetRegionID())
end
end
function onEventUpdate(entity, eventid, result)
if (eventid >= 200 and eventid <= 203) then
local instance = entity:getInstance()
if instance:getProgress() == 0 then
for id = Arrapago.mobs[2][eventid-199].mobs_start, Arrapago.mobs[2][eventid-199].mobs_end do
SpawnMob(id, instance)
end
instance:setProgress(eventid-199)
end
elseif eventid == 204 then
-- spawn floor 3
end
end
function onEventFinish(entity, eventid, result)
local instance = entity:getInstance()
if (eventid >= 200 and eventid <= 203) then
for id = Arrapago.mobs[1][2].mobs_start, Arrapago.mobs[1][2].mobs_end do
DespawnMob(id, instance)
end
DespawnMob(Arrapago.mobs[1][2].rampart, instance)
DespawnMob(Arrapago.mobs[1][2].sabotender, instance)
elseif eventid == 204 then
for _,v in ipairs(Arrapago.mobs[2]) do
for id = v.mobs_start, v.mobs_end do
DespawnMob(id, instance)
end
end
DespawnMob(Arrapago.mobs[2].astrologer, instance)
end
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Mhaura/npcs/Jikka-Abukka.lua | 3 | 1530 | -----------------------------------
-- Area: Mhaura
-- NPC: Jikka-Abukka
-- Involved in Quest: Riding on the Clouds
-- !pos -13 -15 58 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 8) 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 |
ashang/koreader | frontend/apps/reader/modules/readerlink.lua | 4 | 4947 | local InputContainer = require("ui/widget/container/inputcontainer")
local GestureRange = require("ui/gesturerange")
local LinkBox = require("ui/widget/linkbox")
local UIManager = require("ui/uimanager")
local Geom = require("ui/geometry")
local Screen = require("device").screen
local Device = require("device")
local Event = require("ui/event")
local DEBUG = require("dbg")
local _ = require("gettext")
local ReaderLink = InputContainer:new{
link_states = {}
}
function ReaderLink:init()
if Device:isTouchDevice() then
self:initGesListener()
end
self.ui:registerPostInitCallback(function()
self.ui.menu:registerToMainMenu(self)
end)
end
function ReaderLink:onReadSettings(config)
-- called when loading new document
self.link_states = {}
end
function ReaderLink:initGesListener()
if Device:isTouchDevice() then
self.ges_events = {
Tap = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = 0, y = 0,
w = Screen:getWidth(),
h = Screen:getHeight()
}
}
},
Swipe = {
GestureRange:new{
ges = "swipe",
range = Geom:new{
x = 0, y = 0,
w = Screen:getWidth(),
h = Screen:getHeight(),
}
}
},
}
end
end
local function is_follow_links_on()
return G_reader_settings:readSetting("follow_links") ~= false
end
local function swipe_to_go_back()
return G_reader_settings:readSetting("swipe_to_go_back") ~= false
end
function ReaderLink:addToMainMenu(tab_item_table)
-- insert table to main reader menu
table.insert(tab_item_table.navi, {
text = _("Follow links"),
sub_item_table = {
{
text_func = function()
return is_follow_links_on() and _("Disable") or _("Enable")
end,
callback = function()
G_reader_settings:saveSetting("follow_links",
not is_follow_links_on())
end
},
{
text = _("Go back"),
enabled_func = function() return #self.link_states > 0 end,
callback = function() self:onGoBackLink() end,
},
{
text = _("Swipe to go back"),
checked_func = function() return swipe_to_go_back() end,
callback = function()
G_reader_settings:saveSetting("swipe_to_go_back",
not swipe_to_go_back())
end,
},
}
})
end
function ReaderLink:onSetDimensions(dimen)
-- update listening according to new screen dimen
if Device:isTouchDevice() then
self:initGesListener()
end
end
function ReaderLink:onTap(arg, ges)
if not is_follow_links_on() then return end
if self.ui.document.info.has_pages then
local pos = self.view:screenToPageTransform(ges.pos)
if pos then
-- link box in native page
local link, lbox = self.ui.document:getLinkFromPosition(pos.page, pos)
if link and lbox then
-- screen box that holds the link
local sbox = self.view:pageToScreenTransform(pos.page,
self.ui.document:nativeToPageRectTransform(pos.page, lbox))
if sbox then
UIManager:show(LinkBox:new{
box = sbox,
timeout = FOLLOW_LINK_TIMEOUT,
callback = function() self:onGotoLink(link) end
})
return true
end
end
end
else
local link = self.ui.document:getLinkFromPosition(ges.pos)
if link ~= "" then
return self:onGotoLink(link)
end
end
end
function ReaderLink:onGotoLink(link)
if self.ui.document.info.has_pages then
table.insert(self.link_states, self.view.state.page)
self.ui:handleEvent(Event:new("GotoPage", link.page + 1))
else
table.insert(self.link_states, self.ui.document:getXPointer())
self.ui:handleEvent(Event:new("GotoXPointer", link))
end
return true
end
function ReaderLink:onGoBackLink()
local last_page_or_xp = table.remove(self.link_states)
if last_page_or_xp then
local event = self.ui.document.info.has_pages and "GotoPage" or "GotoXPointer"
self.ui:handleEvent(Event:new(event, last_page_or_xp))
return true
end
end
function ReaderLink:onSwipe(arg, ges)
if ges.direction == "east" and swipe_to_go_back() then
return self:onGoBackLink()
end
end
return ReaderLink
| agpl-3.0 |
MRAHS/SuperGpSupporter | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Abyssea-Tahrongi/npcs/qm8.lua | 3 | 1338 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: qm8 (???)
-- Spawns Abas
-- !pos ? ? ? 45
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
if (trade:hasItemQty(2922,1) and trade:getItemCount() == 1) then -- Player has all the required items.
if (GetMobAction(16961924) == ACTION_NONE) then -- Mob not already spawned from this
SpawnMob(16961924):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:tradeComplete();
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(1010, 2922); -- Inform payer what items they need.
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 |
sajadaltaie/sejobot | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
lenovor/BBRL | scripts/lua_scripts/data/experiments_accurate.lua | 3 | 1675 |
-- ============================================================================
-- This script describes the experiments to perform for the 'accurate' case
-- (prior distribution = test distribution)
--
-- An experiment is described as follows:
--
-- ...
-- {
-- -- Short name of the prior distribution
-- prior = "<prior name>",
--
-- -- Prior distribution file in 'data/distributions/'
-- priorFile = "<prior file>",
--
-- -- Short name of the test distribution
-- exp = "<exp name>",
--
-- -- Test distribution file in 'data/distributions/'
-- expFile = "<test file>",
--
-- -- The number of MDPs to draw from the test distribution
-- N = <number of MDPs>,
--
-- -- The discount factor
-- gamma = <discount factor>,
--
-- -- The horizon limit
-- T = <horizon limit>
-- },
-- ...
--
--
-- You also have to associate a short name to this set of experiments
--
-- shortName = <short name>
-- ============================================================================
local experiments =
{
{
prior = "GC", priorFile = "GC-distrib.dat",
exp = "GC", testFile = "GC-distrib.dat",
N = 500, gamma = 0.95, T = 250
},
{
prior = "GDL", priorFile = "GDL-distrib.dat",
exp = "GDL", testFile = "GDL-distrib.dat",
N = 500, gamma = 0.95, T = 250
},
{
prior = "Grid", priorFile = "Grid-distrib.dat",
exp = "Grid", testFile = "Grid-distrib.dat",
N = 500, gamma = 0.95, T = 250
},
shortName = "accurate"
}
return experiments
| gpl-2.0 |
jthomasbarry/aafmt | archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/layered/cycle_removal.lua | 3 | 4560 | -- Copyright 2012 by Till Tantau
--
-- This file may be distributed and/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/layered/cycle_removal.lua,v 1.3 2013/05/23 20:01:27 tantau Exp $
local declare = require("pgf.gd.interface.InterfaceToAlgorithms").declare
---
-- @section subsection {Cycle Removal}
--
-- The Sugiyama method works only on directed \emph{acyclic}
-- graphs. For this reason, if the input graph is not (yet) acyclic, a
-- number of edges need to be redirected so that acyclicity arises. In
-- the following, the different options that allow you to fine-tune
-- this process are documented.
--
-- @end
---
declare {
key = "depth first cycle removal",
algorithm = require "pgf.gd.layered.CycleRemovalGansnerKNV1993",
phase = "cycle removal",
phase_default = true,
summary = [["
Selects a cycle removal algorithm that is especially
appropriate for graphs specified ``by hand''.
"]],
documentation = [["
When graphs are created by humans manually, one can
make assumptions about the input graph that would otherwise not
be possible. For instance, it seems reasonable to assume that the
order in which nodes and edges are entered by the user somehow
reflects the natural flow the user has had in mind for the graph.
In order to preserve the natural flow of the input graph, Gansner
et al.\ propose to remove cycles by performing a series of
depth-first searches starting at individual nodes in the order they
appear in the graph. This algorithm
implicitly constructs a spanning tree of the nodes reached during
the searches. It thereby partitions the edges of the graph into
tree edges and non-tree edges. The non-tree edges are further
subdivided into forward edges, cross edges, and back edges. Forward
edges point from a tree nodes to one of their descendants. Cross
edges connect unrelated branches in
the search tree. Back edges connect descendants to one of their
ancestors. It is not hard to see that reversing back edges will not
only introduce no new cycles but will also make any directed graph
acyclic. Gansner et al.\ argue that this approach is more stable
than others in that fewer inappropriate edges are reversed compared
to other methods, despite the lack of a provable upper bound
for the number of reversed edges.
See section 4.1.1 of Pohlmann's Diplom thesis for more details.
This is the default algorithm for cycle removals.
"]]
}
---
declare {
key = "prioritized greedy cycle removal",
algorithm = "pgf.gd.layered.CycleRemovalEadesLS1993",
phase = "cycle removal",
summary = [["
This algorithm implements a greedy heuristic of Eades et al.\ for
cycle removal that prioritizes sources and sinks.
"]],
documentation = [["
See section 4.1.1 of Pohlmann's Diploma theses for details.
"]]
}
---
declare {
key = "greedy cycle removal",
algorithm = "pgf.gd.layered.CycleRemovalEadesLS1993",
phase = "cycle removal",
summary = [["
This algorithm implements a greedy heuristic of Eades et al.\ for
cycle removal that prioritizes sources and sinks.
"]],
documentation = [["
See section 4.1.1 of Pohlmann's Diploma theses for details.
"]]
}
---
declare {
key = "naive greedy cycle removal",
algorithm = "pgf.gd.layered.CycleRemovalBergerS1990a",
phase = "cycle removal",
summary = [["
This algorithm implements a greedy heuristic of Berger and Shor for
cycle removal. It
is not really compared to the other heuristics and only included
for demonstration purposes.
"]],
documentation = [["
See section 4.1.1 of Pohlmann's Diploma theses for details.
"]]
}
---
declare {
key = "random greedy cycle removal",
algorithm = "pgf.gd.layered.CycleRemovalBergerS1990b",
phase = "cycle removal",
summary = [["
This algorithm implements a randomized greedy heuristic of Berger
and Shor for cycle removal. It, too, is not really compared to
the other heuristics and only included for demonstration purposes.
"]],
documentation = [["
See section 4.1.1 of Pohlmann's Diploma theses for details.
"]]
}
| gpl-2.0 |
padrinoo1/telegeek | plugins/google.lua | 336 | 1323 | do
local function googlethat(query)
local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&'
local parameters = 'q='..(URL.escape(query) or '')
-- Do the request
local res, code = https.request(url..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=''
i = 0
for key,val in ipairs(results) do
i = i+1
stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n'
end
return stringresults
end
local function run(msg, matches)
-- comment this line if you want this plugin works in private message.
if not is_chat_msg(msg) then return nil end
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = 'Returns five results from Google. Safe search is enabled by default.',
usage = ' !google [terms]: Searches Google and send results',
patterns = {
'^!google (.*)$',
'^%.[g|G]oogle (.*)$'
},
run = run
}
end
| gpl-2.0 |
zeus-ff/d | plugins/google.lua | 336 | 1323 | do
local function googlethat(query)
local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&'
local parameters = 'q='..(URL.escape(query) or '')
-- Do the request
local res, code = https.request(url..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=''
i = 0
for key,val in ipairs(results) do
i = i+1
stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n'
end
return stringresults
end
local function run(msg, matches)
-- comment this line if you want this plugin works in private message.
if not is_chat_msg(msg) then return nil end
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = 'Returns five results from Google. Safe search is enabled by default.',
usage = ' !google [terms]: Searches Google and send results',
patterns = {
'^!google (.*)$',
'^%.[g|G]oogle (.*)$'
},
run = run
}
end
| gpl-2.0 |
Afforess/Factorio-Stdlib | stdlib/event/modules/dump_event_data.lua | 1 | 2387 | local inspect = _ENV.inspect
local function setup_event_data(Event, valid_event_id, id_to_name)
local function get_registered_counts(reg_type)
local core, nth, on_events = 0, 0, 0
local events = {}
for id, registry in pairs(Event.registry) do
if tonumber(id) then
if id < 0 then
nth = nth + #registry
else
on_events = on_events + #registry
end
else
if Event.core_events[id] then
core = core + #registry
else
on_events = on_events + #registry
end
end
local name = id_to_name(id)
events[name] = (events[name] or 0) + #registry
end
local all = {
core = core,
events = events,
nth = nth,
on_events = on_events,
total = on_events + nth + core
}
return reg_type and all[reg_type] or all
end
local function dump_data()
local event_data = {
count_data = get_registered_counts(),
event_order = script.get_event_order(),
custom_events = Event.custom_events,
registry = Event.registry,
options = {
protected_mode = Event.options.protected_mode,
force_crc = Event.options.force_crc,
inspect_event = Event.options.inspect_event,
skip_valid = Event.options.skip_valid
}
}
local registry, factorio_events = {}, {}
for event, data in pairs(Event.registry) do
registry['[' .. event .. '] ' .. id_to_name(event)] = data
if valid_event_id(event) then
factorio_events['[' .. event .. '] ' .. id_to_name(event)] = Event.script.get_event_handler(event)
end
end
game.write_file(Event.get_file_path('Event/Event.lua'), 'return ' .. inspect(event_data))
game.write_file(Event.get_file_path('Event/Event.registry.lua'), 'return ' .. inspect(registry, { longkeys = true, arraykeys = true }))
game.write_file(Event.get_file_path('Event/Factorio.registry.lua'), 'return ' .. inspect(factorio_events, { longkeys = true, arraykeys = true }))
end
return dump_data
end
return setup_event_data
| isc |
RebootRevival/FFXI_Test | scripts/zones/Norg/Zone.lua | 12 | 2309 | -----------------------------------
--
-- Zone: Norg (252)
--
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-19.238,-2.163,-63.964,187);
end
if (player:getCurrentMission(ZILART) == THE_NEW_FRONTIER) then
cs = 0x0001;
elseif (player:getCurrentMission(ZILART) == AWAKENING and player:getVar("ZilartStatus") == 0 or player:getVar("ZilartStatus") == 2) then
cs = 0x00B0;
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);
if (csid == 0x0001) then
if (player:hasKeyItem(MAP_OF_NORG) == false) then
player:addKeyItem(MAP_OF_NORG);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_NORG);
end
player:completeMission(ZILART,THE_NEW_FRONTIER);
player:addMission(ZILART,WELCOME_TNORG);
elseif (csid == 0x00B0) then
player:setVar("ZilartStatus", player:getVar("ZilartStatus")+1);
end
end; | gpl-3.0 |
Jimdo/thrift | lib/lua/TTransport.lua | 115 | 2800 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'Thrift'
TTransportException = TException:new {
UNKNOWN = 0,
NOT_OPEN = 1,
ALREADY_OPEN = 2,
TIMED_OUT = 3,
END_OF_FILE = 4,
INVALID_FRAME_SIZE = 5,
INVALID_TRANSFORM = 6,
INVALID_CLIENT_TYPE = 7,
errorCode = 0,
__type = 'TTransportException'
}
function TTransportException:__errorCodeToString()
if self.errorCode == self.NOT_OPEN then
return 'Transport not open'
elseif self.errorCode == self.ALREADY_OPEN then
return 'Transport already open'
elseif self.errorCode == self.TIMED_OUT then
return 'Transport timed out'
elseif self.errorCode == self.END_OF_FILE then
return 'End of file'
elseif self.errorCode == self.INVALID_FRAME_SIZE then
return 'Invalid frame size'
elseif self.errorCode == self.INVALID_TRANSFORM then
return 'Invalid transform'
elseif self.errorCode == self.INVALID_CLIENT_TYPE then
return 'Invalid client type'
else
return 'Default (unknown)'
end
end
TTransportBase = __TObject:new{
__type = 'TTransportBase'
}
function TTransportBase:isOpen() end
function TTransportBase:open() end
function TTransportBase:close() end
function TTransportBase:read(len) end
function TTransportBase:readAll(len)
local buf, have, chunk = '', 0
while have < len do
chunk = self:read(len - have)
have = have + string.len(chunk)
buf = buf .. chunk
if string.len(chunk) == 0 then
terror(TTransportException:new{
errorCode = TTransportException.END_OF_FILE
})
end
end
return buf
end
function TTransportBase:write(buf) end
function TTransportBase:flush() end
TServerTransportBase = __TObject:new{
__type = 'TServerTransportBase'
}
function TServerTransportBase:listen() end
function TServerTransportBase:accept() end
function TServerTransportBase:close() end
TTransportFactoryBase = __TObject:new{
__type = 'TTransportFactoryBase'
}
function TTransportFactoryBase:getTransport(trans)
return trans
end
| apache-2.0 |
RebootRevival/FFXI_Test | scripts/globals/items/slice_of_salted_hare.lua | 12 | 1263 | -----------------------------------------
-- ID: 5737
-- Item: slice_of_salted_hare
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 10
-- Strength 1
-- hHP +1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5737);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_STR, 1);
target:addMod(MOD_HPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_STR, 1);
target:delMod(MOD_HPHEAL, 1);
end;
| gpl-3.0 |
ashang/koreader | frontend/ui/widget/buttontable.lua | 4 | 2666 | local VerticalGroup = require("ui/widget/verticalgroup")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local VerticalSpan = require("ui/widget/verticalspan")
local LineWidget = require("ui/widget/linewidget")
local Button = require("ui/widget/button")
local Screen = require("device").screen
local Geom = require("ui/geometry")
local Blitbuffer = require("ffi/blitbuffer")
local ButtonTable = VerticalGroup:new{
width = Screen:getWidth(),
buttons = {
{
{text="OK", enabled=true, callback=nil},
{text="Cancel", enabled=false, callback=nil},
},
},
sep_width = Screen:scaleBySize(1),
padding = Screen:scaleBySize(2),
zero_sep = false,
button_font_face = "cfont",
button_font_size = 20,
}
function ButtonTable:init()
--local vertical_group = VerticalGroup:new{}
if self.zero_sep then
self:addHorizontalSep()
end
for i = 1, #self.buttons do
local horizontal_group = HorizontalGroup:new{}
local line = self.buttons[i]
local sizer_space = self.sep_width * (#line - 1) + 2
for j = 1, #line do
local button = Button:new{
text = line[j].text,
enabled = line[j].enabled,
callback = line[j].callback,
width = (self.width - sizer_space)/#line,
bordersize = 0,
margin = 0,
padding = 0,
text_font_face = self.button_font_face,
text_font_size = self.button_font_size,
show_parent = self.show_parent,
}
local button_dim = button:getSize()
local vertical_sep = LineWidget:new{
background = Blitbuffer.gray(0.5),
dimen = Geom:new{
w = self.sep_width,
h = button_dim.h,
}
}
table.insert(horizontal_group, button)
if j < #line then
table.insert(horizontal_group, vertical_sep)
end
end -- end for each button
table.insert(self, horizontal_group)
if i < #self.buttons then
self:addHorizontalSep()
end
end -- end for each button line
end
function ButtonTable:addHorizontalSep()
table.insert(self, VerticalSpan:new{ width = Screen:scaleBySize(2) })
table.insert(self, LineWidget:new{
background = Blitbuffer.gray(0.5),
dimen = Geom:new{
w = self.width,
h = self.sep_width,
}
})
table.insert(self, VerticalSpan:new{ width = Screen:scaleBySize(2) })
end
return ButtonTable
| agpl-3.0 |
rudolfmleziva/AdministratorTeritorial | cocos2d/cocos/scripting/lua-bindings/auto/api/Scale9Sprite.lua | 6 | 10363 |
--------------------------------
-- @module Scale9Sprite
-- @extend Node
-- @parent_module ccui
--------------------------------
--
-- @function [parent=#Scale9Sprite] disableCascadeColor
-- @param self
--------------------------------
-- @overload self, cc.Sprite, rect_table, bool, vec2_table, size_table, rect_table
-- @overload self, cc.Sprite, rect_table, bool, rect_table
-- @function [parent=#Scale9Sprite] updateWithSprite
-- @param self
-- @param #cc.Sprite sprite
-- @param #rect_table rect
-- @param #bool rotated
-- @param #vec2_table offset
-- @param #size_table originalSize
-- @param #rect_table capInsets
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Returns the flag which indicates whether the widget is flipped horizontally or not.<br>
-- It only flips the texture of the widget, and not the texture of the widget's children.<br>
-- Also, flipping the texture doesn't alter the anchorPoint.<br>
-- If you want to flip the anchorPoint too, and/or to flip the children too use:<br>
-- widget->setScaleX(sprite->getScaleX() * -1);<br>
-- return true if the widget is flipped horizaontally, false otherwise.
-- @function [parent=#Scale9Sprite] isFlippedX
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Sets whether the widget should be flipped vertically or not.<br>
-- param bFlippedY true if the widget should be flipped vertically, flase otherwise.
-- @function [parent=#Scale9Sprite] setFlippedY
-- @param self
-- @param #bool flippedY
--------------------------------
-- Sets whether the widget should be flipped horizontally or not.<br>
-- param bFlippedX true if the widget should be flipped horizaontally, false otherwise.
-- @function [parent=#Scale9Sprite] setFlippedX
-- @param self
-- @param #bool flippedX
--------------------------------
--
-- @function [parent=#Scale9Sprite] setScale9Enabled
-- @param self
-- @param #bool enabled
--------------------------------
--
-- @function [parent=#Scale9Sprite] disableCascadeOpacity
-- @param self
--------------------------------
--
-- @function [parent=#Scale9Sprite] setInsetBottom
-- @param self
-- @param #float bottomInset
--------------------------------
-- @overload self, string
-- @overload self, string, rect_table
-- @function [parent=#Scale9Sprite] initWithSpriteFrameName
-- @param self
-- @param #string spriteFrameName
-- @param #rect_table capInsets
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Scale9Sprite] getSprite
-- @param self
-- @return Sprite#Sprite ret (return value: cc.Sprite)
--------------------------------
--
-- @function [parent=#Scale9Sprite] setInsetTop
-- @param self
-- @param #float topInset
--------------------------------
-- @overload self, cc.Sprite, rect_table, bool, rect_table
-- @overload self
-- @overload self, cc.Sprite, rect_table, rect_table
-- @overload self, cc.Sprite, rect_table, bool, vec2_table, size_table, rect_table
-- @function [parent=#Scale9Sprite] init
-- @param self
-- @param #cc.Sprite sprite
-- @param #rect_table rect
-- @param #bool rotated
-- @param #vec2_table offset
-- @param #size_table originalSize
-- @param #rect_table capInsets
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Scale9Sprite] setPreferredSize
-- @param self
-- @param #size_table size
--------------------------------
--
-- @function [parent=#Scale9Sprite] getInsetRight
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Scale9Sprite] setSpriteFrame
-- @param self
-- @param #cc.SpriteFrame spriteFrame
-- @param #rect_table capInsets
--------------------------------
--
-- @function [parent=#Scale9Sprite] getInsetBottom
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Creates and returns a new sprite object with the specified cap insets.<br>
-- You use this method to add cap insets to a sprite or to change the existing<br>
-- cap insets of a sprite. In both cases, you get back a new image and the<br>
-- original sprite remains untouched.<br>
-- param capInsets The values to use for the cap insets.
-- @function [parent=#Scale9Sprite] resizableSpriteWithCapInsets
-- @param self
-- @param #rect_table capInsets
-- @return Scale9Sprite#Scale9Sprite ret (return value: ccui.Scale9Sprite)
--------------------------------
--
-- @function [parent=#Scale9Sprite] isScale9Enabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Scale9Sprite] getCapInsets
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
--
-- @function [parent=#Scale9Sprite] getOriginalSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @overload self, string, rect_table
-- @overload self, string, rect_table, rect_table
-- @overload self, rect_table, string
-- @overload self, string
-- @function [parent=#Scale9Sprite] initWithFile
-- @param self
-- @param #string file
-- @param #rect_table rect
-- @param #rect_table capInsets
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Scale9Sprite] getInsetTop
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Scale9Sprite] setInsetLeft
-- @param self
-- @param #float leftInset
--------------------------------
-- @overload self, cc.SpriteFrame
-- @overload self, cc.SpriteFrame, rect_table
-- @function [parent=#Scale9Sprite] initWithSpriteFrame
-- @param self
-- @param #cc.SpriteFrame spriteFrame
-- @param #rect_table capInsets
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Scale9Sprite] getPreferredSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
--
-- @function [parent=#Scale9Sprite] setCapInsets
-- @param self
-- @param #rect_table rect
--------------------------------
-- Return the flag which indicates whether the widget is flipped vertically or not.<br>
-- It only flips the texture of the widget, and not the texture of the widget's children.<br>
-- Also, flipping the texture doesn't alter the anchorPoint.<br>
-- If you want to flip the anchorPoint too, and/or to flip the children too use:<br>
-- widget->setScaleY(widget->getScaleY() * -1);<br>
-- return true if the widget is flipped vertically, flase otherwise.
-- @function [parent=#Scale9Sprite] isFlippedY
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Scale9Sprite] getInsetLeft
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Scale9Sprite] setInsetRight
-- @param self
-- @param #float rightInset
--------------------------------
-- @overload self, string, rect_table, rect_table
-- @overload self
-- @overload self, rect_table, string
-- @overload self, string, rect_table
-- @overload self, string
-- @function [parent=#Scale9Sprite] create
-- @param self
-- @param #string file
-- @param #rect_table rect
-- @param #rect_table capInsets
-- @return Scale9Sprite#Scale9Sprite ret (return value: ccui.Scale9Sprite)
--------------------------------
-- @overload self, string, rect_table
-- @overload self, string
-- @function [parent=#Scale9Sprite] createWithSpriteFrameName
-- @param self
-- @param #string spriteFrameName
-- @param #rect_table capInsets
-- @return Scale9Sprite#Scale9Sprite ret (return value: ccui.Scale9Sprite)
--------------------------------
-- @overload self, cc.SpriteFrame, rect_table
-- @overload self, cc.SpriteFrame
-- @function [parent=#Scale9Sprite] createWithSpriteFrame
-- @param self
-- @param #cc.SpriteFrame spriteFrame
-- @param #rect_table capInsets
-- @return Scale9Sprite#Scale9Sprite ret (return value: ccui.Scale9Sprite)
--------------------------------
--
-- @function [parent=#Scale9Sprite] setAnchorPoint
-- @param self
-- @param #vec2_table anchorPoint
--------------------------------
--
-- @function [parent=#Scale9Sprite] setScaleY
-- @param self
-- @param #float scaleY
--------------------------------
--
-- @function [parent=#Scale9Sprite] setScaleX
-- @param self
-- @param #float scaleX
--------------------------------
--
-- @function [parent=#Scale9Sprite] getScaleY
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Scale9Sprite] getScaleX
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Scale9Sprite] updateDisplayedOpacity
-- @param self
-- @param #unsigned char parentOpacity
--------------------------------
--
-- @function [parent=#Scale9Sprite] cleanup
-- @param self
--------------------------------
-- @overload self, float, float
-- @overload self, float
-- @function [parent=#Scale9Sprite] setScale
-- @param self
-- @param #float scalex
-- @param #float scaley
--------------------------------
--
-- @function [parent=#Scale9Sprite] updateDisplayedColor
-- @param self
-- @param #color3b_table parentColor
--------------------------------
--
-- @function [parent=#Scale9Sprite] setContentSize
-- @param self
-- @param #size_table size
--------------------------------
--
-- @function [parent=#Scale9Sprite] getScale
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- js ctor
-- @function [parent=#Scale9Sprite] Scale9Sprite
-- @param self
return nil
| gpl-3.0 |
LGCaerwyn/QSanguosha-V2-mod | lua/ai/ling-ai.lua | 2 | 1404 | sgs.ai_skill_invoke.yishi = function(self, data)
local damage = data:toDamage()
local target = damage.to
if self:isFriend(target) then
if self:getDamagedEffects(target, self.players, true) or self:needToLoseHp(target, self.player, true) then return false
elseif target:isChained() and self:isGoodChainTarget(target, self.player, nil, nil, damage.card) then return false
elseif self:isWeak(target) or damage.damage > 1 then return true end
if target:getJudgingArea():isEmpty() or target:containsTrick("YanxiaoCard") then
return false
end
return true
else
if target:isNude() then return false end
if self:isWeak(target) or damage.damage > 1 or self:hasHeavySlashDamage(self.player, damage.card, target) then return false end
if target:getArmor() and self:evaluateArmor(target:getArmor(), target) > 3 and not (target:hasArmorEffect("silver_lion") and target:isWounded()) then
return true
end
if target:getEquips():isEmpty() and (target:getHandcardNum() == 1 and (target:hasSkills(sgs.need_kongcheng) or not self:hasLoseHandcardEffective(target))) then
return false
end
if (target:hasSkills("tuntian+zaoxian") and target:getPhase() == sgs.Player_NotActive)
or (target:isKongcheng() and target:hasSkills(sgs.lose_equip_skill)) then
return false
end
if self:getDamagedEffects(target, self.player, true) then return true end
return false
end
return false
end | lgpl-3.0 |
tommo/mock | 3rdparty/icosphere.lua | 1 | 3364 | -- lovr-icosphere v0.0.1
-- https://github.com/bjornbytes/lovr-icosphere
--[[
Copyright (c) 2017 Bjorn Swenson
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 phi = (1 + math.sqrt(5)) / 2
return function(subdivisions, radius)
radius = radius or 1
local vertices = {
{ -1, phi, 0 },
{ 1, phi, 0 },
{ -1, -phi, 0 },
{ 1, -phi, 0 },
{ 0, -1, phi },
{ 0, 1, phi },
{ 0, -1, -phi },
{ 0, 1, -phi },
{ phi, 0, -1 },
{ phi, 0, 1 },
{ -phi, 0, -1 },
{ -phi, 0, 1 }
}
local indices = {
1, 12, 6,
1, 6, 2,
1, 2, 8,
1, 8, 11,
1, 11, 12,
2, 6, 10,
6, 12, 5,
12, 11, 3,
11, 8, 7,
8, 2, 9,
4, 10, 5,
4, 5, 3,
4, 3, 7,
4, 7, 9,
4, 9, 10,
5, 10, 6,
3, 5, 12,
7, 3, 11,
9, 7, 8,
10, 9, 2
}
-- Cache vertex splits to avoid duplicates
local splits = {}
-- Splits vertices i and j, creating a new vertex and returning the index
local function split(i, j)
local key = i < j and (i .. ',' .. j) or (j .. ',' .. i)
if not splits[key] then
local x = (vertices[i][1] + vertices[j][1]) / 2
local y = (vertices[i][2] + vertices[j][2]) / 2
local z = (vertices[i][3] + vertices[j][3]) / 2
table.insert(vertices, { x, y, z })
splits[key] = #vertices
end
return splits[key]
end
-- Subdivide
for _ = 1, subdivisions or 0 do
for i = #indices, 1, -3 do
local v1, v2, v3 = indices[i - 2], indices[i - 1], indices[i - 0]
local a = split(v1, v2)
local b = split(v2, v3)
local c = split(v3, v1)
table.insert(indices, v1)
table.insert(indices, a)
table.insert(indices, c)
table.insert(indices, v2)
table.insert(indices, b)
table.insert(indices, a)
table.insert(indices, v3)
table.insert(indices, c)
table.insert(indices, b)
table.insert(indices, a)
table.insert(indices, b)
table.insert(indices, c)
table.remove(indices, i - 0)
table.remove(indices, i - 1)
table.remove(indices, i - 2)
end
end
-- Normalize
for i, v in ipairs(vertices) do
local x, y, z = unpack(v)
local length = math.sqrt(x * x + y * y + z * z)
v[1], v[2], v[3] = x / length * radius, y / length * radius, z / length * radius
end
return vertices, indices
end
| mit |
openwrt-es/openwrt-luci | applications/luci-app-ocserv/luasrc/controller/ocserv.lua | 29 | 1838 | -- Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.ocserv", package.seeall)
function index()
if not nixio.fs.access("/etc/config/ocserv") then
return
end
local page
page = entry({"admin", "services", "ocserv"}, alias("admin", "services", "ocserv", "main"),
_("OpenConnect VPN"))
page.dependent = true
page = entry({"admin", "services", "ocserv", "main"},
cbi("ocserv/main"),
_("Server Settings"), 200)
page.dependent = true
page = entry({"admin", "services", "ocserv", "users"},
cbi("ocserv/users"),
_("User Settings"), 300)
page.dependent = true
entry({"admin", "services", "ocserv", "status"},
call("ocserv_status")).leaf = true
entry({"admin", "services", "ocserv", "disconnect"},
post("ocserv_disconnect")).leaf = true
end
function ocserv_status()
local ipt = io.popen("/usr/bin/occtl show users");
if ipt then
local fwd = { }
while true do
local ln = ipt:read("*l")
if not ln then break end
local id, user, group, vpn_ip, ip, device, time, cipher, status =
ln:match("^%s*(%d+)%s+([-_%w]+)%s+([%(%)%.%*-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%(%)%:%.-_%w]+)%s+([%:%.-_%w]+).*")
if id then
fwd[#fwd+1] = {
id = id,
user = user,
group = group,
vpn_ip = vpn_ip,
ip = ip,
device = device,
time = time,
cipher = cipher,
status = status
}
end
end
ipt:close()
luci.http.prepare_content("application/json")
luci.http.write_json(fwd)
end
end
function ocserv_disconnect(num)
local idx = tonumber(num)
if idx and idx > 0 then
luci.sys.call("/usr/bin/occtl disconnect id %d" % idx)
luci.http.status(200, "OK")
return
end
luci.http.status(400, "Bad request")
end
| apache-2.0 |
tommo/mock | mock/gfx/AuroraSprite.lua | 1 | 5717 | --[[
* MOCK framework for Moai
* Copyright (C) 2012 Tommo Zhou(tommo.zhou@gmail.com). All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
module 'mock'
--------------------------------------------------------------------
CLASS: AuroraSprite ( GraphicsPropComponent )
:MODEL {
Field 'sprite' :asset( 'aurora_sprite' ) :getset('Sprite');
Field 'default' :string() :selection( 'getClipNames' );
Field 'autoPlay' :boolean();
}
wrapWithMoaiPropMethods( AuroraSprite, 'prop' )
mock.registerComponent( 'AuroraSprite', AuroraSprite )
mock.registerEntityWithComponent( 'AuroraSprite', AuroraSprite )
--------------------------------------------------------------------
function AuroraSprite:__init()
self.prop = MOAIProp.new()
self.driver = MOAIAnim.new()
self.spriteData = false
self.currentClip = false
self.playFPS = 60
self.playSpeed = 1
self.driver:reserveLinks( 3 ) --offset x & offset y & frame index
end
function AuroraSprite:onAttach( entity )
return entity:_attachProp( self.prop )
end
function AuroraSprite:onDetach( entity )
self:stop()
return entity:_detachProp( self.prop )
end
function AuroraSprite:setSprite( path )
self:stop( true )
self.spritePath = path
local spriteData, node = loadAsset( path )
--TODO? assert asset node type
if spriteData then
self:stop( true )
self.currentClip = false
self.spriteData = spriteData
self.prop:setDeck( spriteData.frameDeck )
self.prop:setIndex( 0 )
self.prop:forceUpdate()
end
end
function AuroraSprite:getSprite()
return self.spritePath
end
function AuroraSprite:getSpriteData()
return self.spriteData
end
function AuroraSprite:getClipNames()
local data = self.spriteData
if not data then return nil end
local result = {}
for k,i in pairs( data.animations ) do
table.insert( result, { k, k } )
end
return result
end
function AuroraSprite:setScissorRect( r )
return self.prop:setScissorRect( r )
end
function AuroraSprite:getClipTable()
local data = self.spriteData
if not data then
_error('animation not load', 2)
return nil
end
return data.animations
end
function AuroraSprite:getClip( name )
local data = self.spriteData
if not data then
_error('animation not load', 2)
return nil
end
return data.animations[ name ]
end
function AuroraSprite:getClipLength( name )
local clip = name and self:getClip( name ) or self.currentClip
if clip then return clip.length * self.playFPS end
end
function AuroraSprite:setClip( name, mode )
if self.currentClip and self.currentClip.name == name then return false end
local clip = self:getClip( name )
if not clip then
_error( 'animation clip not found:'..name )
return
end
self.currentClip=clip
if self.driver then self.driver:stop() end
---bind animcurve to driver
local driver = MOAIAnim.new()
local indexCurve = clip.indexCurve
local offsetXCurve = clip.offsetXCurve
local offsetYCurve = clip.offsetYCurve
driver:reserveLinks( 3 )
driver:setLink( 1, indexCurve, self.prop, MOAIProp.ATTR_INDEX )
-- driver:setLink( 2, offsetXCurve, self.prop, MOAIProp.ATTR_X_LOC )
-- driver:setLink( 3, offsetYCurve, self.prop, MOAIProp.ATTR_Y_LOC )
driver:setMode( mode or clip.mode or MOAITimer.NORMAL )
self.driver = driver
self:setFPS(self.playFPS)
self:apply( 0 )
self:setTime( 0 )
return true
end
-----------
function AuroraSprite:setFPS( fps )
self.playFPS = fps
self:setSpeed( self.playSpeed )
end
function AuroraSprite:getFPS()
return self.playFPS
end
function AuroraSprite:setSpeed( speed )
speed = speed or 1
self.playSpeed = speed
self.driver:setSpeed( speed * self.playFPS )
end
function AuroraSprite:getSpeed()
return self.playSpeed
end
function AuroraSprite:setTime( time )
return self.driver:setTime( time )
end
function AuroraSprite:apply( time )
return self.driver:apply( time / self.playFPS )
end
-----------Play control
function AuroraSprite:play( clipName, mode )
if self:setClip( clipName, mode ) then return self:start() end
end
function AuroraSprite:resetAndPlay( clipName, mode )
if self:setClip( clipName, mode ) then --playing a new clip
return self:start()
else --same as playing clip
self:setTime( 0 )
self:apply( 0 )
self:start()
end
end
function AuroraSprite:start()
self.driver:start()
end
function AuroraSprite:reset()
self:setTime( 0 )
end
function AuroraSprite:stop( reset )
self.driver:stop()
if reset then return self:reset() end
end
function AuroraSprite:pause( paused )
self.driver:pause( paused )
end
function AuroraSprite:isPaused()
end
function AuroraSprite:wait()
return MOAICoroutine.blockOnAction( self.driver )
end
function AuroraSprite:isPlaying()
return self.driver:isBusy()
end
| mit |
RebootRevival/FFXI_Test | scripts/globals/items/holy_maul_+1.lua | 1 | 1108 | -----------------------------------------
-- ID: 17114
-- Item: Holy Maul +1
-- Additional Effect: Light Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
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, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = msgBasic.ADD_EFFECT_DMG;
if (dmg < 0) then
message = msgBasic.ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
gmarek/contrib | ingress/controllers/nginx/lua/vendor/lua-resty-http/lib/resty/http_headers.lua | 69 | 1716 | local rawget, rawset, setmetatable =
rawget, rawset, setmetatable
local str_gsub = string.gsub
local str_lower = string.lower
local _M = {
_VERSION = '0.01',
}
-- Returns an empty headers table with internalised case normalisation.
-- Supports the same cases as in ngx_lua:
--
-- headers.content_length
-- headers["content-length"]
-- headers["Content-Length"]
function _M.new(self)
local mt = {
normalised = {},
}
mt.__index = function(t, k)
local k_hyphened = str_gsub(k, "_", "-")
local matched = rawget(t, k)
if matched then
return matched
else
local k_normalised = str_lower(k_hyphened)
return rawget(t, mt.normalised[k_normalised])
end
end
-- First check the normalised table. If there's no match (first time) add an entry for
-- our current case in the normalised table. This is to preserve the human (prettier) case
-- instead of outputting lowercased header names.
--
-- If there's a match, we're being updated, just with a different case for the key. We use
-- the normalised table to give us the original key, and perorm a rawset().
mt.__newindex = function(t, k, v)
-- we support underscore syntax, so always hyphenate.
local k_hyphened = str_gsub(k, "_", "-")
-- lowercase hyphenated is "normalised"
local k_normalised = str_lower(k_hyphened)
if not mt.normalised[k_normalised] then
mt.normalised[k_normalised] = k_hyphened
rawset(t, k_hyphened, v)
else
rawset(t, mt.normalised[k_normalised], v)
end
end
return setmetatable({}, mt)
end
return _M
| apache-2.0 |
hanxi/LoveClear | Resources/Cocos2dConstants.lua | 8 | 7778 | local CCConstants = {}
CCConstants.SPRITE_INDEX_NOT_INITIALIZED = 0xffffffff
CCConstants.TMX_ORIENTATION_HEX = 0x1
CCConstants.TMX_ORIENTATION_ISO = 0x2
CCConstants.TMX_ORIENTATION_ORTHO = 0x0
CCConstants.Z_COMPRESSION_BZIP2 = 0x1
CCConstants.Z_COMPRESSION_GZIP = 0x2
CCConstants.Z_COMPRESSION_NONE = 0x3
CCConstants.Z_COMPRESSION_ZLIB = 0x0
CCConstants.BLEND_DST = 0x303
CCConstants.BLEND_SRC = 0x1
CCConstants.DIRECTOR_IOS_USE_BACKGROUND_THREAD = 0x0
CCConstants.DIRECTOR_MAC_THREAD = 0x0
CCConstants.DIRECTOR_STATS_INTERVAL = 0.1
CCConstants.ENABLE_BOX2_D_INTEGRATION = 0x0
CCConstants.ENABLE_DEPRECATED = 0x1
CCConstants.ENABLE_GL_STATE_CACHE = 0x1
CCConstants.ENABLE_PROFILERS = 0x0
CCConstants.ENABLE_STACKABLE_ACTIONS = 0x1
CCConstants.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0x0
CCConstants.GL_ALL = 0x0
CCConstants.LABELATLAS_DEBUG_DRAW = 0x0
CCConstants.LABELBMFONT_DEBUG_DRAW = 0x0
CCConstants.MAC_USE_DISPLAY_LINK_THREAD = 0x0
CCConstants.MAC_USE_MAIN_THREAD = 0x2
CCConstants.MAC_USE_OWN_THREAD = 0x1
CCConstants.NODE_RENDER_SUBPIXEL = 0x1
CCConstants.PVRMIPMAP_MAX = 0x10
CCConstants.SPRITEBATCHNODE_RENDER_SUBPIXEL = 0x1
CCConstants.SPRITE_DEBUG_DRAW = 0x0
CCConstants.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0x0
CCConstants.TEXTURE_ATLAS_USE_VAO = 0x1
CCConstants.USE_L_A88_LABELS = 0x1
CCConstants.ACTION_TAG_INVALID = -1
CCConstants.DEVICE_MAC = 0x6
CCConstants.DEVICE_MAC_RETINA_DISPLAY = 0x7
CCConstants.DEVICEI_PAD = 0x4
CCConstants.DEVICEI_PAD_RETINA_DISPLAY = 0x5
CCConstants.DEVICEI_PHONE = 0x0
CCConstants.DEVICEI_PHONE5 = 0x2
CCConstants.DEVICEI_PHONE5_RETINA_DISPLAY = 0x3
CCConstants.DEVICEI_PHONE_RETINA_DISPLAY = 0x1
CCConstants.DIRECTOR_PROJECTION2_D = 0x0
CCConstants.DIRECTOR_PROJECTION3_D = 0x1
CCConstants.DIRECTOR_PROJECTION_CUSTOM = 0x2
CCConstants.DIRECTOR_PROJECTION_DEFAULT = 0x1
CCConstants.FILE_UTILS_SEARCH_DIRECTORY_MODE = 0x1
CCConstants.FILE_UTILS_SEARCH_SUFFIX_MODE = 0x0
CCConstants.FLIPED_ALL = 0xe0000000
CCConstants.FLIPPED_MASK = 0x1fffffff
CCConstants.IMAGE_FORMAT_JPEG = 0x0
CCConstants.IMAGE_FORMAT_PNG = 0x1
CCConstants.ITEM_SIZE = 0x20
CCConstants.LABEL_AUTOMATIC_WIDTH = -1
CCConstants.LINE_BREAK_MODE_CHARACTER_WRAP = 0x1
CCConstants.LINE_BREAK_MODE_CLIP = 0x2
CCConstants.LINE_BREAK_MODE_HEAD_TRUNCATION = 0x3
CCConstants.LINE_BREAK_MODE_MIDDLE_TRUNCATION = 0x5
CCConstants.LINE_BREAK_MODE_TAIL_TRUNCATION = 0x4
CCConstants.LINE_BREAK_MODE_WORD_WRAP = 0x0
CCConstants.MAC_VERSION_10_6 = 0xa060000
CCConstants.MAC_VERSION_10_7 = 0xa070000
CCConstants.MAC_VERSION_10_8 = 0xa080000
CCConstants.MENU_HANDLER_PRIORITY = -128
CCConstants.MENU_STATE_TRACKING_TOUCH = 0x1
CCConstants.MENU_STATE_WAITING = 0x0
CCConstants.NODE_TAG_INVALID = -1
CCConstants.PARTICLE_DURATION_INFINITY = -1
CCConstants.PARTICLE_MODE_GRAVITY = 0x0
CCConstants.PARTICLE_MODE_RADIUS = 0x1
CCConstants.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS = -1
CCConstants.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE = -1
CCConstants.POSITION_TYPE_FREE = 0x0
CCConstants.POSITION_TYPE_GROUPED = 0x2
CCConstants.POSITION_TYPE_RELATIVE = 0x1
CCConstants.PRIORITY_NON_SYSTEM_MIN = -2147483647
CCConstants.PRIORITY_SYSTEM = -2147483648
CCConstants.PROGRESS_TIMER_TYPE_BAR = 0x1
CCConstants.PROGRESS_TIMER_TYPE_RADIAL = 0x0
CCConstants.REPEAT_FOREVER = 0xfffffffe
CCConstants.RESOLUTION_MAC = 0x1
CCConstants.RESOLUTION_MAC_RETINA_DISPLAY = 0x2
CCConstants.RESOLUTION_UNKNOWN = 0x0
CCConstants.TMX_TILE_DIAGONAL_FLAG = 0x20000000
CCConstants.TMX_TILE_HORIZONTAL_FLAG = 0x80000000
CCConstants.TMX_TILE_VERTICAL_FLAG = 0x40000000
CCConstants.TEXT_ALIGNMENT_CENTER = 0x1
CCConstants.TEXT_ALIGNMENT_LEFT = 0x0
CCConstants.TEXT_ALIGNMENT_RIGHT = 0x2
CCConstants.TEXTURE2_D_PIXEL_FORMAT_A8 = 0x3
CCConstants.TEXTURE2_D_PIXEL_FORMAT_A_I88 = 0x5
CCConstants.TEXTURE2_D_PIXEL_FORMAT_DEFAULT = 0x0
CCConstants.TEXTURE2_D_PIXEL_FORMAT_I8 = 0x4
CCConstants.TEXTURE2_D_PIXEL_FORMAT_PVRTC2 = 0x9
CCConstants.TEXTURE2_D_PIXEL_FORMAT_PVRTC4 = 0x8
CCConstants.TEXTURE2_D_PIXEL_FORMAT_RG_B565 = 0x2
CCConstants.TEXTURE2_D_PIXEL_FORMAT_RGB5_A1 = 0x7
CCConstants.TEXTURE2_D_PIXEL_FORMAT_RG_B888 = 0x1
CCConstants.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444 = 0x6
CCConstants.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888 = 0x0
CCConstants.TOUCHES_ALL_AT_ONCE = 0x0
CCConstants.TOUCHES_ONE_BY_ONE = 0x1
CCConstants.TRANSITION_ORIENTATION_DOWN_OVER = 0x1
CCConstants.TRANSITION_ORIENTATION_LEFT_OVER = 0x0
CCConstants.TRANSITION_ORIENTATION_RIGHT_OVER = 0x1
CCConstants.TRANSITION_ORIENTATION_UP_OVER = 0x0
CCConstants.UNIFORM_COS_TIME = 0x5
CCConstants.UNIFORM_MV_MATRIX = 0x1
CCConstants.UNIFORM_MVP_MATRIX = 0x2
CCConstants.UNIFORM_P_MATRIX = 0x0
CCConstants.UNIFORM_RANDOM01 = 0x6
CCConstants.UNIFORM_SAMPLER = 0x7
CCConstants.UNIFORM_SIN_TIME = 0x4
CCConstants.UNIFORM_TIME = 0x3
CCConstants.UNIFORM_MAX = 0x8
CCConstants.VERTEX_ATTRIB_FLAG_COLOR = 0x2
CCConstants.VERTEX_ATTRIB_FLAG_NONE = 0x0
CCConstants.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = 0x7
CCConstants.VERTEX_ATTRIB_FLAG_POSITION = 0x1
CCConstants.VERTEX_ATTRIB_FLAG_TEX_COORDS = 0x4
CCConstants.VERTEX_ATTRIB_COLOR = 0x1
CCConstants.VERTEX_ATTRIB_MAX = 0x3
CCConstants.VERTEX_ATTRIB_POSITION = 0x0
CCConstants.VERTEX_ATTRIB_TEX_COORDS = 0x2
CCConstants.VERTICAL_TEXT_ALIGNMENT_BOTTOM = 0x2
CCConstants.VERTICAL_TEXT_ALIGNMENT_CENTER = 0x1
CCConstants.VERTICAL_TEXT_ALIGNMENT_TOP = 0x0
CCConstants.OS_VERSION_4_0 = 0x4000000
CCConstants.OS_VERSION_4_0_1 = 0x4000100
CCConstants.OS_VERSION_4_1 = 0x4010000
CCConstants.OS_VERSION_4_2 = 0x4020000
CCConstants.OS_VERSION_4_2_1 = 0x4020100
CCConstants.OS_VERSION_4_3 = 0x4030000
CCConstants.OS_VERSION_4_3_1 = 0x4030100
CCConstants.OS_VERSION_4_3_2 = 0x4030200
CCConstants.OS_VERSION_4_3_3 = 0x4030300
CCConstants.OS_VERSION_4_3_4 = 0x4030400
CCConstants.OS_VERSION_4_3_5 = 0x4030500
CCConstants.OS_VERSION_5_0 = 0x5000000
CCConstants.OS_VERSION_5_0_1 = 0x5000100
CCConstants.OS_VERSION_5_1_0 = 0x5010000
CCConstants.OS_VERSION_6_0_0 = 0x6000000
CCConstants.ANIMATION_FRAME_DISPLAYED_NOTIFICATION = 'CCAnimationFrameDisplayedNotification'
CCConstants.CHIPMUNK_IMPORT = 'chipmunk.h'
CCConstants.ATTRIBUTE_NAME_COLOR = 'a_color'
CCConstants.ATTRIBUTE_NAME_POSITION = 'a_position'
CCConstants.ATTRIBUTE_NAME_TEX_COORD = 'a_texCoord'
CCConstants.SHADER_POSITION_COLOR = 'ShaderPositionColor'
CCConstants.SHADER_POSITION_LENGTH_TEXURE_COLOR = 'ShaderPositionLengthTextureColor'
CCConstants.SHADER_POSITION_TEXTURE = 'ShaderPositionTexture'
CCConstants.SHADER_POSITION_TEXTURE_A8_COLOR = 'ShaderPositionTextureA8Color'
CCConstants.SHADER_POSITION_TEXTURE_COLOR = 'ShaderPositionTextureColor'
CCConstants.SHADER_POSITION_TEXTURE_COLOR_ALPHA_TEST = 'ShaderPositionTextureColorAlphaTest'
CCConstants.SHADER_POSITION_TEXTURE_U_COLOR = 'ShaderPositionTexture_uColor'
CCConstants.SHADER_POSITION_U_COLOR = 'ShaderPosition_uColor'
CCConstants.UNIFORM_ALPHA_TEST_VALUE_S = 'CC_AlphaValue'
CCConstants.UNIFORM_COS_TIME_S = 'CC_CosTime'
CCConstants.UNIFORM_MV_MATRIX_S = 'CC_MVMatrix'
CCConstants.UNIFORM_MVP_MATRIX_S = 'CC_MVPMatrix'
CCConstants.UNIFORM_P_MATRIX_S = 'CC_PMatrix'
CCConstants.UNIFORM_RANDOM01_S = 'CC_Random01'
CCConstants.UNIFORM_SAMPLER_S = 'CC_Texture0'
CCConstants.UNIFORM_SIN_TIME_S = 'CC_SinTime'
CCConstants.UNIFORM_TIME_S = 'CC_Time'
local modename = "CCConstants"
local CCConstantsproxy = {}
local CCConstantsMt = {
__index = CCConstants,
__newindex = function (t ,k ,v)
print("attemp to update a read-only table")
end
}
setmetatable(CCConstantsproxy,CCConstantsMt)
_G[modename] = CCConstantsproxy
package.loaded[modename] = CCConstantsproxy
| mit |
khoshhal/Fighterbot | plugins/expire.lua | 32 | 1772 | local filename='data/expire.lua'
local cronned = load_from_file(filename)
local function save_cron(msg, text,date)
local origin = get_receiver(msg)
if not cronned[date] then
cronned[date] = {}
end
local arr = { origin, text } ;
table.insert(cronned[date], arr)
serialize_to_file(cronned, filename)
return 'Saved!'
end
local function delete_cron(date)
for k,v in pairs(cronned) do
if k == date then
cronned[k]=nil
end
end
serialize_to_file(cronned, filename)
end
local function cron()
for date, values in pairs(cronned) do
if date < os.time() then --time's up
send_msg(values[1][1], "Time's up:"..values[1][2], ok_cb, false)
delete_cron(date)
end
end
end
local function actually_run(msg, delay,text)
if (not delay or not text) then
return "Usage: !remind [delay: 2h3m1s] text"
end
save_cron(msg, text,delay)
return "I'll remind you on " .. os.date("%x at %H:%M:%S",delay) .. " about '" .. text .. "'"
end
local function run(msg, matches)
local sum = 0
for i = 1, #matches-1 do
local b,_ = string.gsub(matches[i],"[a-zA-Z]","")
if string.find(matches[i], "s") then
sum=sum+b
end
if string.find(matches[i], "m") then
sum=sum+b*60
end
if string.find(matches[i], "h") then
sum=sum+b*3600
end
end
local date=sum+os.time()
local text = matches[#matches]
local text = actually_run(msg, date, text)
return text
end
return {
patterns = {
"^[!/](expire) ([0-9]+[hmsdHMSD]) (.+)$", --- e.g : for a month enter : 720hms - then , in text enter gp id and admin id
"^[!/](expire) ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$",
"^[!/](expire) ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
lrmssc/dlaqdpc | dianliwangguomanyouji/cocos2d/plugin/luabindings/auto/api/AgentManager.lua | 146 | 1798 |
--------------------------------
-- @module AgentManager
-- @parent_module plugin
--------------------------------
--
-- @function [parent=#AgentManager] getSocialPlugin
-- @param self
-- @return plugin::ProtocolSocial#plugin::ProtocolSocial ret (return value: cc.plugin::ProtocolSocial)
--------------------------------
--
-- @function [parent=#AgentManager] getAdsPlugin
-- @param self
-- @return plugin::ProtocolAds#plugin::ProtocolAds ret (return value: cc.plugin::ProtocolAds)
--------------------------------
--
-- @function [parent=#AgentManager] purge
-- @param self
--------------------------------
--
-- @function [parent=#AgentManager] getUserPlugin
-- @param self
-- @return plugin::ProtocolUser#plugin::ProtocolUser ret (return value: cc.plugin::ProtocolUser)
--------------------------------
--
-- @function [parent=#AgentManager] getIAPPlugin
-- @param self
-- @return plugin::ProtocolIAP#plugin::ProtocolIAP ret (return value: cc.plugin::ProtocolIAP)
--------------------------------
--
-- @function [parent=#AgentManager] getSharePlugin
-- @param self
-- @return plugin::ProtocolShare#plugin::ProtocolShare ret (return value: cc.plugin::ProtocolShare)
--------------------------------
--
-- @function [parent=#AgentManager] getAnalyticsPlugin
-- @param self
-- @return plugin::ProtocolAnalytics#plugin::ProtocolAnalytics ret (return value: cc.plugin::ProtocolAnalytics)
--------------------------------
--
-- @function [parent=#AgentManager] destroyInstance
-- @param self
--------------------------------
--
-- @function [parent=#AgentManager] getInstance
-- @param self
-- @return plugin::AgentManager#plugin::AgentManager ret (return value: cc.plugin::AgentManager)
return nil
| mit |
rudolfmleziva/AdministratorTeritorial | cocos2d/cocos/scripting/lua-bindings/auto/api/AudioEngine.lua | 10 | 6277 |
--------------------------------
-- @module AudioEngine
-- @parent_module ccexp
--------------------------------
--
-- @function [parent=#AudioEngine] lazyInit
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Sets the current playback position of an audio instance.<br>
-- param audioID an audioID returned by the play2d function<br>
-- return
-- @function [parent=#AudioEngine] setCurrentTime
-- @param self
-- @param #int audioID
-- @param #float time
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Gets the volume value of an audio instance.<br>
-- param audioID an audioID returned by the play2d function<br>
-- return volume value (range from 0.0 to 1.0)
-- @function [parent=#AudioEngine] getVolume
-- @param self
-- @param #int audioID
-- @return float#float ret (return value: float)
--------------------------------
-- Uncache the audio data from internal buffer.<br>
-- AudioEngine cache audio data on ios platform<br>
-- warning This can lead to stop related audio first.<br>
-- param filePath The path of an audio file
-- @function [parent=#AudioEngine] uncache
-- @param self
-- @param #string filePath
--------------------------------
-- Resume all suspended audio instances
-- @function [parent=#AudioEngine] resumeAll
-- @param self
--------------------------------
-- Stop all audio instances
-- @function [parent=#AudioEngine] stopAll
-- @param self
--------------------------------
-- Pause an audio instance.<br>
-- param audioID an audioID returned by the play2d function
-- @function [parent=#AudioEngine] pause
-- @param self
-- @param #int audioID
--------------------------------
-- Release related objects<br>
-- warning It must be called before the application exit
-- @function [parent=#AudioEngine] end
-- @param self
--------------------------------
--
-- @function [parent=#AudioEngine] getMaxAudioInstance
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Gets the current playback position of an audio instance.<br>
-- param audioID an audioID returned by the play2d function<br>
-- return the current playback position of an audio instance
-- @function [parent=#AudioEngine] getCurrentTime
-- @param self
-- @param #int audioID
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#AudioEngine] setMaxAudioInstance
-- @param self
-- @param #int maxInstances
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Checks whether an audio instance is loop.<br>
-- param audioID an audioID returned by the play2d function<br>
-- return Whether or not an audio instance is loop.
-- @function [parent=#AudioEngine] isLoop
-- @param self
-- @param #int audioID
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Pause all playing audio instances
-- @function [parent=#AudioEngine] pauseAll
-- @param self
--------------------------------
-- Uncache all audio data from internal buffer.<br>
-- warning All audio will be stopped first.<br>
-- param
-- @function [parent=#AudioEngine] uncacheAll
-- @param self
--------------------------------
-- Sets volume for an audio instance.<br>
-- param audioID an audioID returned by the play2d function<br>
-- param volume volume value (range from 0.0 to 1.0)
-- @function [parent=#AudioEngine] setVolume
-- @param self
-- @param #int audioID
-- @param #float volume
--------------------------------
-- Play 2d sound<br>
-- param filePath The path of an audio file<br>
-- param loop Whether audio instance loop or not<br>
-- param volume volume value (range from 0.0 to 1.0)<br>
-- param profile a profile for audio instance<br>
-- return an audio ID. It allows you to dynamically change the behavior of an audio instance on the fly.
-- @function [parent=#AudioEngine] play2d
-- @param self
-- @param #string filePath
-- @param #bool loop
-- @param #float volume
-- @param #cc.experimental::AudioProfile profile
-- @return int#int ret (return value: int)
--------------------------------
-- Returns the state of an audio instance.<br>
-- param audioID an audioID returned by the play2d function<br>
-- return the status of an audio instance
-- @function [parent=#AudioEngine] getState
-- @param self
-- @param #int audioID
-- @return int#int ret (return value: int)
--------------------------------
-- Resume an audio instance.<br>
-- param audioID an audioID returned by the play2d function
-- @function [parent=#AudioEngine] resume
-- @param self
-- @param #int audioID
--------------------------------
-- Stop an audio instance.<br>
-- param audioID an audioID returned by the play2d function
-- @function [parent=#AudioEngine] stop
-- @param self
-- @param #int audioID
--------------------------------
-- Gets the duration of an audio instance.<br>
-- param audioID an audioID returned by the play2d function<br>
-- return the duration of an audio instance
-- @function [parent=#AudioEngine] getDuration
-- @param self
-- @param #int audioID
-- @return float#float ret (return value: float)
--------------------------------
-- Sets whether an audio instance loop or not. <br>
-- param audioID an audioID returned by the play2d function<br>
-- param loop Whether audio instance loop or not
-- @function [parent=#AudioEngine] setLoop
-- @param self
-- @param #int audioID
-- @param #bool loop
--------------------------------
-- Gets the default profile of audio instances<br>
-- return the default profile of audio instances
-- @function [parent=#AudioEngine] getDefaultProfile
-- @param self
-- @return experimental::AudioProfile#experimental::AudioProfile ret (return value: cc.experimental::AudioProfile)
--------------------------------
-- @overload self, string
-- @overload self, int
-- @function [parent=#AudioEngine] getProfile
-- @param self
-- @param #int audioID
-- @return experimental::AudioProfile#experimental::AudioProfile ret (return value: cc.experimental::AudioProfile)
return nil
| gpl-3.0 |
tommo/mock | mock/ai/BTScript.lua | 1 | 14192 | module 'mock'
local match = string.match
local trim = string.trim
local gsplit = string.gsplit
local function calcIndent( l )
local k = match( l, '^\t*' )
if not k then return 0 end
return #k
end
--------------------------------------------------------------------
local ParseContextProto = {}
local ParseContextMT = { __index = ParseContextProto }
function ParseContextProto:init()
self.rootNode = { type = 'root', children = {}, indent = -1, parent = false }
self.currentIndent = -1
self.currentNode = self.rootNode
self.currentParent = false
self.currentDecorationNode = false
end
local function printBTScriptNode( n, indent )
io.write( string.rep( '\t', indent or 0 ) )
print( string.format( '%s : %s >%d', tostring( n.type ), tostring( n.value ), n.indent or 0 ))
for i, child in ipairs( n.children ) do
printBTScriptNode( child, (indent or 0) + 1 )
end
end
function ParseContextProto:addLineChild()
local node = { type = false, children = {}, indent = self.currentIndent }
node.parent = self.currentLineHead
if self.currentLineHead then
table.insert( self.currentLineHead.children, node )
self.currentLineHead.lineEnd = true
end
self.currentNode = node
return node
end
function ParseContextProto:add()
local node = { type = false, children = {}, indent = self.currentIndent }
node.parent = self.currentParent
if self.currentParent then
if self.currentParent.lineEnd then
_warn( 'ambiguous child layout', self.currentLineNo )
end
table.insert( self.currentParent.children, node )
end
self.currentNode = node
return node
end
function ParseContextProto:matchIndent( indent )
-- if indent == self.currentIndent then --parent node no change
-- return self:add()
-- end
if indent > self.currentIndent then --going deeper
self.currentParent = self.currentNode
self.currentIndent = indent
return self:add()
end
--find previous indent level
local found = false
local n = self.currentNode
while n do
if n.indent == indent and n.parent.indent < indent then found = n break end
n = n.parent
end
if not found then
error( 'indent no match' )
end
self.currentNode = n
self.currentParent = self.currentNode.parent
self.currentIndent = indent
return self:add()
end
function ParseContextProto:setErrorInfo( info )
self.errorInfo = info
end
function ParseContextProto:set( type, value )
if not self.currentLineHead then
self.currentLineHead = self.currentNode
else
self:addLineChild()
if self.decorateState == 'decorating' then
self.decorateState = 'decorated'
self.currentParent = self.currentNode
self.currentLineHead = self.currentNode
self.currentDecorationNode = false
elseif self.decorateState == 'decorated' then
-- self:setErrorInfo( 'decorator node can only have ONE target node' )
-- return false
end
end
self.currentNode.type = type
self.currentNode.value = value or 'NONAME'
return true
end
function ParseContextProto:setArguments( args )
self.currentNode.arguments = args or false
end
function ParseContextProto:parseArguments( raw )
local result = {}
for part in string.gsplit( raw, ',', true ) do
local k, v = string.match( part, '^%s*([%w_.]+)%s*=%s*([%w_.%+%-]+)%s*' )
if k then
result[ k ] = v
else
self:setErrorInfo( 'failed parsing arguments' )
return nil
end
end
return result
end
function ParseContextProto:parseCommon( content, pos, type, symbol )
-- local content = content:sub( pos )
local pattern = '^'..symbol..'%s*([%w_.]*)%s*'
local s, e, match = string.find( content, pattern, pos )
-- print( s,e,type,symbol, content:sub( pos, -1 ) )
if not s then return pos end
if self:set( type, match ) then
return e + 1
else
return pos
end
end
function ParseContextProto:parseLineCommon( content, pos, type, symbol )
-- local content = content:sub( pos )
local s, e, match = string.find( content, '^'..symbol..'%s*(.*)%s*', pos )
if not s then return pos end
if self:set( type, match ) then
return e + 1
else
return pos
end
end
function ParseContextProto:parseCommonWithArguments( content, pos, type, symbol )
-- local content = content:sub( pos )
local s, e, match = string.find( content, '^'..symbol..'%s*([%w_.]+)%s*', pos )
if not s then return pos end
if self:set( type, match ) then
local pos1 = e + 1
--test empty arg first
local s, e, match = string.find( content, '%(%s*%)%s*', pos1 )
if s then return e + 1 end
--test kvargs
local s, e, match = string.find( content, '%(%s*(.*)s*%)%s*', pos1 )
if s then
local args = self:parseArguments( match )
if not args then return pos end
self:setArguments( args )
return e + 1
else
return pos1
end
else
return pos
end
end
function ParseContextProto:parseDecorator( content, pos, type, symbol )
-- local content = content:sub( pos )
local s, e, match = string.find( content, '^'..symbol..'%s*', pos )
if not s then return pos end
if self:set( type, type ) then
self.decorateState = 'decorating'
self.currentDecorationNode = self.currentNode
return e + 1
else
return pos
end
end
function ParseContextProto:parseDecoratorFor( content, pos, type, symbol )
local s, e, match = string.find( content, '^'..symbol..'%s*', pos )
if not s then return pos end
if self:set( type, type ) then
local pos1 = e + 1
local s, e, match = string.find( content, '%(%s*(.*)s*%)%s*', pos1 )
if s then
local argStrs = string.split( match, ',', true )
local args = {}
for i, v in ipairs( argStrs ) do
args[ i ] = tonumber( v )
end
local minCount = args[ 1 ] or 1
local maxCount = args[ 2 ] or minCount
self:setArguments( { min = minCount, max = maxCount } )
return e + 1
else
self:setErrorInfo( '"for" decorator needs integer arguments' )
end
self.decorateState = 'decorating'
self.currentDecorationNode = self.currentNode
return e + 1
else
return pos
end
end
function ParseContextProto:parseDecoratorSingleFloat( content, pos, type, symbol )
local s, e, match = string.find( content, '^'..symbol..'%s*', pos )
if not s then return pos end
if self:set( type, type ) then
local pos1 = e + 1
local s, e, match = string.find( content, '%(%s*(.*)s*%)%s*', pos1 )
local num = s and tonumber( match )
if num then
self:setArguments( { value = num } )
return e + 1
else
self:setErrorInfo( string.format( '"%s" decorator needs a number argument', type ) )
end
self.decorateState = 'decorating'
self.currentDecorationNode = self.currentNode
return e + 1
else
return pos
end
end
function ParseContextProto:parse_condition ( content, pos )
return self:parseCommon( content, pos, 'condition', '?' )
end
function ParseContextProto:parse_condition_not ( content, pos )
return self:parseCommon( content, pos, 'condition_not', '!' )
end
function ParseContextProto:parse_action ( content, pos )
return self:parseCommonWithArguments( content, pos, 'action', '@' )
end
function ParseContextProto:parse_msg ( content, pos )
return self:parseCommonWithArguments( content, pos, 'msg', '$' )
end
function ParseContextProto:parse_log ( content, pos )
return self:parseLineCommon( content, pos, 'log', '##' )
end
function ParseContextProto:parse_priority ( content, pos )
return self:parseCommon( content, pos, 'priority', '+' )
end
function ParseContextProto:parse_sequence ( content, pos )
return self:parseCommon( content, pos, 'sequence', '>' )
end
function ParseContextProto:parse_random ( content, pos )
return self:parseCommon( content, pos, 'random', '~' )
end
function ParseContextProto:parse_shuffled ( content, pos )
return self:parseCommon( content, pos, 'shuffled', '~>' )
end
function ParseContextProto:parse_concurrent_and ( content, pos )
return self:parseCommon( content, pos, 'concurrent_and', '|&' )
end
function ParseContextProto:parse_concurrent_or ( content, pos )
return self:parseCommon( content, pos, 'concurrent_or', '||' )
end
function ParseContextProto:parse_concurrent_either ( content, pos )
return self:parseCommon( content, pos, 'concurrent_either', '|~' )
end
function ParseContextProto:parse_decorator_not ( content, pos )
return self:parseDecorator( content, pos, 'decorator_not', ':not' )
end
function ParseContextProto:parse_decorator_ok ( content, pos )
return self:parseDecorator( content, pos, 'decorator_ok', ':ok' )
end
function ParseContextProto:parse_decorator_ignore ( content, pos )
return self:parseDecorator( content, pos, 'decorator_ignore', ':pass' )
end
function ParseContextProto:parse_decorator_fail ( content, pos )
return self:parseDecorator( content, pos, 'decorator_fail', ':fail' )
end
function ParseContextProto:parse_decorator_for ( content, pos )
return self:parseDecoratorFor( content, pos, 'decorator_for', ':for' )
end
function ParseContextProto:parse_decorator_repeat ( content, pos )
return self:parseDecorator( content, pos, 'decorator_repeat', ':repeat' )
end
function ParseContextProto:parse_decorator_while ( content, pos )
return self:parseDecorator( content, pos, 'decorator_while', ':while' )
end
function ParseContextProto:parse_decorator_forever ( content, pos )
return self:parseDecorator( content, pos, 'decorator_forever', ':forever' )
end
function ParseContextProto:parse_decorator_weight ( content, pos )
return self:parseDecoratorSingleFloat( content, pos, 'decorator_weight', ':weight' )
end
function ParseContextProto:parse_decorator_prob ( content, pos )
return self:parseDecoratorSingleFloat( content, pos, 'decorator_prob', ':prob' )
end
function ParseContextProto:parse_commented ( content, pos )
local s, e, match = string.find( content, '^//.*', pos )
if s then
self.currentNode.commented = true
return e + 1
end
return pos
end
function ParseContextProto:parse_spaces ( content, pos )
local s, e, match = string.find( content, '^%s*', pos )
if s then return e + 1 end
return pos
end
function ParseContextProto:parseLine( lineNo, l )
local i = calcIndent( l )
self:matchIndent( i )
if self.decorateState == 'decorating' then
if self.currentParent ~= self.currentDecorationNode then
print( 'decorator node must have ONE sub node')
local info = string.format( 'syntax error @ %d:%d', lineNo, i )
print( info )
error( 'fail parsing' )
end
end
self.currentLineHead = false
self.decorateState = false
local pos = i + 1
local trailComment = l:find( '//' )
if trailComment then
l = l:sub( 1, trailComment - 1 )
end
pos = self:parse_action( l, pos )
local length = #l
while true do
if pos > length then break end
local pos0 = pos
pos = self:parse_shuffled( l, pos )
pos = self:parse_concurrent_and( l, pos )
pos = self:parse_concurrent_or( l, pos )
pos = self:parse_concurrent_either( l, pos )
pos = self:parse_condition( l, pos )
pos = self:parse_condition_not( l, pos )
pos = self:parse_action( l, pos )
pos = self:parse_msg( l, pos )
pos = self:parse_log( l, pos )
pos = self:parse_priority( l, pos )
pos = self:parse_sequence( l, pos )
pos = self:parse_random( l, pos )
pos = self:parse_decorator_not( l, pos )
pos = self:parse_decorator_ok( l, pos )
pos = self:parse_decorator_fail( l, pos )
pos = self:parse_decorator_ignore( l, pos )
pos = self:parse_decorator_forever( l, pos )
pos = self:parse_decorator_for( l, pos )
pos = self:parse_decorator_weight( l, pos )
pos = self:parse_decorator_prob( l, pos )
pos = self:parse_decorator_while( l, pos )
pos = self:parse_decorator_repeat( l, pos )
pos = self:parse_commented( l, pos )
pos = self:parse_spaces( l, pos )
if pos0 == pos then
if self.errorInfo then
print( self.errorInfo )
end
local info = string.format( 'syntax error @ %d:%d', lineNo, pos )
print( info )
error( 'fail parsing') end
end
-- if self.decorateState == 'decorating' then
-- print( 'decorator node must have ONE sub node')
-- local info = string.format( 'syntax error @ %d:%d', lineNo, pos )
-- print( info )
-- error( 'fail parsing')
-- end
return true
end
function ParseContextProto:parseSource( src )
self:init()
local lineNo = 0
for line in string.gsplit( src, '\n', true ) do
lineNo = lineNo + 1
self.currentLineNo = lineNo
if line:trim() ~= '' then
self:parseLine( lineNo, line )
end
end
-- printBTScriptNode( self.rootNode )
return self.rootNode
-- for i, node in ipairs( self.rootNode.children ) do
-- if node.value == 'root' then
-- return node
-- end
-- end
-- return false
end
--------------------------------------------------------------------
local function stripNode( n )
local newChildren = {}
for i, child in ipairs( n.children ) do
if not ( child.commented or ( not child.type ) ) then
table.insert( newChildren, child )
stripNode( child )
end
end
if #newChildren == 0 then
n.children = nil
else
n.children = newChildren
end
n.parent = nil
n.indent = nil
n.lineEnd = nil
return n
end
function loadBTScript( src, name )
local context = setmetatable( {}, ParseContextMT )
local outputNode = try( function() return context:parseSource( src ) end )
if not outputNode then
_error( 'failed parsing behaviour tree or no root node specified', name or '<unknown>')
return false
end
outputNode = stripNode( outputNode )
local tree = BehaviorTree()
tree:load( outputNode )
return tree
end
function loadBTScriptFromFile( path )
local f = io.open( path, 'r' )
if f then
local src = f:read( '*a' )
return loadBTScript( src, path )
end
return false
end
function parseBTScriptFile( path )
local f = io.open( path, 'r' )
if f then
local src = f:read( '*a' )
local context = setmetatable( {}, ParseContextMT )
local outputNode = try( function() return context:parseSource( src ) end )
if not outputNode then
_error( 'failed parsing behaviour tree or no root node specified', path or '<unknown>')
return false
else
printBTScriptNode( outputNode )
end
end
return false
end
local function BTScriptLoader( node )
local path = node:getObjectFile('def')
return loadBTScriptFromFile( path ), false --no cache( for debugging )
end
--------------------------------------------------------------------
registerAssetLoader ( 'bt_script', BTScriptLoader )
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.