repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
umbrellaTG/sphero | plugins/invite.lua | 393 | 1225 | do
local function callbackres(extra, success, result) -- Callback for res_user in line 27
local user = 'user#id'..result.id
local chat = 'chat#id'..extra.chatid
if is_banned(result.id, extra.chatid) then -- Ignore bans
send_large_msg(chat, 'User is banned.')
elseif is_gbanned(result.id) then -- Ignore globall bans
send_large_msg(chat, 'User is globaly banned.')
else
chat_add_user(chat, user, ok_cb, false) -- Add user on chat
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then
return 'Group is private.'
end
end
if msg.to.type ~= 'chat' then
return
end
if not is_momod(msg) then
return
end
--if not is_admin(msg) then -- For admins only !
--return 'Only admins can invite.'
--end
local cbres_extra = {chatid = msg.to.id}
local username = matches[1]
local username = username:gsub("@","")
res_user(username, callbackres, cbres_extra)
end
return {
patterns = {
"^[!/]invite (.*)$"
},
run = run
}
end
| gpl-2.0 |
kitala1/darkstar | scripts/commands/takegil.lua | 26 | 1171 | ---------------------------------------------------------------------------------------------------
-- func: @takegil <amount> <player>
-- desc: Removes the amount of gil from the given player.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "is"
};
function onTrigger(player, amount, target)
if (amount == nil) then
player:PrintToPlayer("You must enter a valid amount.");
player:PrintToPlayer( "@takegil <amount> <player>" );
return;
end
if (target == nil) then
player:delGil(amount);
player:PrintToPlayer( string.format( "Removed %i gil from self. ", amount ) );
else
local targ = GetPlayerByName(target);
if (targ ~= nil) then
targ:delGil(amount);
player:PrintToPlayer( string.format( "Removed %i gil from player '%s' ", amount, target ) )
else
player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) );
player:PrintToPlayer( "@takegil <amount> <player>" );
end
end
end; | gpl-3.0 |
kaustavha/rackspace-monitoring-agent | check/raxxen.lua | 3 | 6764 | --[[
Copyright 2015 Rackspace
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 SubProcCheck = require('./base').SubProcCheck
local CheckResult = require('./base').CheckResult
local hostname = require('../hostname')
local Emitter = require('core').Emitter
local bind = require('utils').bind
local async = require('async')
local fs = require('fs')
local spawn = require('childprocess').spawn
local LineEmitter = require('line-emitter').LineEmitter
local misc = require('virgo/util/misc')
local CONFIG_FILE = '/opt/rackspace/host.conf'
local OVS_PID = '/var/run/openvswitch/ovs-vswitchd.pid'
local function parseIni(filename)
local t = { DEFAULT = {} }
local section = 'DEFAULT'
local data, err = fs.readFileSync(filename)
if err then return nil, err end
for line in data:gmatch("([^\n]*)\n") do
local s = line:match("^%[([^%]]+)%]$")
if s then
section = s
t[section] = t[section] or {}
end
local key, value = line:match("^(.+)%s-=%s-(.+)$")
if key and value then
if tonumber(value) then value = tonumber(value) end
if value == "true" then value = true end
if value == "false" then value = false end
t[section][key] = value
end
end
return t
end
-- **************************************************************************
local Deputy = Emitter:extend()
function Deputy:initialize()
self.le = LineEmitter:new()
self.le:on('data', function(line) self:emit('line', line) end)
end
function Deputy:run(cmd, args)
local onError, onStdout, onStdoutEnd, onExit, onDone
local callbackCount = 2
local child = spawn(cmd, args)
function onDone()
if callbackCount ~= 0 then return end
self:emit('done')
end
function onError(err)
self:emit('error', err)
end
function onExit()
callbackCount = callbackCount - 1
onDone()
end
function onStdout(chunk)
self.le:write(chunk)
end
function onStdoutEnd()
self.le:write()
callbackCount = callbackCount - 1
onDone()
end
child.stdout:on('data', onStdout)
child.stdout:on('end', onStdoutEnd)
child:on('error', onError)
child:on('exit', onExit)
end
-- **************************************************************************
local RaxxenCheck = SubProcCheck:extend()
function RaxxenCheck:initialize(params)
SubProcCheck.initialize(self, params)
end
function RaxxenCheck:getType()
return 'agent.raxxen'
end
function RaxxenCheck:_collectInstanceCount(checkResult, prefix, callback)
local count = 0
local d = Deputy:new()
d:run('/usr/sbin/xl', { 'list' })
d:on('line', function(line)
if line:find('instance') then count = count + 1 end
end)
d:on('done', function()
checkResult:addMetric(prefix .. 'instance_count', nil, 'uint64', count)
callback()
end)
d:on('error', function()
checkResult:addMetric(prefix .. 'instance_count', nil, 'uint64', 0)
callback()
end)
end
function RaxxenCheck:_collectOvsCPUUsage(checkResult, prefix, callback)
local usage = 0
local pid, err = fs.readFileSync(OVS_PID)
if err then return callback(err) end
local function onLine(line)
line = misc.trim(line)
if line:find('^' .. pid) then
line = misc.split(line)
usage = tonumber(line[9])
end
end
local d = Deputy:new()
d:run('top', { '-bn1', '-p', misc.trim(pid) })
d:on('line', onLine)
d:on('done', function()
checkResult:addMetric(prefix .. 'ovs_cpu', nil, 'double', usage)
callback()
end)
d:on('error', function()
checkResult:addMetric(prefix .. 'ovs_cpu', nil, 'double', 0)
callback()
end)
end
function RaxxenCheck:_collectDataPathStats(checkResult, prefix, callback)
local datapaths = {}
local current_datapath = ''
local function onLine(line)
if line:byte(1) ~= 0x09 then
current_datapath = misc.trim(line):gsub(":", "")
datapaths[current_datapath] = {}
else
line = misc.trim(line)
local key, value = line:match("([^:]+):(.+)")
if key == 'lookups' or key == 'flows' or key == 'masks' then
value = misc.trim(value)
if key == 'flows' then
datapaths[current_datapath][key] = value
else
local t = {}
for _, v in pairs(misc.split(value)) do
local kv, vv = v:match("([^:]+):(.+)")
t[kv] = vv
end
datapaths[current_datapath][key] = t
end
end
end
end
local function onDone()
local path = datapaths['system@ovs-system']
if path then
pcall(function()
checkResult:addMetric(prefix .. 'ovs_datapath.flow_count', nil, 'uint64', path.flows)
checkResult:addMetric(prefix .. 'ovs_datapath.hit', nil, 'uint64', path.lookups.hit)
checkResult:addMetric(prefix .. 'ovs_datapath.missed', nil, 'uint64', path.lookups.missed)
checkResult:addMetric(prefix .. 'ovs_datapath.lost', nil, 'uint64', path.lookups.lost)
checkResult:addMetric(prefix .. 'ovs_datapath_masks.hit', nil, 'uint64', path.masks.hit)
checkResult:addMetric(prefix .. 'ovs_datapath_masks.total', nil, 'uint64', path.masks.total)
checkResult:addMetric(prefix .. 'ovs_datapath_masks.hit_per_pkt', nil, 'uint64', path.masks['hit/pkt'])
end)
end
callback()
end
local d = Deputy:new()
d:run('ovs-dpctl', { 'show' })
d:on('line', onLine)
d:on('done', onDone)
d:on('error', callback)
end
function RaxxenCheck:_runCheckInChild(callback)
local checkResult = CheckResult:new(self, {})
local config, err = parseIni(CONFIG_FILE)
if err then
checkResult:setError(tostring(err))
return callback(checkResult)
end
local region = config['DEFAULT']['ENV_NAME']
local cell = config['DEFAULT']['cell']
local prefix = ''
if region and cell then
prefix = region .. '.' .. cell .. '.' .. hostname() .. '.'
prefix = prefix:gsub('-', '_')
end
async.series({
-- Gather Instance Count
bind(self._collectInstanceCount, self, checkResult, prefix),
-- Gather OVS CPU Usage
bind(self._collectOvsCPUUsage, self, checkResult, prefix),
-- Gather DataPath Stats
bind(self._collectDataPathStats, self, checkResult, prefix),
}, function(err)
if err then
checkResult:setError(tostring(err))
end
callback(checkResult)
end)
end
exports.RaxxenCheck = RaxxenCheck
| apache-2.0 |
kitala1/darkstar | scripts/zones/Newton_Movalpolos/npcs/Mining_Point.lua | 29 | 1108 | -----------------------------------
-- Area: Newton Movalpolos
-- NPC: Mining Point
-----------------------------------
package.loaded["scripts/zones/Newton_Movalpolos/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/mining");
require("scripts/zones/Newton_Movalpolos/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startMining(player,player:getZoneID(),npc,trade,0x000A);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(MINING_IS_POSSIBLE_HERE,605);
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 |
kitala1/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Sharin-Garin.lua | 12 | 1896 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sharin-Garin
-- Type: Adventurer's Assistant
-- @pos 122.658 -1.315 33.001 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/besieged");
require("scripts/globals/keyitems");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local runicpass = 0;
if (player:hasKeyItem(RUNIC_PORTAL_USE_PERMIT)) then
runicpass = 1;
end
local cost = 200 -- 200 IS to get a permit
if(getMercenaryRank(player) == 11) then
captain = 1;
else
captain = 0;
end;
local merc = 2 -- Probably could be done, but not really important atm
player:startEvent(0x008C,0,merc,runicpass,player:getCurrency("imperial_standing"),getAstralCandescence(),cost,captain);
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 == 0x008C and option == 1) then
player:addKeyItem(RUNIC_PORTAL_USE_PERMIT);
player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT);
player:delCurrency("imperial_standing", 200);
elseif(csid == 0x008C and option == 2) then
player:addKeyItem(RUNIC_PORTAL_USE_PERMIT);
player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT);
end
end; | gpl-3.0 |
paulosalvatore/maruim_server | data/lib/itens.lua | 1 | 10127 | valorItens = {
[1678] = {20, 0},
[1679] = {20, 0},
[1680] = {20, 0},
[1681] = {20, 0},
[1682] = {20, 0},
[1683] = {20, 0},
[1684] = {20, 0},
[1685] = {30, 0},
[1686] = {25, 0},
[1687] = {25, 0},
[1688] = {25, 0},
[1689] = {25, 0},
[1690] = {25, 0},
[1691] = {25, 0},
[1692] = {25, 0},
[1693] = {25, 0},
[1738] = {10, 0},
[1739] = {10, 0},
[1740] = {10, 0},
[1746] = {1000, 0},
[1845] = {40, 0},
[1848] = {40, 0},
[1851] = {40, 0},
[1852] = {50, 0},
[1853] = {50, 0},
[1854] = {50, 0},
[1857] = {25, 0},
[1860] = {25, 0},
[1863] = {25, 0},
[1866] = {25, 0},
[1869] = {25, 0},
[1872] = {25, 0},
[1880] = {25, 0},
[1881] = {40, 0},
[1976] = {0, 100},
[1988] = {20, 0},
[2006] = {0, 5},
[2008] = {3, 0},
[2023] = {4, 0},
[2033] = {0, 250},
[2047] = {2, 0},
[2050] = {5, 0},
[2093] = {40, 0},
[2099] = {40, 0},
[2100] = {5, 0},
[2102] = {6, 0},
[2103] = {5, 0},
[2104] = {5, 0},
[2107] = {300, 0},
[2120] = {20, 0},
[2121] = {990, 100},
[2124] = {0, 250},
[2129] = {0, 100},
[2134] = {0, 150},
[2143] = {320, 160},
[2144] = {560, 280},
[2145] = {600, 300},
[2146] = {500, 250},
[2147] = {500, 250},
[2149] = {500, 250},
[2150] = {500, 250},
[2151] = {0, 320},
[2153] = {0, 10000},
[2154] = {0, 1000},
[2155] = {0, 5000},
[2156] = {0, 1000},
[2158] = {0, 5000},
[2162] = {120, 35},
[2165] = {5000, 200},
[2167] = {2000, 100},
[2168] = {900, 50},
[2169] = {2000, 100},
[2170] = {100, 45},
[2171] = {0, 2500},
[2172] = {100, 45},
[2175] = {150, 0},
[2177] = {0, 85},
[2178] = {0, 170},
[2181] = {10000, 0},
[2182] = {500, 0},
[2183] = {15000, 0},
[2185] = {5000, 0},
[2186] = {1000, 0},
[2187] = {15000, 3000},
[2188] = {5000, 0},
[2189] = {10000, 0},
[2190] = {500, 0},
[2191] = {1000, 0},
[2194] = {0, 50},
[2197] = {5000, 500},
[2213] = {2000, 100},
[2214] = {1800, 100},
[2229] = {0, 6},
[2230] = {0, 18},
[2235] = {0, 40},
[2245] = {0, 8},
[2261] = {45, 0},
[2263] = {300, 0},
[2265] = {95, 0},
[2268] = {350, 0},
[2273] = {175, 0},
[2278] = {700, 0},
[2287] = {40, 0},
[2290] = {80, 0},
[2291] = {210, 0},
[2293] = {350, 0},
[2304] = {180, 0},
[2310] = {80, 0},
[2311] = {120, 0},
[2313] = {250, 0},
[2316] = {375, 0},
[2372] = {0, 120},
[2376] = {65, 25},
[2377] = {900, 450},
[2378] = {535, 110},
[2379] = {5, 2},
[2380] = {7, 5},
[2381] = {0, 400},
[2383] = {1300, 400},
[2384] = {15, 5},
[2385] = {26, 12},
[2386] = {20, 10},
[2387] = {0, 260},
[2388] = {65, 25},
[2389] = {9, 3},
[2391] = {10000, 970},
[2392] = {0, 4000},
[2394] = {630, 150},
[2395] = {170, 118},
[2396] = {6000, 1000},
[2397] = {230, 105},
[2398] = {65, 30},
[2399] = {42, 0},
[2406] = {22, 10},
[2409] = {370, 300},
[2410] = {23, 4},
[2411] = {0, 50},
[2412] = {190, 80},
[2413] = {0, 500},
[2417] = {550, 120},
[2422] = {230, 105},
[2423] = {720, 170},
[2425] = {2500, 500},
[2428] = {0, 350},
[2429] = {590, 185},
[2434] = {2500, 1700},
[2436] = {0, 6000},
[2437] = {50, 25},
[2439] = {500, 100},
[2441] = {200, 105},
[2442] = {0, 90},
[2448] = {15, 5},
[2449] = {25, 12},
[2450] = {50, 20},
[2455] = {500, 160},
[2456] = {350, 130},
[2457] = {580, 293},
[2458] = {44, 17},
[2459] = {290, 150},
[2460] = {90, 30},
[2461] = {10, 4},
[2463] = {900, 400},
[2464] = {150, 60},
[2465] = {450, 150},
[2467] = {22, 12},
[2468] = {40, 15},
[2473] = {180, 60},
[2476] = {0, 5000},
[2477] = {0, 5000},
[2478] = {195, 49},
[2479] = {0, 500},
[2480] = {230, 68},
[2481] = {260, 100},
[2482] = {50, 20},
[2483] = {230, 75},
[2484] = {70, 25},
[2492] = {0, 40000},
[2498] = {0, 30000},
[2508] = {230, 110},
[2509] = {230, 80},
[2510] = {110, 45},
[2511] = {60, 25},
[2512] = {15, 5},
[2513] = {330, 95},
[2515] = {0, 2000},
[2516] = {0, 4000},
[2525] = {450, 100},
[2526] = {50, 16},
[2528] = {0, 8000},
[2530] = {150, 60},
[2531] = {260, 85},
[2532] = {5000, 900},
[2535] = {0, 5000},
[2541] = {180, 80},
[2543] = {4, 0},
[2544] = {3, 0},
[2545] = {3, 0},
[2546] = {15, 0},
[2547] = {7, 0},
[2553] = {10, 0},
[2554] = {20, 0},
[2559] = {6, 5},
[2580] = {100, 0},
[2595] = {15, 0},
[2597] = {8, 0},
[2599] = {1, 0},
[2642] = {4, 2},
[2643] = {4, 2},
[2647] = {350, 115},
[2648] = {70, 23},
[2649] = {10, 9},
[2656] = {0, 10000},
[2657] = {0, 50},
[2661] = {15, 5},
[2666] = {5, 0},
[2667] = {3, 0},
[2669] = {0, 100},
[2671] = {8, 0},
[2673] = {4, 0},
[2674] = {3, 0},
[2679] = {1, 0},
[2681] = {3, 0},
[2689] = {3, 0},
[2696] = {5, 0},
[2787] = {10, 0},
[2796] = {0, 100},
[2799] = {28, 20},
[2800] = {21, 15},
[2805] = {0, 25},
[2813] = {0, 5},
[2817] = {0, 4},
[3086] = {0, 12},
[3119] = {0, 5},
[3901] = {40, 0},
[3902] = {40, 0},
[3903] = {15, 0},
[3904] = {25, 0},
[3905] = {55, 0},
[3906] = {25, 0},
[3907] = {25, 0},
[3908] = {20, 0},
[3909] = {200, 0},
[3911] = {30, 0},
[3912] = {30, 0},
[3913] = {25, 0},
[3914] = {25, 0},
[3915] = {18, 0},
[3916] = {25, 0},
[3917] = {30, 0},
[3918] = {7, 0},
[3919] = {12, 0},
[3920] = {10, 0},
[3921] = {20, 0},
[3922] = {50, 0},
[3923] = {50, 0},
[3924] = {35, 0},
[3925] = {70, 0},
[3926] = {30, 0},
[3927] = {75, 0},
[3928] = {50, 0},
[3929] = {50, 0},
[3930] = {50, 0},
[3931] = {50, 0},
[3932] = {25, 0},
[3933] = {200, 0},
[3934] = {50, 0},
[3935] = {20, 0},
[3936] = {20, 0},
[3937] = {8, 0},
[3938] = {80, 0},
[3965] = {0, 25},
[3976] = {1, 0},
[5022] = {80, 40},
[5086] = {65, 0},
[5087] = {65, 0},
[5088] = {65, 0},
[5678] = {0, 4},
[5741] = {0, 40000},
[5877] = {0, 100},
[5878] = {0, 80},
[5879] = {0, 100},
[5880] = {0, 500},
[5882] = {0, 200},
[5895] = {0, 150},
[5896] = {0, 50},
[5897] = {0, 50},
[5899] = {0, 90},
[5901] = {0, 10},
[5902] = {0, 40},
[5920] = {0, 100},
[5928] = {50, 0},
[5948] = {0, 200},
[6114] = {90, 0},
[6115] = {90, 0},
[6131] = {0, 150},
[6372] = {80, 0},
[6373] = {70, 0},
[7158] = {0, 100},
[7159] = {0, 100},
[7363] = {5, 0},
[7364] = {5, 0},
[7378] = {15, 0},
[7383] = {0, 25000},
[7385] = {600, 150},
[7397] = {0, 3000},
[7399] = {0, 10000},
[7400] = {0, 3000},
[7402] = {0, 15000},
[7430] = {0, 3000},
[7452] = {0, 5000},
[7588] = {100, 0},
[7589] = {80, 0},
[7590] = {120, 0},
[7591] = {190, 0},
[7618] = {45, 0},
[7620] = {50, 0},
[7632] = {0, 3000},
[7633] = {0, 3000},
[7634] = {0, 5},
[7635] = {0, 5},
[7636] = {0, 5},
[7735] = {0, 299},
[7838] = {5, 0},
[7839] = {5, 0},
[7840] = {5, 0},
[7850] = {5, 0},
[7884] = {0, 11000},
[7886] = {0, 2500},
[7893] = {0, 2500},
[7897] = {0, 11000},
[7901] = {0, 2500},
[7904] = {80, 0},
[7905] = {80, 0},
[7906] = {80, 0},
[7907] = {80, 0},
[7936] = {50, 0},
[7963] = {0, 800},
[8299] = {0, 2000},
[8472] = {190, 0},
[8473] = {310, 0},
[8601] = {500, 100},
[8602] = {500, 100},
[8692] = {200, 0},
[8704] = {10, 0},
[8839] = {1, 0},
[8840] = {1, 0},
[8819] = {450, 0},
[8820] = {150, 0},
[8859] = {0, 7},
[8910] = {22000, 0},
[8911] = {7500, 0},
[8912] = {18000, 0},
[8920] = {18000, 0},
[8921] = {7500, 0},
[8922] = {22000, 0},
[8971] = {0, 50},
[9676] = {0, 45},
[9959] = {80, 0},
[10553] = {0, 375},
[10557] = {0, 50},
[10564] = {0, 80},
[10568] = {0, 25},
[10569] = {0, 60},
[10574] = {0, 55},
[10603] = {0, 20},
[10606] = {0, 4},
[10608] = {0, 60},
[10609] = {0, 10},
[11113] = {0, 100},
[11189] = {0, 22},
[11191] = {0, 12},
[11192] = {0, 35},
[11198] = {0, 80},
[11208] = {0, 30},
[11210] = {0, 50},
[11214] = {0, 5},
[11218] = {0, 12},
[11224] = {0, 150},
[11236] = {0, 15},
[11309] = {3000, 800},
[11323] = {6000, 500},
[11324] = {0, 25},
[11328] = {0, 110},
[11329] = {0, 3000},
[11337] = {0, 250},
[11373] = {0, 15},
[12402] = {0, 350},
[12414] = {0, 80},
[12419] = {0, 120},
[12382] = {0, 17},
[12399] = {0, 30},
[12400] = {0, 60},
[12413] = {0, 100},
[12423] = {0, 60},
[12430] = {500, 40},
[12435] = {0, 30},
[12437] = {0, 8},
[12440] = {0, 25},
[12441] = {0, 8},
[12443] = {0, 140},
[12444] = {0, 350},
[12445] = {0, 280},
[12447] = {0, 500},
[12471] = {0, 40},
[12495] = {0, 12},
[13159] = {0, 15},
[13529] = {100000, 0},
[13531] = {0, 5400},
[13532] = {0, 1200},
[13546] = {0, 3000},
[13757] = {0, 20},
[13838] = {0, 2000},
[13870] = {0, 150},
[14328] = {25, 0},
[14329] = {25, 0},
[15400] = {0, 4000},
[15403] = {0, 3000},
[15421] = {0, 280},
[15422] = {0, 330},
[15423] = {0, 230},
[15424] = {0, 90},
[15425] = {0, 180},
[15426] = {0, 290},
[15430] = {0, 80},
[15451] = {0, 11000},
[15452] = {0, 360},
[15453] = {0, 9000},
[15454] = {0, 9000},
[15455] = {0, 430},
[15487] = {0, 4},
[15644] = {0, 12000},
[15647] = {0, 7000},
[15649] = {6, 0},
[18436] = {12, 0},
[19390] = {2, 1},
[19738] = {0, 20},
[19743] = {0, 25},
[20102] = {0, 20},
[20103] = {0, 30},
[20104] = {0, 40},
[21427] = {0, 35},
[21428] = {0, 25},
[23722] = {12, 0},
[23723] = {7, 0}
}
categoriasItens = {
["utilidades"] = {1988, 2120, 2553, 2554, 2580, 3976},
["correio"] = {2595, 2597, 2599},
["armas_distancia_c"] = {2389, 2455, 2456, 2543, 2544, 19390},
["armas_distancia_v"] = {2389, 2455, 2456, 19390},
["comidas_basicas"] = {2666, 2667, 2671, 2674, 2689, 2696},
["frutas_basicas"] = {2673, 2674, 2679, 2681, 8839, 8840},
["moveis"] = {1678, 1679, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693, 1738, 1739, 1740, 1746, 1845, 1848, 1851, 1852, 1853, 1854, 1857, 1860, 1863, 1866, 1869, 1872, 1880, 1881, {2008, 0, 1}, {2023, 0, 1}, 2093, 2099, 2100, 2102, 2103, 2104, 2107, 3901, 3902, 3903, 3904, 3905, 3906, 3907, 3908, 3909, 3911, 3912, 3913, 3914, 3915, 3916, 3917, 3918, 3919, 3920, 3921, 3922, 3923, 3924, 3925, 3926, 3927, 3928, 3929, 3930, 3931, 3932, 3933, 3934, 3935, 3936, 3937, 3938, 5086, 5087, 5088, 5928, 6114, 6115, 6372, 6373, 7904, 7905, 7906, 7907, 8692, 9959, 14328, 14329},
["pocoes_c"] = {7588, 7589, 7590, 7591, 7618, 7620, 8472, 8473},
["pocoes_v"] = {7634, 7635, 7636},
["runas_c"] = {2261, 2263, 2265, 2268, 2273, 2278, 2287, 2290, 2291, 2293, 2304, 2310, 2311, 2313, 2316},
["runas_v"] = {2006, 7634, 7635, 7636, 7735}
}
| gpl-2.0 |
kitala1/darkstar | scripts/zones/Lower_Jeuno/npcs/Zauko.lua | 17 | 5098 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Zauko
-- Involved in Quests: Save the Clock Tower, Community Service
-- @zone 245
-- @pos -3 0 11
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
----- Save The Clock Tower Quest -----
if(trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then
a = player:getVar("saveTheClockTowerNPCz2"); -- NPC Zone2
if(a == 0 or (a ~= 256 and a ~= 288 and a ~= 320 and a ~= 384 and a ~= 768 and a ~= 352 and a ~= 896 and a ~= 416 and
a ~= 832 and a ~= 448 and a ~= 800 and a ~= 480 and a ~= 864 and a ~= 928 and a ~= 960 and a ~= 992)) then
player:startEvent(0x0032,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
local cService = player:getVar("cService");
questServerVar = GetServerVariable("[JEUNO]CommService");
----- Community Service Quest -----
-- The reason for all the Default Dialogue "else"s is because of all the different checks needed and to keep default dialogue
-- If they're not there then the player will keep triggering the Quest Complete (Repeat) Cutscene
-- Please leave them here unless you can find a way to fix this but the quest as it should do.
-- Quest Start --
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_AVAILABLE and player:getFameLevel(JEUNO) >=1) then
if (hour >= 18 and hour < 21) then
if(questServerVar == 0) then
player:startEvent(0x0074,questServerVar+1); -- Quest Start Dialogue (NOTE: The Cutscene says somebody else is working on it but it still adds the quest)
else
player:startEvent(0x0074,questServerVar);
end
else
player:startEvent(0x0076); -- Default Dialogue
end
-- Task Failed --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if(cService >= 1 and cService < 12 == true) then -- If the quest is accepted but all lamps are NOT lit
if (hour >= 18 and hour < 23) then
player:startEvent(0x0077); -- Task Failed Dialogue
else
player:startEvent(0x0076);
end
-- Quest Complete --
else
player:startEvent(0x0075); -- Quest Complete Dialogue
end
-- Repeat Quest --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 18) then
if (hour >= 18 and hour < 21) then
player:startEvent(0x0074,1) -- Quest Start (Repeat)
else
player:startEvent(0x0076); -- Default Dialogue
end
-- Repeat Quest Task Failed --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (cService >= 14 and cService < 24 == true) then
if (hour >= 18 and hour < 23) then -- If Quest Repeat is accepted but lamps are not lit
player:startEvent(0x0077); -- Task Failed Dialogue
end
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 0) then
player:startEvent(0x0076);
-- Repeat Quest Complete --
else
player:startEvent(0x0071); -- Quest Complete (Repeat)
end
else
player:startEvent(0x0076);
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);
-- ClockTower Quest --
if(csid == 0x0032) then
player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1);
player:setVar("saveTheClockTowerNPCz2",player:getVar("saveTheClockTowerNPCz2") + 256);
---- Community Service Quest ----
elseif(csid == 0x0074 and option == 0) then -- Quest Start
if(questServerVar == 0) then
player:addQuest(JEUNO,COMMUNITY_SERVICE);
SetServerVariable("[JEUNO]CommService",1);
end
elseif(csid == 0x0075) then -- Quest Finish
player:completeQuest(JEUNO,COMMUNITY_SERVICE);
player:addFame(JEUNO,JEUNO_FAME*30);
player:setVar("cService",13)
player:addTitle(TORCHBEARER);
elseif(csid == 0x0071) then -- Quest Finish (Repeat)
player:addKeyItem(LAMP_LIGHTERS_MEMBERSHIP_CARD); -- Lamp Lighter's Membership Card
player:messageSpecial(KEYITEM_OBTAINED,LAMP_LIGHTERS_MEMBERSHIP_CARD);
player:addFame(JEUNO, JEUNO_FAME*15);
player:setVar("cService",0);
end
end; | gpl-3.0 |
hanxi/cocos2d-x-v3.1 | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Tween.lua | 6 | 1308 |
--------------------------------
-- @module Tween
-- @extend ProcessBase
--------------------------------
-- @function [parent=#Tween] getAnimation
-- @param self
-- @return ArmatureAnimation#ArmatureAnimation ret (return value: ccs.ArmatureAnimation)
--------------------------------
-- @function [parent=#Tween] gotoAndPause
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#Tween] play
-- @param self
-- @param #ccs.MovementBoneData movementbonedata
-- @param #int int
-- @param #int int
-- @param #int int
-- @param #int int
--------------------------------
-- @function [parent=#Tween] gotoAndPlay
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#Tween] init
-- @param self
-- @param #ccs.Bone bone
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#Tween] setAnimation
-- @param self
-- @param #ccs.ArmatureAnimation armatureanimation
--------------------------------
-- @function [parent=#Tween] create
-- @param self
-- @param #ccs.Bone bone
-- @return Tween#Tween ret (return value: ccs.Tween)
--------------------------------
-- @function [parent=#Tween] Tween
-- @param self
return nil
| mit |
apletnev/koreader | spec/unit/translator_spec.lua | 3 | 1341 | local dutch_wikipedia_text = "Wikipedia is een meertalige encyclopedie, waarvan de inhoud vrij beschikbaar is. Iedereen kan hier kennis toevoegen!"
local Translator
describe("Translator module", function()
setup(function()
require("commonrequire")
Translator = require("ui/translator")
end)
it("should return server", function()
assert.is.same("http://translate.google.cn", Translator:getTransServer())
G_reader_settings:saveSetting("trans_server", "http://translate.google.nl")
G_reader_settings:flush()
assert.is.same("http://translate.google.nl", Translator:getTransServer())
G_reader_settings:delSetting("trans_server")
G_reader_settings:flush()
end)
it("should return translation #notest #nocov", function()
local translation_result = Translator:loadPage("en", "nl", dutch_wikipedia_text)
assert.is.truthy(translation_result)
-- while some minor variation in the translation is possible it should
-- be between about 100 and 130 characters
assert.is_true(#translation_result > 50 and #translation_result < 200)
end)
it("should autodetect language #notest #nocov", function()
local detect_result = Translator:detect(dutch_wikipedia_text)
assert.is.same("nl", detect_result)
end)
end)
| agpl-3.0 |
kitala1/darkstar | scripts/globals/spells/advancing_march.lua | 13 | 1472 | -----------------------------------------
-- Spell: Advancing March
-- Gives party members Haste
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 35;
if (sLvl+iLvl > 200) then
power = power + math.floor((sLvl+iLvl-200) / 7);
end
if(power >= 64) then
power = 64;
end
local iBoost = caster:getMod(MOD_MARCH_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost*16;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MARCH,power,0,duration,caster:getID(), 0, 1)) then
spell:setMsg(75);
end
return EFFECT_MARCH;
end; | gpl-3.0 |
kitala1/darkstar | scripts/zones/Bastok_Markets/npcs/Arawn.lua | 34 | 2642 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Arawn
-- Starts & Finishes Quest: Stamp Hunt
-- @pos -121.492 -4.000 -123.923 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local StampHunt = player:getQuestStatus(BASTOK,STAMP_HUNT);
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,11) == false) then
player:startEvent(0x01ad);
elseif (StampHunt == QUEST_AVAILABLE) then
player:startEvent(0x00e1);
elseif (StampHunt == QUEST_ACCEPTED and player:isMaskFull(player:getVar("StampHunt_Mask"),7) == true) then
player:startEvent(0x00e2);
else
player:startEvent(0x0072);
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 == 0x00e1 and option == 0) then
player:addQuest(BASTOK,STAMP_HUNT);
player:addKeyItem(STAMP_SHEET);
player:messageSpecial(KEYITEM_OBTAINED,STAMP_SHEET);
elseif (csid == 0x00e2) then
if (player:getFreeSlotsCount(0) >= 1) then
player:addTitle(STAMPEDER);
player:addItem(13081);
player:messageSpecial(ITEM_OBTAINED,13081); -- Leather Gorget
player:delKeyItem(STAMP_SHEET);
player:setVar("StampHunt_Mask",0);
player:addFame(BASTOK,BAS_FAME*50);
player:completeQuest(BASTOK,STAMP_HUNT);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 13081);
end
elseif (csid == 0x01ad) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",11,true);
end
end; | gpl-3.0 |
kitala1/darkstar | scripts/zones/Lower_Jeuno/npcs/Taza.lua | 36 | 1722 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Taza
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
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)
player:showText(npc,TAZA_SHOP_DIALOG);
stock = {0x1311,10304, -- Scroll of Sleepga
0x1232,26244, -- Scroll of Shell III
0x127f,19200, -- Scroll of Protectra III
0x1283,14080, -- Scroll of Shellra II
0x1284,26244, -- Scroll of Shellra III
0x124d,15120, -- Scroll of Barpetrify
0x124e,9600, -- Scroll of Barvirus
0x125b,15120, -- Scroll of Barpetra
0x125c,9600, -- Scroll of Barvira
0x1303,18720, -- Scroll of Sleep II
0x12a1,19932, -- Scroll of Stone III
0x12ab,22682, -- Scroll of Water III
0x129c,27744, -- Scroll of Aero III
0x1292,33306, -- Scroll of Fire III
0x1297,39368, -- Scroll of Blizzard III
0x12a6,45930} -- Scroll of Thunder III
showShop(player, STATIC, 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 |
kitala1/darkstar | scripts/globals/weaponskills/fell_cleave.lua | 30 | 1392 | -----------------------------------
-- Fell Cleave
-- Great Axe weapon skill
-- Skill Level: 300
-- Delivers an area attack. Radius varies with TP.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Element: None
-- Modifiers: STR: 60%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 2.0; params.ftp200 = 2.0; params.ftp300 = 2.0;
params.str_wsc = 0.6; 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.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
hanxi/cocos2d-x-v3.1 | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/AtlasNode.lua | 3 | 2256 |
--------------------------------
-- @module AtlasNode
-- @extend Node,TextureProtocol
--------------------------------
-- @function [parent=#AtlasNode] updateAtlasValues
-- @param self
--------------------------------
-- @function [parent=#AtlasNode] getTexture
-- @param self
-- @return Texture2D#Texture2D ret (return value: cc.Texture2D)
--------------------------------
-- @function [parent=#AtlasNode] setTextureAtlas
-- @param self
-- @param #cc.TextureAtlas textureatlas
--------------------------------
-- @function [parent=#AtlasNode] getTextureAtlas
-- @param self
-- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas)
--------------------------------
-- @function [parent=#AtlasNode] getQuadsToDraw
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- @function [parent=#AtlasNode] setTexture
-- @param self
-- @param #cc.Texture2D texture2d
--------------------------------
-- @function [parent=#AtlasNode] setQuadsToDraw
-- @param self
-- @param #long long
--------------------------------
-- @function [parent=#AtlasNode] create
-- @param self
-- @param #string str
-- @param #int int
-- @param #int int
-- @param #int int
-- @return AtlasNode#AtlasNode ret (return value: cc.AtlasNode)
--------------------------------
-- @function [parent=#AtlasNode] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #cc.Mat4 mat4
-- @param #bool bool
--------------------------------
-- @function [parent=#AtlasNode] isOpacityModifyRGB
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#AtlasNode] setColor
-- @param self
-- @param #color3b_table color3b
--------------------------------
-- @function [parent=#AtlasNode] getColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)
--------------------------------
-- @function [parent=#AtlasNode] setOpacityModifyRGB
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#AtlasNode] setOpacity
-- @param self
-- @param #unsigned char char
return nil
| mit |
crabman77/minetest-minetestforfun-server | mods/homedecor_modpack/building_blocks/init.lua | 7 | 16634 | minetest.register_node("building_blocks:Adobe", {
tiles = {"building_blocks_Adobe.png"},
description = "Adobe",
is_ground_content = true,
groups = {crumbly=3},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("building_blocks:Roofing", {
tiles = {"building_blocks_Roofing.png"},
is_ground_content = true,
description = "Roof block",
groups = {snappy=3},
})
minetest.register_craft({
output = 'building_blocks:terrycloth_towel 2',
recipe = {
{"farming:string", "farming:string", "farming:string"},
}
})
minetest.register_craft({
output = 'building_blocks:Tarmac_spread 4',
recipe = {
{"group:tar_block", "group:tar_block"},
}
})
minetest.register_craft({
output = 'building_blocks:gravel_spread 4',
recipe = {
{"default:gravel", "default:gravel", "default:gravel"},
}
})
minetest.register_craft({
output = 'building_blocks:brobble_spread 4',
recipe = {
{"default:brick", "default:cobble", "default:brick"},
}
})
minetest.register_craft({
output = 'building_blocks:Fireplace 1',
recipe = {
{"default:steel_ingot", "building_blocks:sticks", "default:steel_ingot"},
}
})
minetest.register_craft({
output = 'building_blocks:Adobe 3',
recipe = {
{"default:sand"},
{"default:clay"},
{"group:stick"},
}
})
minetest.register_craft({
output = 'building_blocks:Roofing 10',
recipe = {
{"building_blocks:Adobe", "building_blocks:Adobe"},
{"building_blocks:Adobe", "building_blocks:Adobe"},
}
})
minetest.register_craft({
output = 'building_blocks:BWtile 10',
recipe = {
{"group:marble", "group:tar_block"},
{"group:tar_block", "group:marble"},
}
})
minetest.register_craft({
output = 'building_blocks:grate 1',
recipe = {
{"default:steel_ingot", "default:steel_ingot"},
{"default:glass", "default:glass"},
}
})
minetest.register_craft({
output = 'building_blocks:woodglass 1',
recipe = {
{"default:wood"},
{"default:glass"},
}
})
minetest.register_craft({
output = 'building_blocks:hardwood 2',
recipe = {
{"default:wood", "default:junglewood"},
{"default:junglewood", "default:wood"},
}
})
minetest.register_craft({
output = 'building_blocks:hardwood 2',
recipe = {
{"default:junglewood", "default:wood"},
{"default:wood", "default:junglewood"},
}
})
if minetest.get_modpath("moreblocks") then
minetest.register_craft({
output = 'building_blocks:sticks 2',
recipe = {
{'group:stick', '' , 'group:stick'},
{'group:stick', 'group:stick', 'group:stick'},
{'group:stick', 'group:stick', 'group:stick'},
}
})
else
minetest.register_craft({
output = 'building_blocks:sticks',
recipe = {
{'group:stick', 'group:stick'},
{'group:stick', 'group:stick'},
}
})
end
minetest.register_craft({
output = 'building_blocks:sticks',
recipe = {
{'group:stick', '', 'group:stick'},
{'', 'group:stick', ''},
{'group:stick', '', 'group:stick'},
} -- MODIFICATION MADE FOR MFF ^
})
minetest.register_craft({
output = 'building_blocks:fakegrass 2',
recipe = {
{'default:leaves'},
{"default:dirt"},
}
})
minetest.register_craft({
output = 'building_blocks:tar_base 2',
recipe = {
{"default:coal_lump", "default:gravel"},
{"default:gravel", "default:coal_lump"}
}
})
minetest.register_craft({
output = 'building_blocks:tar_base 2',
recipe = {
{"default:gravel", "default:coal_lump"},
{"default:coal_lump", "default:gravel"}
}
})
minetest.register_craft({
type = "cooking",
output = "building_blocks:smoothglass",
recipe = "default:glass"
})
minetest.register_node("building_blocks:smoothglass", {
drawtype = "glasslike",
description = "Streak Free Glass",
tiles = {"building_blocks_sglass.png"},
inventory_image = minetest.inventorycube("building_blocks_sglass.png"),
paramtype = "light",
sunlight_propagates = true,
is_ground_content = true,
groups = {snappy=3,cracky=3,oddly_breakable_by_hand=3},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_node("building_blocks:grate", {
drawtype = "glasslike",
description = "Grate",
tiles = {"building_blocks_grate.png"},
inventory_image = minetest.inventorycube("building_blocks_grate.png"),
paramtype = "light",
sunlight_propagates = true,
is_ground_content = true,
groups = {cracky=1},
})
minetest.register_node("building_blocks:Fireplace", {
description = "Fireplace",
tiles = {
"building_blocks_cast_iron.png",
"building_blocks_cast_iron.png",
"building_blocks_cast_iron.png",
"building_blocks_cast_iron_fireplace.png"
},
paramtype = "light",
paramtype2 = "facedir",
light_source = default.LIGHT_MAX,
sunlight_propagates = true,
is_ground_content = true,
groups = {cracky=2},
})
minetest.register_node("building_blocks:woodglass", {
drawtype = "glasslike",
description = "Wood Framed Glass",
tiles = {"building_blocks_wglass.png"},
inventory_image = minetest.inventorycube("building_blocks_wglass.png"),
paramtype = "light",
sunlight_propagates = true,
is_ground_content = true,
groups = {snappy=3,cracky=3,oddly_breakable_by_hand=3},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_node("building_blocks:terrycloth_towel", {
drawtype = "raillike",
description = "Terrycloth towel",
tiles = {"building_blocks_towel.png"},
inventory_image = "building_blocks_towel_inv.png",
paramtype = "light",
walkable = false,
selection_box = {
type = "fixed",
-- but how to specify the dimensions for curved and sideways rails?
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
sunlight_propagates = true,
is_ground_content = true,
groups = {crumbly=3},
})
minetest.register_node("building_blocks:Tarmac_spread", {
drawtype = "raillike",
description = "Tarmac Spread",
tiles = {"building_blocks_tar.png"},
inventory_image = "building_blocks_tar_spread_inv.png",
paramtype = "light",
walkable = false,
selection_box = {
type = "fixed",
-- but how to specify the dimensions for curved and sideways rails?
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
sunlight_propagates = true,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_dirt_defaults(),
})
minetest.register_node("building_blocks:BWtile", {
drawtype = "raillike",
description = "Chess board tiling",
tiles = {"building_blocks_BWtile.png"},
inventory_image = "building_blocks_bwtile_inv.png",
paramtype = "light",
walkable = false,
selection_box = {
type = "fixed",
-- but how to specify the dimensions for curved and sideways rails?
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
sunlight_propagates = true,
is_ground_content = true,
groups = {crumbly=3},
})
minetest.register_node("building_blocks:brobble_spread", {
drawtype = "raillike",
description = "Brobble Spread",
tiles = {"building_blocks_brobble.png"},
inventory_image = "building_blocks_brobble_spread_inv.png",
paramtype = "light",
walkable = false,
selection_box = {
type = "fixed",
-- but how to specify the dimensions for curved and sideways rails?
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
sunlight_propagates = true,
is_ground_content = true,
groups = {crumbly=3},
})
minetest.register_node("building_blocks:gravel_spread", {
drawtype = "raillike",
description = "Gravel Spread",
tiles = {"default_gravel.png"},
inventory_image = "building_blocks_gravel_spread_inv.png",
paramtype = "light",
walkable = false,
selection_box = {
type = "fixed",
-- but how to specify the dimensions for curved and sideways rails?
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
sunlight_propagates = true,
is_ground_content = true,
groups = {crumbly=2},
sounds = default.node_sound_dirt_defaults({
footstep = {name="default_gravel_footstep", gain=0.5},
dug = {name="default_gravel_footstep", gain=1.0},
}),
})
minetest.register_node("building_blocks:hardwood", {
tiles = {"building_blocks_hardwood.png"},
is_ground_content = true,
description = "Hardwood",
groups = {choppy=1,flammable=1},
sounds = default.node_sound_wood_defaults(),
})
if minetest.get_modpath("moreblocks") then
stairsplus:register_all(
"building_blocks",
"marble",
"building_blocks:Marble",
{
description = "Marble",
tiles = {"building_blocks_marble.png"},
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
}
)
stairsplus:register_all(
"building_blocks",
"hardwood",
"building_blocks:hardwood",
{
description = "Hardwood",
tiles = {"building_blocks_hardwood.png"},
groups = {choppy=1,flammable=1},
sounds = default.node_sound_wood_defaults(),
}
)
stairsplus:register_all(
"building_blocks",
"fakegrass",
"building_blocks:fakegrass",
{
description = "Grass",
tiles = {"default_grass.png"},
groups = {crumbly=3},
sounds = default.node_sound_dirt_defaults({
footstep = {name="default_grass_footstep", gain=0.4},
}),
}
)
stairsplus:register_all(
"building_blocks",
"tar",
"building_blocks:Tar",
{
description = "Tar",
tiles = {"building_blocks_tar.png"},
groups = {crumbly=1},
sounds = default.node_sound_stone_defaults(),
}
)
stairsplus:register_all(
"building_blocks",
"grate",
"building_blocks:grate",
{
description = "Grate",
tiles = {"building_blocks_grate.png"},
groups = {cracky=1},
sounds = default.node_sound_stone_defaults(),
}
)
stairsplus:register_all(
"building_blocks",
"Adobe",
"building_blocks:Adobe",
{
description = "Adobe",
tiles = {"building_blocks_Adobe.png"},
groups = {crumbly=3},
sounds = default.node_sound_stone_defaults(),
}
)
stairsplus:register_all(
"building_blocks",
"Roofing",
"building_blocks:Roofing",
{
description = "Roofing",
tiles = {"building_blocks_Roofing.png"},
groups = {snappy=3},
sounds = default.node_sound_stone_defaults(),
}
)
else
bb_stairs = {}
-- Node will be called stairs:stair_<subname>
function bb_stairs.register_stair(subname, recipeitem, groups, images, description)
minetest.register_node("building_blocks:stair_" .. subname, {
description = description,
drawtype = "nodebox",
tiles = images,
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = true,
groups = groups,
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0, 0.5},
{-0.5, 0, 0, 0.5, 0.5, 0.5},
},
},
})
minetest.register_craft({
output = 'building_blocks:stair_' .. subname .. ' 4',
recipe = {
{recipeitem, "", ""},
{recipeitem, recipeitem, ""},
{recipeitem, recipeitem, recipeitem},
},
})
-- Flipped recipe for the silly minecrafters
minetest.register_craft({
output = 'building_blocks:stair_' .. subname .. ' 4',
recipe = {
{"", "", recipeitem},
{"", recipeitem, recipeitem},
{recipeitem, recipeitem, recipeitem},
},
})
end
-- Node will be called stairs:slab_<subname>
function bb_stairs.register_slab(subname, recipeitem, groups, images, description)
minetest.register_node("building_blocks:slab_" .. subname, {
description = description,
drawtype = "nodebox",
tiles = images,
paramtype = "light",
is_ground_content = true,
groups = groups,
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
selection_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
})
minetest.register_craft({
output = 'building_blocks:slab_' .. subname .. ' 3',
recipe = {
{recipeitem, recipeitem, recipeitem},
},
})
end
-- Nodes will be called stairs:{stair,slab}_<subname>
function bb_stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab)
bb_stairs.register_stair(subname, recipeitem, groups, images, desc_stair)
bb_stairs.register_slab(subname, recipeitem, groups, images, desc_slab)
end
bb_stairs.register_stair_and_slab("marble","building_blocks:Marble",
{cracky=3},
{"building_blocks_marble.png"},
"Marble stair",
"Marble slab"
)
bb_stairs.register_stair_and_slab("hardwood","building_blocks:hardwood",
{choppy=1,flammable=1},
{"building_blocks_hardwood.png"},
"Hardwood stair",
"Hardwood slab"
)
bb_stairs.register_stair_and_slab("fakegrass","building_blocks:fakegrass",
{crumbly=3},
{"default_grass.png"},
"Grass stair",
"Grass slab"
)
bb_stairs.register_stair_and_slab("tar","building_blocks:Tar",
{crumbly=1},
{"building_blocks_tar.png"},
"Tar stair",
"Tar slab"
)
bb_stairs.register_stair_and_slab("grate","building_blocks:grate",
{cracky=1},
{"building_blocks_grate.png"},
"Grate Stair",
"Grate Slab"
)
bb_stairs.register_stair_and_slab("Adobe", "building_blocks:Adobe",
{crumbly=3},
{"building_blocks_Adobe.png"},
"Adobe stair",
"Adobe slab"
)
bb_stairs.register_stair_and_slab("Roofing", "building_blocks:Roofing",
{snappy=3},
{"building_blocks_Roofing.png"},
"Roofing stair",
"Roofing slab"
)
end
minetest.register_craft({
type = "fuel",
recipe = "building_blocks:hardwood",
burntime = 28,
})
minetest.register_node("building_blocks:fakegrass", {
tiles = {"default_grass.png", "default_dirt.png", "default_dirt.png^default_grass_side.png"},
description = "Fake Grass",
is_ground_content = true,
groups = {crumbly=3},
sounds = default.node_sound_dirt_defaults({
footstep = {name="default_grass_footstep", gain=0.4},
}),
})
minetest.register_craftitem("building_blocks:sticks", {
description = "Small bundle of sticks",
image = "building_blocks_sticks.png",
on_place_on_ground = minetest.craftitem_place_item,
})
minetest.register_craftitem("building_blocks:tar_base", {
description = "Tar base",
image = "building_blocks_tar_base.png",
})
--Tar
--[[minetest.register_craft({
output = 'building_blocks:knife 1',
recipe = {
{"group:tar_block"},
{"group:stick"},
}
})
--]] -- Modif MFF, remove this useless tool
minetest.register_alias("tar", "building_blocks:Tar")
minetest.register_alias("fakegrass", "building_blocks:fakegrass")
minetest.register_alias("tar_knife", "building_blocks:knife")
minetest.register_alias("adobe", "building_blocks:Adobe")
minetest.register_alias("building_blocks_roofing", "building_blocks:Roofing")
minetest.register_alias("hardwood", "building_blocks:hardwood")
minetest.register_alias("sticks", "building_blocks:sticks")
minetest.register_alias("building_blocks:faggot", "building_blocks:sticks")
minetest.register_alias("marble", "building_blocks:Marble")
minetest.register_node("building_blocks:Tar", {
description = "Tar",
tiles = {"building_blocks_tar.png"},
is_ground_content = true,
groups = {crumbly=1, tar_block = 1},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("building_blocks:Marble", {
description = "Marble",
tiles = {"building_blocks_marble.png"},
is_ground_content = true,
groups = {cracky=3, marble = 1},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
type = "fuel",
recipe = "building_blocks:sticks",
burntime = 5,
})
minetest.register_craft({
type = "fuel",
recipe = "building_blocks:Tar",
burntime = 40,
})
minetest.register_craft({
type = "cooking",
output = "building_blocks:Tar",
recipe = "building_blocks:tar_base",
})
minetest.register_tool("building_blocks:knife", {
description = "Tar Knife",
inventory_image = "building_blocks_knife.png",
tool_capabilities = {
max_drop_level=0,
groupcaps={
choppy={times={[2]=7.50, [3]=2.80}, uses = 100, maxlevel=1},
fleshy={times={[2]=5.50, [3]=2.80}, uses = 100, maxlevel=1}
}
},
})
minetest.register_craft({
output = "building_blocks:Marble 9",
recipe = {
{"default:clay", "group:tar_block", "default:clay"},
{"group:tar_block","default:clay", "group:tar_block"},
{"default:clay", "group:tar_block","default:clay"},
}
})
if not minetest.get_modpath("technic") then
minetest.register_node( ":technic:granite", {
description = "Granite",
tiles = { "technic_granite.png" },
is_ground_content = true,
groups = {cracky=1},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "technic:granite 9",
recipe = {
{ "group:tar_block", "group:marble", "group:tar_block" },
{ "group:marble", "group:tar_block", "group:marble" },
{ "group:tar_block", "group:marble", "group:tar_block" }
},
})
if minetest.get_modpath("moreblocks") then
stairsplus:register_all("technic", "granite", "technic:granite", {
description="Granite",
groups={cracky=1, not_in_creative_inventory=1},
tiles={"technic_granite.png"},
})
end
end
| unlicense |
kitala1/darkstar | scripts/globals/weaponskills/quietus.lua | 30 | 1643 | -----------------------------------
-- Quietus
-- Scythe weapon skill
-- Skill Level: N/A
-- Delivers a triple damage attack that ignores target's defense. Amount ignored varies with TP. Redemption: Aftermath.
-- Available only when equipped with Redemption (85)/(90)/(95)/(99) or Penitence +1/+2/+3/Umiliati.
-- Aligned with the Shadow Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Shadow Belt, Aqua Belt & Snow Belt.
-- Element: None
-- Modifiers: STR: 60% MND: 60%
-- 100%TP 200%TP 300%TP
-- 3.00 3.00 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 3.0; params.ftp200 = 3.0; params.ftp300 = 3.0;
params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; 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;
params.ignoresDef = true;
params.ignored100 = 0.1;
params.ignored200 = 0.3;
params.ignored300 = 0.5;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.6; params.mnd_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kitala1/darkstar | scripts/zones/Temenos/mobs/Fire_Elemental.lua | 17 | 1657 | -----------------------------------
-- Area: Temenos E T
-- NPC: Fire_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,killer)
local mobID = mob:getID();
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
switch (mobID): caseof {
[16928840] = function (x)
GetNPCByID(16928768+173):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+173):setStatus(STATUS_NORMAL);
end ,
[16928841] = function (x)
GetNPCByID(16928768+215):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+215):setStatus(STATUS_NORMAL);
end ,
[16928842] = function (x)
GetNPCByID(16928768+284):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+284):setStatus(STATUS_NORMAL);
end ,
[16928843] = function (x)
GetNPCByID(16928768+40):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+40):setStatus(STATUS_NORMAL);
end ,
[16929033] = function (x)
if(IsMobDead(16929034)==false)then -- ice
DespawnMob(16929034);
SpawnMob(16929040);
end
end ,
}
end; | gpl-3.0 |
d-o/LUA-LIB | K400Examples/external.lua | 2 | 6339 | #!/usr/bin/env lua
-------------------------------------------------------------------------------
-- external
--
-- Example of how to set up sockets for remote connections to this device
-- To see things operating, telnet to port 1111 or 1112.
-------------------------------------------------------------------------------
local rinApp = require "rinApp" -- load in the application framework
local timers = require 'rinSystem.rinTimers'
local sockets = require 'rinSystem.rinSockets'
local dbg = require 'rinLibrary.rinDebug'
--=============================================================================
-- Connect to the instruments you want to control
--=============================================================================
local device = rinApp.addK400() -- make a connection to the instrument
-------------------------------------------------------------------------------
-- Callback to handle PWR+ABORT key and end application
device.setKeyCallback('pwr_cancel', rinApp.finish, 'long')
-------------------------------------------------------------------------------
--=============================================================================
-- Create a new socket on port 1111 that allows bidirection communications
-- with an extenal device
--=============================================================================
-------------------------------------------------------------------------------
-- We need somewhere to keep the socket descriptor so we can send messages to it
local bidirectionalSocket = nil
-- Write to the bidirectional socket
-- @param msg The message to write
local function writeBidirectional(msg)
if bidirectionalSocket ~= nil then
sockets.writeSocket(bidirectionalSocket, msg)
end
end
-------------------------------------------------------------------------------
-- Helper function to split the read string into separate lines.
-- @param s The string to split
-- @return Table of lines. Usually with a blank line at the end.
local function split(s)
local t = {}
local function helper(line)
table.insert(t, line)
return ""
end
helper(s:gsub("(.-)\r?\n", helper))
return t
end
-------------------------------------------------------------------------------
-- Callback function for client connections on the bidirectional socket.
-- @param sock Socket that has something ready to read.
local function bidirectionalFromExternal(sock)
local m, err = sockets.readSocket(sock)
if err ~= nil then
sockets.removeSocket(sock)
bidirectionalSocket = nil
else
local lines = split(m)
for i = 1, #lines do
if lines[i] == "ping" then
writeBidirectional("pong\r\n")
end
end
end
end
-------------------------------------------------------------------------------
-- Three callback functions that are called when a new socket connection is
-- established. These functions should add the socket to the sockets management
-- module and set any required timouts
local function socketBidirectionalAccept(sock, ip, port)
if bidirectionalSocket ~= nil then
dbg.info('second bidirectional connection from', ip, port)
else
bidirectionalSocket = sock
sockets.addSocket(sock, bidirectionalFromExternal)
sockets.setSocketTimeout(sock, 0.010)
dbg.info('bidirectional connection from', ip, port)
end
end
-------------------------------------------------------------------------------
-- Create the server socket
sockets.createServerSocket(1111, socketBidirectionalAccept)
--=============================================================================
-- Create a new socket on port 1112 that allows unidirection communications
-- to an extenal device
--=============================================================================
-------------------------------------------------------------------------------
-- Filter function on the outgoing data.
-- @param sock The socket in question (you'll usually ignore this)
-- @param msg The message to be filtered
-- @return The message to be sent or nil for no message
-- It is important to note that this function is called for things you
-- write to the socket set as well as system messages.
local function unidirectionFilter(sock, msg)
-- We'll keep all messages that contain a capital G and discard the rest
if string.find(msg, "G") ~= nil then
return msg
end
-- Allow our own message but we change it to demonstrate message edit
-- capabilities.
if msg == "IDLE" then
return " uni-idle "
end
return nil
end
-------------------------------------------------------------------------------
-- Callback when a new connection is incoming the unidirection data stream.
-- @param sock The newly connected socket
-- @param ip The source IP address of the socket
-- @param port The source port of the socket
local function socketUnidirectionalAccept(sock, ip, port)
-- Set up so that all incoming traffic is ignored, this stream only
-- does outgoings. Failure to do this will cause a build up of incoming
-- data packets and blockage.
sockets.addSocket(sock, sockets.flushReadSocket)
-- Set a brief timeout to prevent things clogging up.
sockets.setSocketTimeout(sock, 0.001)
-- Add the socket to the unidirectional broadcast group. A message
-- sent here is forwarded to all unidirectional sockets.
-- We're using an inline filter function that just allows all traffic
-- through, this function can return nil to prevent a message or something
-- else to replace a message.
sockets.addSocketSet("uni", sock, unidirectionFilter)
-- Finally, log the fact that we've got a new connection
dbg.info('unidirectional connection from', ip, port)
end
-------------------------------------------------------------------------------
-- Timer call back that injects extra information into the unidirection sockets
local function unidirectionalTimedMessages()
sockets.writeSet("uni", "IDLE")
end
-------------------------------------------------------------------------------
-- Create the server socket and timer
timers.addTimer(1.324, 0.3, unidirectionalTimedMessages)
sockets.createServerSocket(1112, socketUnidirectionalAccept)
rinApp.run() -- run the application framework
| gpl-3.0 |
LaurieJohnson/iguana-web-apps | shared/testui.lua | 2 | 17566 | local ui = {}
function ui.main()
return ui.template("/unit", ui.ResourceTable['/unit/main'])
end
function ui.template(Name, Content)
Name = Name:gsub("/", "_")
if iguana.isTest() then
for Key, Val in pairs(ui.ResourceTable) do
Key = Key:gsub("/", "_")
local File = io.open(Key, 'w+')
File:write(Val);
File:close()
end
else
local File = io.open(Name, 'r')
if (File) then
Content = File:read('*a');
File:close()
end
end
return Content
end
ui.ResourceTable={
['/unit/main']=[[
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="/unit/dashboard.js"></script>
<link rel="stylesheet" type="text/css" href="/unit/dashboard.css">
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800">
<title>Iguana Regression Tests</title>
</head>
<body></body>
</html>
]];
['/unit/dashboard.css']=[[
body {
background-color: #eff1e8;
font-family: 'Open Sans',sans-serif;
font-size: 12pt;
padding: 0px;
margin: 0px;
}
h1 {
font-size: 2.8em;
font-weight: 700;
text-align: center;
padding: 35px 0px 25px 0px;
background: -webkit-linear-gradient(#a5db58, #7bc144) #a5db58;
background: -o-linear-gradient(#a5db58, #7bc144) #a5db58;
background: -moz-linear-gradient(#a5db58, #7bc144) #a5db58;
background: linear-gradient(#a5db58, #7bc144) #a5db58;
color: #FFFFFF;
text-shadow: #264504 0px 1px 2px;
box-shadow: #888888 0px 1px 1px;
}
#global {
background: none repeat scroll 0 0 #FCFCFC;
border: 1px solid #DDDDDD;
border-radius: 5px;
margin: 10px;
padding: 20px;
}
#chart, #time {
margin: 0px auto;
display: block;
width: 80%;
}
#time {
padding: 4px 0 0 0;
text-align: right;
}
#time span {
font-weight: bold;
}
#detail, #inspect {
display: none;
}
#detailchart {
width: 50%;
margin: auto;
}
#detailmessage {
padding: 10px;
margin: 15px 0;
border 1px solid #ffffff;
}
#detailmessage.go {
border: 1px solid #a5db58;
color: #79A041;
background-color: #EEF8E8;
}
#detailmessage.stop {
border: 1px solid #da2300;
color: #da2300;
background-color: #F7E5E5;
}
#translatorlink {
text-align: center;
padding: 20px;
}
.sample-data {
font-family: Inconsolata, Menlo, Courier, monospace;
}
del {
background-color: #F7E5E5;
}
ins {
background-color: #EEF8E8;
}
.line-end {
font-weight: bold;
font-size: 1.3em;
color: fuchsia;
}
div.dataTables_wrapper {
background-color: #FFFFFF;
border: 1px solid #DDDDDD;
border-radius: 5px;
box-shadow: none;
overflow: hidden;
padding: 15px 15px 10px 15px;
}
.dataTables_length label,
.dataTables_filter label {
color: #777777;
letter-spacing: 0.05em;
font-size: 0.85em;
text-transform: uppercase;
font-weight: 600;
}
input {
border: 1px solid #DDDDDD;
height: 20px;
}
#summary {
width: 100% !important;
border-collapse: separate;
border-color: #DDDDDD;
border-image: none;
border-style: solid solid solid none;
border-width: 1px 1px 1px 0px;
margin: 36px 0px 10px 0px;
}
#summary thead {
background-color: #FAFAFA;
background-image: linear-gradient(to bottom, #FAFAFA, #EFEFEF);
box-shadow: none;
height: 36px;
overflow: hidden;
color: #444444;
}
#summary thead th {
border-bottom: 0px solid #FFFFFF;
}
#summary thead th {
border-left: 1px solid #DDDDDD;
}
#summary thead th:first-child {
border-left: 1px solid #DDDDDD;
}
#summary thead th:last-child {
border-right: 0px solid #DDDDDD;
}
#summary_info.dataTables_info {
float: left;
min-width: 30%;
}
th {
font-size: 0.75em;
font-weight: 600 !important;
text-transform: uppercase;
letter-spacing: 0.15em;
}
td {
font-size: 0.9em;
font-weight: 300;
border-top: 1px solid #DDDDDD;
border-left: 1px solid #DDDDDD;
}
table.dataTable td {
padding: 5px 10px;
}
table.dataTable tr.odd {
background-color: #FFFFFF;
}
table.dataTable tr.even {
background-color: #F9F9F9;
}
table.dataTable tr.odd td.sorting_1 {
background-color: #f3fafc;
}
table.dataTable tr.even td.sorting_1 {
background-color: #e7f4f9;
}
.status-green {
width:10px;
height:10px;
border-radius:50px;
background:linear-gradient(to bottom, #a6e182, #54c600);
border: 2px solid #FFFFFF;
margin: 0px auto;
}
.status-red {
width:10px;
height:10px;
border-radius:50px;
background:linear-gradient(to bottom, #f5896e, #da2300);
border: 2px solid #FFFFFF;
margin: 0px auto;
}
.dataTables_info, #time {
text-transform: uppercase;
padding: 10px;
color: #777777;
letter-spacing: 0.05em;
font-size: 0.85em;
font-weight: 600;
}
div#summary_paginate {
text-transform: uppercase;
color: #777777;
letter-spacing: 0.05em;
font-size: 0.8em;
font-weight: 600;
}
.paginate_disabled_previous,
.paginate_enabled_previous,
.paginate_enabled_previous:hover,
.paginate_disabled_next,
.paginate_enabled_next,
.paginate_enabled_next:hover {
background: none;
}
a#summary_previous:before
{
content: "\2190 \A0";
}
a#summary_previous {
border: 1px solid #DDDDDD;
border-bottom-left-radius: 4px;
border-left-width: 1px;
border-top-left-radius: 4px;
padding: 8px 10px 3px 10px;
background: #FFFFFF;
}
a#summary_next:after {
content: "\A0 \2192";
}
a#summary_next {
border: 1px solid #DDDDDD;
border-bottom-right-radius: 4px;
border-right-width: 1px;
border-top-right-radius: 4px;
border-left: none;
padding: 8px 10px 3px 10px;
background: #FFFFFF;
margin-left: 0px;
}
.alarm {
color: #da2300;
font-weight: bold;
}
.filterMatches {
background-color: #ffffaa;
}
]];
['/unit/dashboard.js']=[[
var Tank = {};
jQuery(document).ready(function($) {
document.location.hash = '';
var ifware = {};
ifware.TblSrchCache = {};
ifware.here = document.location;
$("body").html('\
<h1>Iguana Regression Tests</h1>\
<div id="global">\
<div id="breadcrumbs"><a href="/unit">Main</a></div>\
<div id="main">\
<div id="chart"></div>\
</div>\
<div id="detail"></div>\
<div id="inspect"></div>\
');
$("#chart").html('<table id="summary" cellpadding="0" cellspacing="0" border="0"></table>');
resetDetail();
var GreenLight = '<div class="status-green"></div>';
var RedLight = '<div class="status-red"></div>';
function arrows(Table) {
var Arrows = $("#summary_paginate a");
if (Tank.aaData.length < Table.fnSettings()._iDisplayLength) {
Arrows.hide();
return;
}
Arrows.show();
}
var Params = {
url: "/unit/channels",
success: function(Data) {
Tank = Data;
Tank.fnRowCallback = hl;
var Tbl = $("#summary").dataTable(Tank);
arrows(Tbl);
}
};
$.ajax(Params);
function hl(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var searchStrings = [];
var oApi = this.oApi;
var oSettings = this.fnSettings();
var ch = ifware.TblSrchCache;
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(oSettings.aoPreSearchCols[i].sSearch);
}
}
}
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!ch[sSregex]) {
// This regex will avoid in HTML matches
ch[sSregex] = new RegExp("("+sSregex+")(?!([^<]+)?>)", 'i');
}
var regex = ch[sSregex];
}
$('td', nRow).each( function(i) {
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
if (aData[j]) {
if ((typeof sSregex !== 'undefined') && (sSregex)) {
this.innerHTML = aData[j].replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
else {
this.innerHTML = aData[j];
}
}
});
return nRow;
};
function showMain() {
$("#detail").hide();
$("#inspect").hide();
$("#main").show();
resetDetail();
}
function showDetail() {
$("#main").hide();
$("#inspect").html('').hide();
$("#detail").show();
}
function resetDetail() {
$("#detail").html('<h3></h3><div id="detailmessage"></div><div id="detailchart"></div>');
Tank.Detail = {};
}
function mapGuid(Guid) {
for (var i = 0; i < Tank.Guids.length; i++) {
if (Tank.Guids[i][0] == Guid) {
return i;
}
}
}
function runTests(Guid) {
console.log("Running Test.");
var index = mapGuid(Guid);
showDetail();
if (Tank.Guids[index][2]) {
$("#detail h3").html('Running tests for ' + Tank.Guids[index][1]);
$.ajax({
url: "/unit?channel=" + Guid +"&name=" + Tank.Guids[index][1],
success: function(Data) {
Tank.Detail = Data;
var Status = Data.error
? RedLight
: GreenLight;
var Tbl = $("#summary").dataTable();
Tbl.fnUpdate(Status, index, 4);
$("#detailchart").html('<table id="testresult" cellpadding="0" cellspacing="0" border="0"></table>');
var TestTbl = $("#testresult").dataTable(Tank.Detail);
}
});
} else {
$("#detail").prepend('<h3 id="test_title">Can\'t run tests for ' + Tank.Guids[index][1] + '</h3>\
<p>(Need to <a href="' + document.location + '" id="generate">generate a set of expected results first</a>)</p>');
$("a#generate").click(function(event) {
event.preventDefault();
$.ajax({
url: "/unit/build?channel=" + Tank.Guids[index][3],
success: function(Data) {
if (Data.error) {
$("#detailmessage").addClass('stop').html(Data.error);
} else {
Tank.Guids[index][2] = true;
console.log(Tank.Guids[index][2]);
var Tbl = $("#summary").dataTable();
Tbl.fnUpdate(GreenLight, index, 3);
$('#detailmessage').addClass('go').html('Result set built successfully. <a id="runtestsnow" href="' + document.location + '">Run tests now</a>');
$('#runtestsnow').click(function(event) {
event.preventDefault();
$('#detailmessage').removeClass('go').html('');
$('#detail h3, #detail p').remove();
runTests(Guid);
});
}
}
});
});
}
}
function inspectTest(SDidx, Guid) {
--SDidx;
$('#main').hide();
$('#detail').hide();
$('#inspect').html('<div id="translatorlink">' + Tank.Detail.Res[SDidx].EditLink + '</div>\
<div id="expected" class="sample-data"><h3>Expected result:</h3><span id="youcanchangethis" contenteditable="true">' + Tank.Detail.Res[SDidx].Exp + '</span></div>\
<div id="actual" class="sample-data"><h3>Actual result:</h3>' + diffString(Tank.Detail.Res[SDidx].Exp, Tank.Detail.Res[SDidx].Act) + '</div>');
$('#youcanchangethis').blur(function() {
if ($(this).text() != Tank.Detail.Res[SDidx].Exp) {
console.log("Will update expected results.");
var NewExp = $(this).html().replace(/ <span class="line-end">(\\n|\\r)<\/span><br> /gm, '<span class=\"line-end\">$1</span><br>');
$(this).html(NewExp);
changeExpected(Guid, SDidx, $(this).text());
Tank.Detail.Res[SDidx].Exp = $(this).text();
}
});
$('#inspect').show();
}
function changeExpected(Guid, SDidx, NewText) {
var i = mapGuid(Guid);
var Data = {
't_guid': Tank.Guids[i][3],
'sd_idx': SDidx,
'txt': NewText
};
$.ajax({
url: '/unit/edit_result',
type: 'POST',
data: Data,
dataType: 'json',
success: function() {
console.log("Expected result changed.");
}
});
}
function breadcrumbs(Hash, Vars) {
var OldBc = $('#breadcrumbs *:not(a:first)');
var NewBc = '';
if (! Hash.length) {
OldBc.remove();
return;
}
if (Vars.Test) {
NewBc = '<span> > </span><a href="#Test=' + Vars.Test + '">' + Tank.Guids[mapGuid(Vars.Test)][1] + '</a>';
if (Vars.Inspect) {
NewBc += '<span> > </span><a href="#Inspect=' + Vars.Inspect + '&Test=' + Vars.Test + '">Test #' + Vars.Inspect + '</a>';
}
}
OldBc.remove()
$('#breadcrumbs').append(NewBc);
}
window.onhashchange = function() {
var Hash = document.location.hash;
var Vars = {};
if (Hash.length) {
var Nubbins = Hash.substr(1).split('&');
for (var i = 0; i < Nubbins.length; i++) {
var Pieces = Nubbins[i].split('=');
// The baffy spacing below keeps the Lua extended string quoting intact
Vars[ Pieces[0] ] = Pieces[1];
}
}
breadcrumbs(Hash, Vars);
if (Vars.Test) {
if (Vars.Inspect) {
inspectTest(Vars.Inspect, Vars.Test);
return;
} else {
runTests(Vars.Test);
return;
}
} else {
showMain();
}
}
});
/*
* Javascript Diff Algorithm
* By John Resig (http://ejohn.org/)
* Modified by Chu Alan "sprite"
*
* Released under the MIT license.
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
*/
function escape(s) {
var n = s;
n = n.replace(/&/g, "&");
n = n.replace(/</g, "<");
n = n.replace(/>/g, ">");
n = n.replace(/"/g, """);
return n;
}
function diffString( o, n ) {
o = o.replace(/\s+$/, '');
n = n.replace(/\s+$/, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/) );
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = ["\n"];
} else {
oSpace.push("\n");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = ["\n"];
} else {
nSpace.push("\n");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<del>' + escape(out.o[i]) + oSpace[i] + "</del>";
}
} else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<del>' + escape(out.o[n]) + oSpace[n] + "</del>";
}
}
for ( var i = 0; i < out.n.length; i++ ) {
if (out.n[i].text == null) {
str += '<ins>' + escape(out.n[i]) + nSpace[i] + "</ins>";
} else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) {
pre += '<del>' + escape(out.o[n]) + oSpace[n] + "</del>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
}
function diff( o, n ) {
var ns = new Object();
var os = new Object();
for ( var i = 0; i < n.length; i++ ) {
if ( ns[ n[i] ] == null )
ns[ n[i] ] = { rows: new Array(), o: null };
ns[ n[i] ].rows.push( i );
}
for ( var i = 0; i < o.length; i++ ) {
if ( os[ o[i] ] == null )
os[ o[i] ] = { rows: new Array(), n: null };
os[ o[i] ].rows.push( i );
}
for ( var i in ns ) {
if ( ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1 ) {
n[ ns[i].rows[0] ] = { text: n[ ns[i].rows[0] ], row: os[i].rows[0] };
o[ os[i].rows[0] ] = { text: o[ os[i].rows[0] ], row: ns[i].rows[0] };
}
}
for ( var i = 0; i < n.length - 1; i++ ) {
if ( n[i].text != null && n[i+1].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null &&
n[i+1] == o[ n[i].row + 1 ] ) {
n[i+1] = { text: n[i+1], row: n[i].row + 1 };
o[n[i].row+1] = { text: o[n[i].row+1], row: i + 1 };
}
}
for ( var i = n.length - 1; i > 0; i-- ) {
if ( n[i].text != null && n[i-1].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null &&
n[i-1] == o[ n[i].row - 1 ] ) {
n[i-1] = { text: n[i-1], row: n[i].row - 1 };
o[n[i].row-1] = { text: o[n[i].row-1], row: i - 1 };
}
}
return { o: o, n: n };
}
]];
}
return ui | mit |
kitala1/darkstar | scripts/zones/Dangruf_Wadi/TextIDs.lua | 5 | 1316 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6541; -- Obtained: <item>.
GIL_OBTAINED = 6542; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6544; -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7195; -- You can't fish here.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7415; -- You unlock the chest!
CHEST_FAIL = 7416; -- fails to open the chest.
CHEST_TRAP = 7417; -- The chest was trapped!
CHEST_WEAK = 7418; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7419; -- The chest was a mimic!
CHEST_MOOGLE = 7420; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7421; -- The chest was but an illusion...
CHEST_LOCKED = 7422; -- The chest appears to be locked.
-- Other Text
GEOMAGNETIC_FOUNT = 7164; -- A faint energy wafts up from the ground.
SMALL_HOLE = 7469; -- There is a small hole here.
-- conquest Base
CONQUEST_BASE = 0;
-- Strange Apparatus
DEVICE_NOT_WORKING = 7304; -- The device is not working.
SYS_OVERLOAD = 7313; -- arning! Sys...verload! Enterin...fety mode. ID eras...d
YOU_LOST_THE = 7318; -- You lost the #.
| gpl-3.0 |
kitala1/darkstar | scripts/zones/Outer_Horutoto_Ruins/npcs/_5ef.lua | 19 | 3309 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Ancient Magical Gizmo #2 (F out of E, F, G, H, I, J)
-- Involved In Mission: The Heart of the Matter
-----------------------------------
package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Outer_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Check if we are on Windurst Mission 1-2
if(player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER) then
MissionStatus = player:getVar("MissionStatus");
if(MissionStatus == 2) then
-- Entered a Dark Orb
if(player:getVar("MissionStatus_orb2") == 1) then
player:startEvent(0x002f);
else
player:messageSpecial(ORB_ALREADY_PLACED);
end
elseif(MissionStatus == 4) then
-- Took out a Glowing Orb
if(player:getVar("MissionStatus_orb2") == 2) then
player:startEvent(0x002f);
else
player:messageSpecial(G_ORB_ALREADY_GOTTEN);
end
else
player:messageSpecial(DARK_MANA_ORB_RECHARGER);
end
else
player:messageSpecial(DARK_MANA_ORB_RECHARGER);
end
return 1;
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 == 0x002f) then
orb_value = player:getVar("MissionStatus_orb2");
if(orb_value == 1) then
player:setVar("MissionStatus_orb2",2);
-- Push the text that the player has placed the orb
player:messageSpecial(SECOND_DARK_ORB_IN_PLACE);
--Delete the key item
player:delKeyItem(SECOND_DARK_MANA_ORB);
-- Check if all orbs have been placed or not
if(player:getVar("MissionStatus_orb1") == 2 and
player:getVar("MissionStatus_orb3") == 2 and
player:getVar("MissionStatus_orb4") == 2 and
player:getVar("MissionStatus_orb5") == 2 and
player:getVar("MissionStatus_orb6") == 2) then
player:messageSpecial(ALL_DARK_MANA_ORBS_SET);
player:setVar("MissionStatus",3);
end
elseif(orb_value == 2) then
player:setVar("MissionStatus_orb2",3);
-- Time to get the glowing orb out
player:addKeyItem(SECOND_GLOWING_MANA_ORB);
player:messageSpecial(KEYITEM_OBTAINED,SECOND_GLOWING_MANA_ORB);
-- Check if all orbs have been placed or not
if(player:getVar("MissionStatus_orb1") == 3 and
player:getVar("MissionStatus_orb3") == 3 and
player:getVar("MissionStatus_orb4") == 3 and
player:getVar("MissionStatus_orb5") == 3 and
player:getVar("MissionStatus_orb6") == 3) then
player:messageSpecial(RETRIEVED_ALL_G_ORBS);
player:setVar("MissionStatus",5);
end
end
end
end; | gpl-3.0 |
kitala1/darkstar | scripts/globals/items/winterflower.lua | 36 | 1319 | -----------------------------------------
-- ID: 5907
-- Item: Winterflower
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility +3
-- Intelligence +5
-- Charisma -5
-- Resist Virus +20
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5907);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 3);
target:addMod(MOD_INT, 5);
target:addMod(MOD_CHR, -5);
target:addMod(MOD_VIRUSRES, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 3);
target:delMod(MOD_INT, 5);
target:delMod(MOD_CHR, -5);
target:delMod(MOD_VIRUSRES, 20);
end;
| gpl-3.0 |
Roblox/Core-Scripts | CoreScriptsRoot/Modules/TenFootInterface.lua | 1 | 11203 | --[[
Filename: TenFootInterface.lua
Written by: jeditkacheff
Version 1.0
Description: Setups up some special UI for ROBLOX TV gaming
--]]
-------------- CONSTANTS --------------
local HEALTH_GREEN_COLOR = Color3.new(27/255, 252/255, 107/255)
local DISPLAY_POS_INIT_INSET = 0
local DISPLAY_ITEM_OFFSET = 4
local FORCE_TEN_FOOT_INTERFACE = false
-------------- SERVICES --------------
local CoreGui = game:GetService("CoreGui")
local RobloxGui = CoreGui:WaitForChild("RobloxGui")
local UserInputService = game:GetService("UserInputService")
local GuiService = game:GetService("GuiService")
local Players = game:GetService("Players")
------------------ VARIABLES --------------------
local tenFootInterfaceEnabled = false
do
local platform = UserInputService:GetPlatform()
tenFootInterfaceEnabled = (platform == Enum.Platform.XBoxOne or platform == Enum.Platform.WiiU or platform == Enum.Platform.PS4 or
platform == Enum.Platform.AndroidTV or platform == Enum.Platform.XBox360 or platform == Enum.Platform.PS3 or
platform == Enum.Platform.Ouya or platform == Enum.Platform.SteamOS)
end
if FORCE_TEN_FOOT_INTERFACE then
tenFootInterfaceEnabled = true
end
local Util = {}
do
function Util.Create(instanceType)
return function(data)
local obj = Instance.new(instanceType)
for k, v in pairs(data) do
if type(k) == 'number' then
v.Parent = obj
else
obj[k] = v
end
end
return obj
end
end
end
local function CreateModule()
local this = {}
local nextObjectDisplayYPos = DISPLAY_POS_INIT_INSET
local displayStack = {}
local displayStackChanged = Instance.new("BindableEvent")
local healthContainerPropertyChanged = Instance.new("BindableEvent")
-- setup base gui
local function createContainer()
if not this.Container then
this.Container = Util.Create'ImageButton'
{
Name = "TopRightContainer";
Size = UDim2.new(0, 350, 0, 100);
Position = UDim2.new(1,-415,0,10);
AutoButtonColor = false;
Image = "";
Active = false;
BackgroundTransparency = 1;
Parent = RobloxGui;
};
end
end
function removeFromDisplayStack(displayObject)
local moveUpFromHere = nil
for i = 1, #displayStack do
if displayStack[i] == displayObject then
moveUpFromHere = i + 1
break
end
end
local prevObject = displayObject
for i = moveUpFromHere, #displayStack do
local objectToMoveUp = displayStack[i]
objectToMoveUp.Position = UDim2.new(objectToMoveUp.Position.X.Scale, objectToMoveUp.Position.X.Offset,
objectToMoveUp.Position.Y.Scale, prevObject.AbsolutePosition.Y)
prevObject = objectToMoveUp
end
displayStackChanged:Fire()
end
function addBackToDisplayStack(displayObject)
local moveDownFromHere = 0
for i = 1, #displayStack do
if displayStack[i] == displayObject then
moveDownFromHere = i + 1
break
end
end
local prevObject = displayObject
for i = moveDownFromHere, #displayStack do
local objectToMoveDown = displayStack[i]
local nextDisplayPos = prevObject.AbsolutePosition.Y + prevObject.AbsoluteSize.Y + DISPLAY_ITEM_OFFSET
objectToMoveDown.Position = UDim2.new(objectToMoveDown.Position.X.Scale, objectToMoveDown.Position.X.Offset,
objectToMoveDown.Position.Y.Scale, nextDisplayPos)
prevObject = objectToMoveDown
end
displayStackChanged:Fire()
end
function addToDisplayStack(displayObject)
local lastDisplayed = nil
if #displayStack > 0 then
lastDisplayed = displayStack[#displayStack]
end
displayStack[#displayStack + 1] = displayObject
local nextDisplayPos = DISPLAY_POS_INIT_INSET
if lastDisplayed then
nextDisplayPos = lastDisplayed.AbsolutePosition.Y + lastDisplayed.AbsoluteSize.Y + DISPLAY_ITEM_OFFSET
end
displayObject.Position = UDim2.new(displayObject.Position.X.Scale, displayObject.Position.X.Offset,
displayObject.Position.Y.Scale, nextDisplayPos)
createContainer()
displayObject.Parent = this.Container
displayObject.Changed:connect(function(prop)
if prop == "Visible" then
if not displayObject.Visible then
removeFromDisplayStack(displayObject)
else
addBackToDisplayStack(displayObject)
end
end
end)
displayStackChanged:Fire()
end
function this:CreateHealthBar()
this.HealthContainer = Util.Create'Frame'{
Name = "HealthContainer";
Size = UDim2.new(1, -86, 0, 50);
Position = UDim2.new(0, 92, 0, 0);
BorderSizePixel = 0;
BackgroundColor3 = Color3.new(0,0,0);
BackgroundTransparency = 0.5;
};
local healthFillHolder = Util.Create'Frame'{
Name = "HealthFillHolder";
Size = UDim2.new(1, -10, 1, -10);
Position = UDim2.new(0, 5, 0, 5);
BorderSizePixel = 0;
BackgroundColor3 = Color3.new(1,1,1);
BackgroundTransparency = 1.0;
Parent = this.HealthContainer;
};
local healthFill = Util.Create'Frame'{
Name = "HealthFill";
Size = UDim2.new(1, 0, 1, 0);
Position = UDim2.new(0, 0, 0, 0);
BorderSizePixel = 0;
BackgroundTransparency = 0.0;
BackgroundColor3 = HEALTH_GREEN_COLOR;
Parent = healthFillHolder;
};
local healthText = Util.Create'TextLabel'{
Name = "HealthText";
Size = UDim2.new(0, 98, 0, 50);
Position = UDim2.new(0, -100, 0, 0);
BackgroundTransparency = 0.5;
BackgroundColor3 = Color3.new(0,0,0);
Font = Enum.Font.SourceSans;
FontSize = Enum.FontSize.Size36;
Text = "Health";
TextColor3 = Color3.new(1,1,1);
BorderSizePixel = 0;
Parent = this.HealthContainer;
};
local username = Util.Create'TextLabel'{
Visible = false
}
local accountType = Util.Create'TextLabel'{
Visible = false
}
addToDisplayStack(this.HealthContainer)
createContainer()
this.HealthContainer.Changed:connect(function()
healthContainerPropertyChanged:Fire()
end)
return this.Container, username, this.HealthContainer, healthFill, accountType
end
function this:CreateAccountType(accountTypeTextShort)
this.AccountTypeContainer = Util.Create'Frame'{
Name = "AccountTypeContainer";
Size = UDim2.new(0, 50, 0, 50);
Position = UDim2.new(1, -55, 0, 10);
BorderSizePixel = 0;
BackgroundColor3 = Color3.new(0,0,0);
BackgroundTransparency = 0.5;
Parent = RobloxGui;
};
local accountTypeTextLabel = Util.Create'TextLabel'{
Name = "AccountTypeText";
Size = UDim2.new(1, 0, 1, 0);
Position = UDim2.new(0, 0, 0, 0);
BackgroundTransparency = 1;
BackgroundColor3 = Color3.new(0,0,0);
Font = Enum.Font.SourceSans;
FontSize = Enum.FontSize.Size36;
Text = accountTypeTextShort;
TextColor3 = Color3.new(1,1,1);
BorderSizePixel = 0;
Parent = this.AccountTypeContainer;
TextXAlignment = Enum.TextXAlignment.Center;
TextYAlignment = Enum.TextYAlignment.Center;
};
end
function this:SetupTopStat()
local topStatEnabled = true
local displayedStat = nil
local displayedStatChangedCon = nil
local displayedStatParentedCon = nil
local leaderstatsChildAddedCon = nil
local tenFootInterfaceStat = nil
local function makeTenFootInterfaceStat()
if tenFootInterfaceStat then return end
tenFootInterfaceStat = Util.Create'Frame'{
Name = "OneStatFrame";
Size = UDim2.new(1, 0, 0, 36);
Position = UDim2.new(0, 0, 0, 0);
BorderSizePixel = 0;
BackgroundTransparency = 1;
};
local statName = Util.Create'TextLabel'{
Name = "StatName";
Size = UDim2.new(0.5,0,0,36);
BackgroundTransparency = 1;
Font = Enum.Font.SourceSans;
FontSize = Enum.FontSize.Size36;
TextStrokeColor3 = Color3.new(104/255, 104/255, 104/255);
TextStrokeTransparency = 0;
Text = " StatName:";
TextColor3 = Color3.new(1,1,1);
TextXAlignment = Enum.TextXAlignment.Left;
BorderSizePixel = 0;
ClipsDescendants = true;
Parent = tenFootInterfaceStat;
};
local statValue = statName:clone()
statValue.Position = UDim2.new(0.5,0,0,0)
statValue.Name = "StatValue"
statValue.Text = "123,643,231"
statValue.TextXAlignment = Enum.TextXAlignment.Right
statValue.Parent = tenFootInterfaceStat
addToDisplayStack(tenFootInterfaceStat)
end
local function setDisplayedStat(newStat)
if displayedStatChangedCon then displayedStatChangedCon:disconnect() displayedStatChangedCon = nil end
if displayedStatParentedCon then displayedStatParentedCon:disconnect() displayedStatParentedCon = nil end
displayedStat = newStat
if displayedStat then
makeTenFootInterfaceStat()
updateTenFootStat(displayedStat)
displayedStatParentedCon = displayedStat.AncestryChanged:connect(function() updateTenFootStat(displayedStat, "Parent") end)
displayedStatChangedCon = displayedStat.Changed:connect(function(prop) updateTenFootStat(displayedStat, prop) end)
end
end
function updateTenFootStat(statObj, property)
if property and property == "Parent" then
tenFootInterfaceStat.StatName.Text = ""
tenFootInterfaceStat.StatValue.Text = ""
setDisplayedStat(nil)
tenFootInterfaceChanged()
else
if topStatEnabled then
tenFootInterfaceStat.StatName.Text = " " .. tostring(statObj.Name) .. ":"
tenFootInterfaceStat.StatValue.Text = tostring(statObj.Value)
else
tenFootInterfaceStat.StatName.Text = ""
tenFootInterfaceStat.StatValue.Text = ""
end
end
end
local function isValidStat(obj)
return obj:IsA('StringValue') or obj:IsA('IntValue') or obj:IsA('BoolValue') or obj:IsA('NumberValue') or
obj:IsA('DoubleConstrainedValue') or obj:IsA('IntConstrainedValue')
end
local function tenFootInterfaceNewStat( newStat )
if not displayedStat and isValidStat(newStat) then
setDisplayedStat(newStat)
end
end
local localPlayer = Players.LocalPlayer
while not localPlayer do
Players.PlayerAdded:wait()
localPlayer = Players.LocalPlayer
end
function tenFootInterfaceChanged()
local leaderstats = localPlayer:FindFirstChild('leaderstats')
if leaderstats then
local statChildren = leaderstats:GetChildren()
for i = 1, #statChildren do
tenFootInterfaceNewStat(statChildren[i])
end
if leaderstatsChildAddedCon then leaderstatsChildAddedCon:disconnect() end
leaderstatsChildAddedCon = leaderstats.ChildAdded:connect(function(newStat)
tenFootInterfaceNewStat(newStat)
end)
end
end
local leaderstats = localPlayer:FindFirstChild('leaderstats')
if leaderstats then
tenFootInterfaceChanged()
else
localPlayer.ChildAdded:connect(tenFootInterfaceChanged)
end
--Top Stat Public API
local topStatApiTable = {}
function topStatApiTable:SetTopStatEnabled(value)
topStatEnabled = value
if displayedStat then
updateTenFootStat(displayedStat, "")
end
end
return topStatApiTable
end
return this
end
-- Public API
local moduleApiTable = {}
local TenFootInterfaceModule = CreateModule()
function moduleApiTable:IsEnabled()
return tenFootInterfaceEnabled
end
function moduleApiTable:CreateHealthBar()
return TenFootInterfaceModule:CreateHealthBar()
end
function moduleApiTable:CreateAccountType(accountTypeText)
return TenFootInterfaceModule:CreateAccountType(accountTypeText)
end
function moduleApiTable:SetupTopStat()
return TenFootInterfaceModule:SetupTopStat()
end
return moduleApiTable
| apache-2.0 |
Roblox/Core-Scripts | CoreScriptsRoot/Modules/DevConsole/Components/Memory/ServerMemoryData.lua | 1 | 6048 | local Signal = require(script.Parent.Parent.Parent.Signal)
local CircularBuffer = require(script.Parent.Parent.Parent.CircularBuffer)
local Constants = require(script.Parent.Parent.Parent.Constants)
local HEADER_NAMES = Constants.MemoryFormatting.ChartHeaderNames
local MAX_DATASET_COUNT = tonumber(settings():GetFVariable("NewDevConsoleMaxGraphCount"))
local BYTES_PER_MB = 1048576.0
local SORT_COMPARATOR = {
[HEADER_NAMES[1]] = function(a, b)
return a.name < b.name
end,
[HEADER_NAMES[2]] = function(a, b)
return a.dataStats.dataSet:back().data < b.dataStats.dataSet:back().data
end,
}
local getClientReplicator = require(script.Parent.Parent.Parent.Util.getClientReplicator)
local ServerMemoryData = {}
ServerMemoryData.__index = ServerMemoryData
function ServerMemoryData.new()
local self = {}
setmetatable(self, ServerMemoryData)
self._init = false
self._totalMemory = 0
self._memoryData = {}
self._memoryDataSorted = {}
self._coreTreeData = {}
self._coreTreeDataSorted = {}
self._placeTreeData = {}
self._placeTreeDataSorted = {}
self._treeViewUpdated = Signal.new()
self._sortType = HEADER_NAMES[1]
return self
end
function ServerMemoryData:updateEntry(entryList, sortedList, name, data)
if not entryList[name] then
local newBuffer = CircularBuffer.new(MAX_DATASET_COUNT)
newBuffer:push_back({
data = data,
time = self._lastUpdate
})
entryList[name] = {
min = data,
max = data,
dataSet = newBuffer
}
local newEntry = {
name = name,
dataStats = entryList[name]
}
table.insert(sortedList, newEntry)
else
local currMax = entryList[name].max
local currMin = entryList[name].min
local update = {
data = data,
time = self._lastUpdate
}
local overwrittenEntry = entryList[name].dataSet:push_back(update)
if overwrittenEntry then
local iter = entryList[name].dataSet:iterator()
local dat = iter:next()
if currMax == overwrittenEntry.data then
currMax = currMin
while dat do
currMax = dat.data < currMax and currMax or dat.data
dat = iter:next()
end
end
if currMin == overwrittenEntry.data then
currMin = currMax
while dat do
currMin = currMin < dat.data and currMin or dat.data
dat = iter:next()
end
end
end
entryList[name].max = currMax < data and data or currMax
entryList[name].min = currMin < data and currMin or data
end
end
function ServerMemoryData:updateEntryList(entryList, sortedList, statsItems)
-- All values are in bytes.
-- Convert to MB ASAP.
local totalMB = 0
for label, numBytes in pairs(statsItems) do
local value = numBytes / BYTES_PER_MB
totalMB = totalMB + value
self:updateEntry(entryList, sortedList, label, value)
end
return totalMB
end
function ServerMemoryData:updateWithTreeStats(stats)
local update = {
PlaceMemory = 0,
CoreMemory = 0,
UntrackedMemory = 0,
}
for key, value in pairs(stats) do
if key == "totalServerMemory" then
self._totalMemory = value / BYTES_PER_MB
elseif key == "developerTags" then
update.PlaceMemory = self:updateEntryList(self._placeTreeData, self._placeTreeDataSorted, value)
elseif key == "internalCategories" then
update.CoreMemory = self:updateEntryList(self._coreTreeData, self._coreTreeDataSorted, value)
end
end
update.UntrackedMemory = self._totalMemory - update.PlaceMemory - update.CoreMemory
if self._init then
for name, value in pairs(update) do
self:updateEntry(
self._memoryData["Memory"].children,
self._memoryData["Memory"].sortedChildren,
name,
value
)
end
self:updateEntry(self._memoryData, self._memoryDataSorted, "Memory", self._totalMemory)
else
local memChildren = {}
local memChildrenSorted = {}
for name, value in pairs(update) do
self:updateEntry(memChildren, memChildrenSorted, name, value)
end
self:updateEntry(self._memoryData, self._memoryDataSorted, "Memory", self._totalMemory)
memChildren["PlaceMemory"].children = self._placeTreeData
memChildren["PlaceMemory"].sortedChildren = self._placeTreeDataSorted
memChildren["CoreMemory"].children = self._coreTreeData
memChildren["CoreMemory"].sortedChildren = self._coreTreeDataSorted
self._memoryData["Memory"].children = memChildren
self._memoryData["Memory"].sortedChildren = memChildrenSorted
self._init = true
end
end
function ServerMemoryData:totalMemSignal()
return self._totalMemoryUpdated
end
function ServerMemoryData:treeUpdatedSignal()
return self._treeViewUpdated
end
function ServerMemoryData:getSortType()
return self._sortType
end
local function recursiveSort(memoryDataSort, comparator)
table.sort(memoryDataSort, comparator)
for _, entry in pairs(memoryDataSort) do
if entry.dataStats.sortedChildren then
recursiveSort(entry.dataStats.sortedChildren, comparator)
end
end
end
function ServerMemoryData:setSortType(sortType)
if SORT_COMPARATOR[sortType] then
self._sortType = sortType
recursiveSort(self._memoryDataSorted, SORT_COMPARATOR[self._sortType])
else
error(string.format("attempted to pass invalid sortType: %s", tostring(sortType)), 2)
end
end
function ServerMemoryData:getMemoryData()
return self._memoryDataSorted
end
function ServerMemoryData:start()
local clientReplicator = getClientReplicator()
if clientReplicator and not self._statsListenerConnection then
self._statsListenerConnection = clientReplicator.StatsReceived:connect(function(stats)
if not stats.ServerMemoryTree then
return
end
self._lastUpdate = os.time()
local serverMemoryTree = stats.ServerMemoryTree
if serverMemoryTree then
self:updateWithTreeStats(serverMemoryTree)
self._treeViewUpdated:Fire(self._memoryDataSorted)
end
end)
clientReplicator:RequestServerStats(true)
end
end
function ServerMemoryData:stop()
-- listeners are responsible for disconnecting themselves
local clientReplicator = getClientReplicator()
if clientReplicator then
clientReplicator:RequestServerStats(false)
self._statsListenerConnection:Disconnect()
end
end
return ServerMemoryData | apache-2.0 |
kitala1/darkstar | scripts/zones/Windurst_Waters/npcs/Maysoon.lua | 17 | 2167 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Maysoon
-- Starts and Finishes Quest: Hoist the Jelly, Roger
-- Involved in Quests: Cook's Pride
-- @zone 238
-- @pos -105 -2 69
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER) == QUEST_ACCEPTED) then
if(trade:hasItemQty(4508,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(0x2711); -- Finish quest "Hoist the Jelly, Roger"
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CooksPride = player:getQuestStatus(JEUNO,COOK_S_PRIDE);
HoistTheJelly = player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER);
if(CooksPride == QUEST_ACCEPTED and HoistTheJelly == QUEST_AVAILABLE) then
player:startEvent(0x2710); -- Start quest "Hoist the Jelly, Roger"
else
player:startEvent(0x010a); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x2710) then
player:addQuest(WINDURST,HOIST_THE_JELLY_ROGER);
elseif(csid == 0x2711) then
player:completeQuest(WINDURST,HOIST_THE_JELLY_ROGER);
player:addKeyItem(SUPER_SOUP_POT);
player:messageSpecial(KEYITEM_OBTAINED,SUPER_SOUP_POT);
player:addFame(WINDURST,WIN_FAME*30);
player:tradeComplete();
end
end;
| gpl-3.0 |
kitala1/darkstar | scripts/zones/Windurst_Waters/npcs/Yung_Yaam.lua | 36 | 1727 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Yung Yaam
-- Involved In Quest: Wondering Minstrel
-- Working 100%
-- @zone = 238
-- @pos = -63 -4 27
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:addFame(WINDURST,WIN_FAME*100)
wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL);
fame = player:getFameLevel(WINDURST)
if (wonderingstatus <= 1 and fame >= 5) then
player:startEvent(0x027d); -- WONDERING_MINSTREL: Quest Available / Quest Accepted
elseif (wonderingstatus == QUEST_COMPLETED and player:needToZone()) then
player:startEvent(0x0283); -- WONDERING_MINSTREL: Quest After
else
player:startEvent(0x0261); -- 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);
end;
| gpl-3.0 |
mahdi1062/avira | plugins/kickall.lua | 125 | 1670 | local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = result.id
local chatname = result.print_name
local get_cmd = cb_extra.get_cmd
if get_cmd == 'kickall' then
for k,v in pairs(result.members) do
local data = load_data(_config.moderation.data)
--[[if data[tostring(chat_id)] then
if data[tostring(chat_id)]['moderators'][tostring(v.id)] then
return nil
end
end]]
if data['admins'] then
if data['admins'][tostring(v.id)] then
return nil
end
end
if v.id ~= our_id then
kick_user(v.id, chat_id)
end
end
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if not is_chat_msg(msg) then
return 'This function only works on group'
end
if matches[1] == 'kickall' and matches[2] then
if matches[2] ~= tostring(msg.to.id) then
return 'Chat id missmatch'
end
local get_cmd = matches[1]
local user_id = msg.to.id
local text = 'Kicking all members of ' .. string.gsub(msg.to.print_name, '_', ' ') .. '...'
send_large_msg(receiver, text)
chat_info(receiver, returnids, {receiver=receiver, get_cmd=get_cmd})
end
end
return {
description = "Broadcast message to all group participant.",
usage = {
admin = {
"!kickall <chat_id> : Kick all users from group",
},
},
patterns = {
"^!(kickall) (%d+)$",
},
run = run,
moderated = true
}
| gpl-2.0 |
hanxi/cocos2d-x-v3.1 | frameworks/cocos2d-x/cocos/scripting/lua-bindings/script/json.lua | 60 | 15380 | -----------------------------------------------------------------------------
-- JSON4Lua: JSON encoding / decoding support for the Lua language.
-- json Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.40
-- This module is released under the MIT License (MIT).
-- 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.e", 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.e"
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
| mit |
kidaa/MoonGen | test/example-scripts/moongen.lua | 6 | 1939 | local mg = {}
local proc = {}
proc.__index = proc
function mg.start(script, ...)
local str = ""
for i = 1, select("#", ...) do
-- TODO: escape arguments properly
str = str .. " \"" .. select(i, ...) .. "\""
end
local obj = setmetatable({}, proc)
obj.proc = io.popen("cd ../.. && ./build/MoonGen " .. script .. str)
return obj
end
local function appendArg(a, ...)
local varArgs = { ... }
varArgs[#varArgs + 1] = a
return unpack(varArgs)
end
function proc:waitFor(expr1, expr2)
local lines = {}
for line in self.proc:lines() do
print("[Output] " .. line)
lines[#lines + 1] = line
if line:match(expr1) then
return appendArg(lines, appendArg(1, appendArg(line, line:match(expr1))))
elseif expr2 and line:match(expr2) then
return appendArg(lines, appendArg(2, appendArg(line, line:match(expr2))))
end
end
return false, lines
end
function proc:waitForPorts(numPorts, expectedSpeed)
expectedSpeed = expectedSpeed or 10
local found = 0
while true do
local state, speed, line = self:waitFor("Port %d+ %S+ is (%S+): %S+ (%d+) MBit", "(%d+) ports are up(%.)$")
if line:match("ports are up") then
assert(numPorts == found, ("expected %s ports, found %s"):format(numPorts, found))
return true
end
found = found + 1
assert(state and speed)
if state ~= "up" then
print("Port down: " .. line)
assert(false)
end
speed = tonumber(speed) / 1000
if speed ~= expectedSpeed then
print("Wrong link speed: " .. line)
assert(false)
end
end
end
function proc:kill(signal)
signal = signal or "TERM"
-- TODO: get the correct pid instead of killall :>
os.execute("killall -" .. signal .. " MoonGen")
end
function proc:running()
local pidProc = io.popen("pidof sshda")
local pid = pidProc:read()
pidProc:close()
return not not pid
end
function proc:destroy()
self:kill()
if self:running() then
os.execute("sleep 1")
self:kill("KILL")
end
self.proc:close()
end
return mg
| mit |
kitala1/darkstar | scripts/zones/Port_Bastok/npcs/Melloa.lua | 36 | 1613 | -----------------------------------
-- Area: Port Bastok
-- NPC: Melloa
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MELLOA_SHOP_DIALOG);
stock = {
0x11EF, 147,1, --Pumpernickel
0x1141, 3036,1, --Egg Soup
0x115A, 368,1, --Pineapple Juice
0x1127, 22,2, --Bretzel
0x11E2, 143,2, --Sausage
0x1148, 1012,2, --Melon Juice
0x1155, 662,2, --Roast Mutton
0x1193, 92,3, --Iron Bread
0x1154, 294,3, --Baked Popoto
0x1167, 184,3, --Pebble Soup
0x119D, 10,3 --Distilled Water
}
showNationShop(player, 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 |
kitala1/darkstar | scripts/zones/Northern_San_dOria/npcs/Durogg.lua | 31 | 2754 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Durogg
-- Type: Past Event Watcher
-- @zone: 231
-- @pos: 15 0 -18
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Add-on Scenarios
local AddonScenarios = 0xFFFFFFFE;
if (player:hasCompletedMission(AMK,DRENCHED_IT_BEGAN_WITH_A_RAINDROP)) then
AddonScenarios = AddonScenarios - 2; -- Drenched! It Began with a Raindrop.
end
-- *Need the correct csid
-- if (player:hasCompletedMission(AMK,HASTEN_IN_A_JAM_IN_JEUNO)) then
-- AddonScenarios = AddonScenarios - 4; -- Hasten! In a Jam in Jeuno?
-- end
-- Seekers of Adoulin
local SeekersOfAdoulin = 0xFFFFFFFE;
-- *Need the correct csid
-- if (player:hasCompletedMission(SOA,RUMORS_FROM_THE_WEST)) then
-- SeekersOfAdoulin = SeekersOfAdoulin - 2; -- Rumors from the West
-- end
-- Determine if any cutscenes are available for the player.
local gil = player:getGil();
if (AddonScenarios == 0xFFFFFFFE and
SeekersOfAdoulin == 0xFFFFFFFE)
then -- Player has no cutscenes available to be viewed.
gil = 0; -- Setting gil to a value less than 10(cost) will trigger the appropriate response from this npc.
end
player:startEvent(0x0361,AddonScenarios,SeekersOfAdoulin,0xFFFFFFFE,0xFFFFFFFE,0xFFFFFFFE,0xFFFFFFFE,10,gil); -- CSID,Missions,Fame,?,?,?,?,Cost,TotalGilPlayerHas
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (player:delGil(10) == false) then
player:setLocalVar("Durogg_PlayCutscene", 2) ; -- Cancel the cutscene.
player:updateEvent(0);
else
player:setLocalVar("Durogg_PlayCutscene", 1)
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (player:getLocalVar("Durogg_PlayCutscene") < 2) then
if ( option == 1) then -- Drenched! It Began with a Raindrop
player:startEvent(0x7549,0,0,0,0,0,0,231);
-- elseif (option == 2) then -- Hasten! In a Jam in Jeuno?
-- player:startEvent(CSID,0,0,0,0,0,0,231);
-- elseif (option == 33) then -- Rumors from the West
-- player:startEvent(CSID);
end
end
player:setLocalVar("Durogg_PlayCutscene", 0)
end;
| gpl-3.0 |
kitala1/darkstar | scripts/globals/spells/learned_etude.lua | 13 | 1758 | -----------------------------------------
-- Spell: Learned Etude
-- Static INT Boost, BRD 26
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 0;
if (sLvl+iLvl <= 181) then
power = 3;
elseif((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then
power = 4;
elseif((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then
power = 5;
elseif((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then
power = 6;
elseif((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then
power = 7;
elseif((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then
power = 8;
elseif(sLvl+iLvl >= 450) then
power = 9;
end
local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_INT, 1)) then
spell:setMsg(75);
end
return EFFECT_ETUDE;
end; | gpl-3.0 |
kitala1/darkstar | scripts/zones/Rabao/npcs/Maryoh_Comyujah.lua | 19 | 2011 | -----------------------------------
-- Area: Rabao
-- NPC: Maryoh Comyujah
-- Involved in Mission: The Mithra and the Crystal (Zilart 12)
-- @pos 0 8 73 247
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Rabao/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(ZILART) == THE_MITHRA_AND_THE_CRYSTAL) then
if(player:getVar("ZilartStatus") == 0) then
player:startEvent(0x0051); -- Start
elseif(player:hasKeyItem(SCRAP_OF_PAPYRUS)) then
player:startEvent(0x0053); -- Finish
elseif(player:getVar("ZilartStatus") == 2) then
player:startEvent(0x0054); -- Go to hall of the gods
else
player:startEvent(0x0052);
end
elseif(player:hasCompletedMission(ZILART,THE_MITHRA_AND_THE_CRYSTAL)) then
player:startEvent(0x0055); -- New standard dialog after ZM12
else
player:startEvent(0x002b); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0051 and option == 1) then
player:setVar("ZilartStatus",1);
elseif(csid == 0x0053) then
player:setVar("ZilartStatus",2);
player:delKeyItem(SCRAP_OF_PAPYRUS);
player:addKeyItem(CERULEAN_CRYSTAL);
player:messageSpecial(KEYITEM_OBTAINED,CERULEAN_CRYSTAL);
end
end; | gpl-3.0 |
nicodinh/cuberite | MCServer/Plugins/Debuggers/Debuggers.lua | 9 | 56552 |
-- Global variables
g_DropSpensersToActivate = {}; -- A list of dispensers and droppers (as {World, X, Y Z} quadruplets) that are to be activated every tick
g_HungerReportTick = 10;
g_ShowFoodStats = false; -- When true, each player's food stats are sent to them every 10 ticks
function Initialize(a_Plugin)
--[[
-- Test multiple hook handlers:
cPluginManager.AddHook(cPluginManager.HOOK_TICK, OnTick1);
cPluginManager.AddHook(cPluginManager.HOOK_TICK, OnTick2);
--]]
local PM = cPluginManager;
PM:AddHook(cPluginManager.HOOK_PLAYER_USING_BLOCK, OnPlayerUsingBlock);
PM:AddHook(cPluginManager.HOOK_PLAYER_USING_ITEM, OnPlayerUsingItem);
PM:AddHook(cPluginManager.HOOK_TAKE_DAMAGE, OnTakeDamage);
PM:AddHook(cPluginManager.HOOK_TICK, OnTick);
PM:AddHook(cPluginManager.HOOK_CHAT, OnChat);
PM:AddHook(cPluginManager.HOOK_PLAYER_RIGHT_CLICKING_ENTITY, OnPlayerRightClickingEntity);
PM:AddHook(cPluginManager.HOOK_WORLD_TICK, OnWorldTick);
PM:AddHook(cPluginManager.HOOK_PLUGINS_LOADED, OnPluginsLoaded);
PM:AddHook(cPluginManager.HOOK_PLAYER_JOINED, OnPlayerJoined);
PM:AddHook(cPluginManager.HOOK_PROJECTILE_HIT_BLOCK, OnProjectileHitBlock);
PM:AddHook(cPluginManager.HOOK_CHUNK_UNLOADING, OnChunkUnloading);
PM:AddHook(cPluginManager.HOOK_WORLD_STARTED, OnWorldStarted);
PM:AddHook(cPluginManager.HOOK_PROJECTILE_HIT_BLOCK, OnProjectileHitBlock);
-- _X: Disabled WECUI manipulation:
-- PM:AddHook(cPluginManager.HOOK_PLUGIN_MESSAGE, OnPluginMessage);
-- _X: Disabled so that the normal operation doesn't interfere with anything
-- PM:AddHook(cPluginManager.HOOK_CHUNK_GENERATED, OnChunkGenerated);
-- Load the InfoReg shared library:
dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua")
-- Bind all the commands:
RegisterPluginInfoCommands();
-- Bind all the console commands:
RegisterPluginInfoConsoleCommands();
a_Plugin:AddWebTab("Debuggers", HandleRequest_Debuggers)
a_Plugin:AddWebTab("StressTest", HandleRequest_StressTest)
-- Enable the following line for BlockArea / Generator interface testing:
-- PluginManager:AddHook(Plugin, cPluginManager.HOOK_CHUNK_GENERATED);
-- TestBlockAreas()
-- TestSQLiteBindings()
-- TestExpatBindings()
TestPluginCalls()
TestBlockAreasString()
TestStringBase64()
-- TestUUIDFromName()
-- TestRankMgr()
TestFileExt()
TestFileLastMod()
TestPluginInterface()
local LastSelfMod = cFile:GetLastModificationTime(a_Plugin:GetLocalFolder() .. "/Debuggers.lua")
LOG("Debuggers.lua last modified on " .. os.date("%Y-%m-%dT%H:%M:%S", LastSelfMod))
--[[
-- Test cCompositeChat usage in console-logging:
LOGINFO(cCompositeChat("This is a simple message with some @2 color formatting @4 and http://links.to .")
:AddSuggestCommandPart("(Suggested command)", "cmd")
:AddRunCommandPart("(Run command)", "cmd")
:SetMessageType(mtInfo)
)
--]]
-- Test the crash in #1889:
cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_RIGHT_CLICKING_ENTITY,
function (a_CBPlayer, a_CBEntity)
a_CBPlayer:GetWorld():DoWithEntityByID( -- This will crash the server in #1889
a_CBEntity:GetUniqueID(),
function(Entity)
LOG("RightClicking an entity, crash #1889 fixed. Entity is a " .. tolua.type(Entity))
end
)
end
)
return true
end;
function TestPluginInterface()
cPluginManager:DoWithPlugin("Core",
function (a_CBPlugin)
if (a_CBPlugin:GetStatus() == cPluginManager.psLoaded) then
LOG("Core plugin was found, version " .. a_CBPlugin:GetVersion())
else
LOG("Core plugin is not loaded")
end
end
)
cPluginManager:ForEachPlugin(
function (a_CBPlugin)
LOG("Plugin in " .. a_CBPlugin:GetFolderName() .. " has an API name of " .. a_CBPlugin:GetName() .. " and status " .. a_CBPlugin:GetStatus())
end
)
end
function TestFileExt()
assert(cFile:ChangeFileExt("fileless_dir/", "new") == "fileless_dir/")
assert(cFile:ChangeFileExt("fileless_dir/", ".new") == "fileless_dir/")
assert(cFile:ChangeFileExt("pathless_file.ext", "new") == "pathless_file.new")
assert(cFile:ChangeFileExt("pathless_file.ext", ".new") == "pathless_file.new")
assert(cFile:ChangeFileExt("path/to/file.ext", "new") == "path/to/file.new")
assert(cFile:ChangeFileExt("path/to/file.ext", ".new") == "path/to/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file", "new") == "path/to.dir/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file", ".new") == "path/to.dir/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file.ext", "new") == "path/to.dir/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file.ext", ".new") == "path/to.dir/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file.longext", "new") == "path/to.dir/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file.longext", ".new") == "path/to.dir/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file.", "new") == "path/to.dir/file.new")
assert(cFile:ChangeFileExt("path/to.dir/file.", ".new") == "path/to.dir/file.new")
end
function TestFileLastMod()
local f = assert(io.open("test.txt", "w"))
f:write("test")
f:close()
local filetime = cFile:GetLastModificationTime("test.txt")
local ostime = os.time()
LOG("file time: " .. filetime .. ", OS time: " .. ostime .. ", difference: " .. ostime - filetime)
end
function TestPluginCalls()
-- In order to test the inter-plugin communication, we're going to call Core's ReturnColorFromChar() function
-- It is a rather simple function that doesn't need any tables as its params and returns a value, too
-- Note the signature: function ReturnColorFromChar( Split, char ) ... return cChatColog.Gray ... end
-- The Split parameter should be a table, but it is not used in that function anyway,
-- so we can get away with passing nil to it.
LOG("Debuggers: Calling NoSuchPlugin.FnName()...")
cPluginManager:CallPlugin("NoSuchPlugin", "FnName", "SomeParam")
LOG("Debuggers: Calling Core.NoSuchFunction()...")
cPluginManager:CallPlugin("Core", "NoSuchFunction", "SomeParam")
LOG("Debuggers: Calling Core.ReturnColorFromChar(..., \"8\")...")
local Gray = cPluginManager:CallPlugin("Core", "ReturnColorFromChar", "split", "8")
if (Gray ~= cChatColor.Gray) then
LOGWARNING("Debuggers: Call failed, exp " .. cChatColor.Gray .. ", got " .. (Gray or "<nil>"))
else
LOG("Debuggers: Call succeeded")
end
LOG("Debuggers: Inter-plugin calls done.")
end
function TestBlockAreas()
LOG("Testing block areas...");
-- Debug block area merging:
local BA1 = cBlockArea();
local BA2 = cBlockArea();
if (BA1:LoadFromSchematicFile("schematics/test.schematic")) then
if (BA2:LoadFromSchematicFile("schematics/fountain.schematic")) then
BA2:SetRelBlockType(0, 0, 0, E_BLOCK_LAPIS_BLOCK);
BA2:SetRelBlockType(1, 0, 0, E_BLOCK_LAPIS_BLOCK);
BA2:SetRelBlockType(2, 0, 0, E_BLOCK_LAPIS_BLOCK);
BA1:Merge(BA2, 1, 10, 1, cBlockArea.msImprint);
BA1:SaveToSchematicFile("schematics/merge.schematic");
end
else
BA1:Create(16, 16, 16);
end
-- Debug block area cuboid filling:
BA1:FillRelCuboid(2, 9, 2, 8, 2, 8, cBlockArea.baTypes, E_BLOCK_GOLD_BLOCK);
BA1:RelLine(2, 2, 2, 9, 8, 8, cBlockArea.baTypes or cBlockArea.baMetas, E_BLOCK_SAPLING, E_META_SAPLING_BIRCH);
BA1:SaveToSchematicFile("schematics/fillrel.schematic");
-- Debug block area mirroring:
if (BA1:LoadFromSchematicFile("schematics/lt.schematic")) then
BA1:MirrorXYNoMeta();
BA1:SaveToSchematicFile("schematics/lt_XY.schematic");
BA1:MirrorXYNoMeta();
BA1:SaveToSchematicFile("schematics/lt_XY2.schematic");
BA1:MirrorXZNoMeta();
BA1:SaveToSchematicFile("schematics/lt_XZ.schematic");
BA1:MirrorXZNoMeta();
BA1:SaveToSchematicFile("schematics/lt_XZ2.schematic");
BA1:MirrorYZNoMeta();
BA1:SaveToSchematicFile("schematics/lt_YZ.schematic");
BA1:MirrorYZNoMeta();
BA1:SaveToSchematicFile("schematics/lt_YZ2.schematic");
end
-- Debug block area rotation:
if (BA1:LoadFromSchematicFile("schematics/rot.schematic")) then
BA1:RotateCWNoMeta();
BA1:SaveToSchematicFile("schematics/rot1.schematic");
BA1:RotateCWNoMeta();
BA1:SaveToSchematicFile("schematics/rot2.schematic");
BA1:RotateCWNoMeta();
BA1:SaveToSchematicFile("schematics/rot3.schematic");
BA1:RotateCWNoMeta();
BA1:SaveToSchematicFile("schematics/rot4.schematic");
end
-- Debug block area rotation:
if (BA1:LoadFromSchematicFile("schematics/rotm.schematic")) then
BA1:RotateCCW();
BA1:SaveToSchematicFile("schematics/rotm1.schematic");
BA1:RotateCCW();
BA1:SaveToSchematicFile("schematics/rotm2.schematic");
BA1:RotateCCW();
BA1:SaveToSchematicFile("schematics/rotm3.schematic");
BA1:RotateCCW();
BA1:SaveToSchematicFile("schematics/rotm4.schematic");
end
-- Debug block area mirroring:
if (BA1:LoadFromSchematicFile("schematics/ltm.schematic")) then
BA1:MirrorXY();
BA1:SaveToSchematicFile("schematics/ltm_XY.schematic");
BA1:MirrorXY();
BA1:SaveToSchematicFile("schematics/ltm_XY2.schematic");
BA1:MirrorXZ();
BA1:SaveToSchematicFile("schematics/ltm_XZ.schematic");
BA1:MirrorXZ();
BA1:SaveToSchematicFile("schematics/ltm_XZ2.schematic");
BA1:MirrorYZ();
BA1:SaveToSchematicFile("schematics/ltm_YZ.schematic");
BA1:MirrorYZ();
BA1:SaveToSchematicFile("schematics/ltm_YZ2.schematic");
end
LOG("Block areas test ended");
end
function TestBlockAreasString()
-- Write one area to string, then to file:
local BA1 = cBlockArea()
BA1:Create(5, 5, 5, cBlockArea.baTypes + cBlockArea.baMetas)
BA1:Fill(cBlockArea.baTypes, E_BLOCK_DIAMOND_BLOCK)
BA1:FillRelCuboid(1, 3, 1, 3, 1, 3, cBlockArea.baTypes, E_BLOCK_GOLD_BLOCK)
local Data = BA1:SaveToSchematicString()
if ((type(Data) ~= "string") or (Data == "")) then
LOG("Cannot save schematic to string")
return
end
cFile:CreateFolder("schematics")
local f = io.open("schematics/StringTest.schematic", "wb")
f:write(Data)
f:close()
-- Load a second area from that file:
local BA2 = cBlockArea()
if not(BA2:LoadFromSchematicFile("schematics/StringTest.schematic")) then
LOG("Cannot read schematic from string test file")
return
end
BA2:Clear()
-- Load another area from a string in that file:
f = io.open("schematics/StringTest.schematic", "rb")
Data = f:read("*all")
if not(BA2:LoadFromSchematicString(Data)) then
LOG("Cannot load schematic from string")
end
end
function TestStringBase64()
-- Create a binary string:
local s = ""
for i = 0, 255 do
s = s .. string.char(i)
end
-- Roundtrip through Base64:
local Base64 = Base64Encode(s)
local UnBase64 = Base64Decode(Base64)
assert(UnBase64 == s)
end
function TestUUIDFromName()
LOG("Testing UUID-from-Name resolution...")
-- Test by querying a few existing names, along with a non-existent one:
local PlayerNames =
{
"xoft",
"aloe_vera",
"nonexistent_player",
}
-- WARNING: Blocking operation! DO NOT USE IN TICK THREAD!
local UUIDs = cMojangAPI:GetUUIDsFromPlayerNames(PlayerNames)
-- Log the results:
for _, name in ipairs(PlayerNames) do
local UUID = UUIDs[name]
if (UUID == nil) then
LOG(" UUID(" .. name .. ") not found.")
else
LOG(" UUID(" .. name .. ") = \"" .. UUID .. "\"")
end
end
-- Test once more with the same players, valid-only. This should go directly from cache, so fast.
LOG("Testing again with the same valid players...")
local ValidPlayerNames =
{
"xoft",
"aloe_vera",
}
UUIDs = cMojangAPI:GetUUIDsFromPlayerNames(ValidPlayerNames);
-- Log the results:
for _, name in ipairs(ValidPlayerNames) do
local UUID = UUIDs[name]
if (UUID == nil) then
LOG(" UUID(" .. name .. ") not found.")
else
LOG(" UUID(" .. name .. ") = \"" .. UUID .. "\"")
end
end
-- Test yet again, cache-only:
LOG("Testing once more, cache only...")
local PlayerNames3 =
{
"xoft",
"aloe_vera",
"notch", -- Valid player name, but not cached (most likely :)
}
UUIDs = cMojangAPI:GetUUIDsFromPlayerNames(PlayerNames3, true)
-- Log the results:
for _, name in ipairs(PlayerNames3) do
local UUID = UUIDs[name]
if (UUID == nil) then
LOG(" UUID(" .. name .. ") not found.")
else
LOG(" UUID(" .. name .. ") = \"" .. UUID .. "\"")
end
end
LOG("UUID-from-Name resolution tests finished.")
LOG("Performing a Name-from-UUID test...")
-- local NameToTest = "aloe_vera"
local NameToTest = "xoft"
local Name = cMojangAPI:GetPlayerNameFromUUID(UUIDs[NameToTest])
LOG("Name(" .. UUIDs[NameToTest] .. ") = '" .. Name .. "', expected '" .. NameToTest .. "'.")
LOG("Name-from-UUID test finished.")
end
function TestRankMgr()
LOG("Testing the rank manager")
cRankManager:AddRank("LuaRank")
cRankManager:AddGroup("LuaTestGroup")
cRankManager:AddGroupToRank("LuaTestGroup", "LuaRank")
cRankManager:AddPermissionToGroup("luaperm", "LuaTestGroup")
end
function TestSQLiteBindings()
LOG("Testing SQLite bindings...");
-- Debug SQLite binding
local TestDB, ErrCode, ErrMsg = sqlite3.open("test.sqlite");
if (TestDB ~= nil) then
local function ShowRow(UserData, NumCols, Values, Names)
assert(UserData == 'UserData');
LOG("New row");
for i = 1, NumCols do
LOG(" " .. Names[i] .. " = " .. Values[i]);
end
return 0;
end
local sql = [=[
CREATE TABLE numbers(num1,num2,str);
INSERT INTO numbers VALUES(1, 11, "ABC");
INSERT INTO numbers VALUES(2, 22, "DEF");
INSERT INTO numbers VALUES(3, 33, "UVW");
INSERT INTO numbers VALUES(4, 44, "XYZ");
SELECT * FROM numbers;
]=]
local Res = TestDB:exec(sql, ShowRow, 'UserData');
if (Res ~= sqlite3.OK) then
LOG("TestDB:exec() failed: " .. Res .. " (" .. TestDB:errmsg() .. ")");
end;
TestDB:close();
else
-- This happens if for example SQLite cannot open the file (eg. a folder with the same name exists)
LOG("SQLite3 failed to open DB! (" .. ErrCode .. ", " .. ErrMsg ..")");
end
LOG("SQLite bindings test ended");
end
function TestExpatBindings()
LOG("Testing Expat bindings...");
-- Debug LuaExpat bindings:
local count = 0
callbacks = {
StartElement = function (parser, name)
LOG("+ " .. string.rep(" ", count) .. name);
count = count + 1;
end,
EndElement = function (parser, name)
count = count - 1;
LOG("- " .. string.rep(" ", count) .. name);
end
}
local p = lxp.new(callbacks);
p:parse("<elem1>\nnext line\nanother line");
p:parse("text\n");
p:parse("<elem2/>\n");
p:parse("more text");
p:parse("</elem1>");
p:parse("\n");
p:parse(); -- finishes the document
p:close(); -- closes the parser
LOG("Expat bindings test ended");
end
function OnUsingBlazeRod(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
-- Magic rod of query: show block types and metas for both neighbors of the pointed face
local Valid, Type, Meta = Player:GetWorld():GetBlockTypeMeta(BlockX, BlockY, BlockZ);
if (Type == E_BLOCK_AIR) then
Player:SendMessage(cChatColor.LightGray .. "Block {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}: air:" .. Meta);
else
local TempItem = cItem(Type, 1, Meta);
Player:SendMessage(cChatColor.LightGray .. "Block {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}: " .. ItemToFullString(TempItem) .. " (" .. Type .. ":" .. Meta .. ")");
end
local X, Y, Z = AddFaceDirection(BlockX, BlockY, BlockZ, BlockFace);
Valid, Type, Meta = Player:GetWorld():GetBlockTypeMeta(X, Y, Z);
if (Type == E_BLOCK_AIR) then
Player:SendMessage(cChatColor.LightGray .. "Block {" .. X .. ", " .. Y .. ", " .. Z .. "}: air:" .. Meta);
else
local TempItem = cItem(Type, 1, Meta);
Player:SendMessage(cChatColor.LightGray .. "Block {" .. X .. ", " .. Y .. ", " .. Z .. "}: " .. ItemToFullString(TempItem) .. " (" .. Type .. ":" .. Meta .. ")");
end
return false;
end
function OnUsingDiamond(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
-- Rclk with a diamond to test block area cropping and expanding
local Area = cBlockArea();
Area:Read(Player:GetWorld(),
BlockX - 19, BlockX + 19,
BlockY - 7, BlockY + 7,
BlockZ - 19, BlockZ + 19
);
LOG("Size before cropping: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
Area:DumpToRawFile("crop0.dat");
Area:Crop(2, 3, 0, 0, 0, 0);
LOG("Size after cropping 1: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
Area:DumpToRawFile("crop1.dat");
Area:Crop(2, 3, 0, 0, 0, 0);
LOG("Size after cropping 2: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
Area:DumpToRawFile("crop2.dat");
Area:Expand(2, 3, 0, 0, 0, 0);
LOG("Size after expanding 1: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
Area:DumpToRawFile("expand1.dat");
Area:Expand(3, 2, 1, 1, 0, 0);
LOG("Size after expanding 2: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
Area:DumpToRawFile("expand2.dat");
Area:Crop(0, 0, 0, 0, 3, 2);
LOG("Size after cropping 3: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
Area:DumpToRawFile("crop3.dat");
Area:Crop(0, 0, 3, 2, 0, 0);
LOG("Size after cropping 4: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
Area:DumpToRawFile("crop4.dat");
LOG("Crop test done");
Player:SendMessage("Crop / expand test done.");
return false;
end
function OnUsingEyeOfEnder(Player, BlockX, BlockY, BlockZ)
-- Rclk with an eye of ender places a predefined schematic at the cursor
local Area = cBlockArea();
if not(Area:LoadFromSchematicFile("schematics/test.schematic")) then
LOG("Loading failed");
return false;
end
LOG("Schematic loaded, placing now.");
Area:Write(Player:GetWorld(), BlockX, BlockY, BlockZ);
LOG("Done.");
return false;
end
function OnUsingEnderPearl(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
-- Rclk with an ender pearl saves a predefined area around the cursor into a .schematic file. Also tests area copying
local Area = cBlockArea();
if not(Area:Read(Player:GetWorld(),
BlockX - 8, BlockX + 8, BlockY - 8, BlockY + 8, BlockZ - 8, BlockZ + 8)
) then
LOG("LUA: Area couldn't be read");
return false;
end
LOG("LUA: Area read, copying now.");
local Area2 = cBlockArea();
Area2:CopyFrom(Area);
LOG("LUA: Copied, now saving.");
if not(Area2:SaveToSchematicFile("schematics/test.schematic")) then
LOG("LUA: Cannot save schematic file.");
return false;
end
LOG("LUA: Done.");
return false;
end
function OnUsingRedstoneTorch(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
-- Redstone torch activates a rapid dispenser / dropper discharge (at every tick):
local BlockType = Player:GetWorld():GetBlock(BlockX, BlockY, BlockZ);
if (BlockType == E_BLOCK_DISPENSER) then
table.insert(g_DropSpensersToActivate, {World = Player:GetWorld(), x = BlockX, y = BlockY, z = BlockZ});
Player:SendMessage("Dispenser at {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "} discharging");
return true;
elseif (BlockType == E_BLOCK_DROPPER) then
table.insert(g_DropSpensersToActivate, {World = Player:GetWorld(), x = BlockX, y = BlockY, z = BlockZ});
Player:SendMessage("Dropper at {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "} discharging");
return true;
else
Player:SendMessage("Neither a dispenser nor a dropper at {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}: " .. BlockType);
end
return false;
end
function OnPlayerUsingItem(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
-- dont check if the direction is in the air
if (BlockFace == BLOCK_FACE_NONE) then
return false
end
local HeldItem = Player:GetEquippedItem();
local HeldItemType = HeldItem.m_ItemType;
if (HeldItemType == E_ITEM_STICK) then
-- Magic sTick of ticking: set the pointed block for ticking at the next tick
Player:SendMessage(cChatColor.LightGray .. "Setting next block tick to {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}")
Player:GetWorld():SetNextBlockTick(BlockX, BlockY, BlockZ);
return true
elseif (HeldItemType == E_ITEM_BLAZE_ROD) then
return OnUsingBlazeRod(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
elseif (HeldItemType == E_ITEM_DIAMOND) then
return OnUsingDiamond(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
elseif (HeldItemType == E_ITEM_EYE_OF_ENDER) then
return OnUsingEyeOfEnder(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
elseif (HeldItemType == E_ITEM_ENDER_PEARL) then
return OnUsingEnderPearl(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
end
return false;
end
function OnPlayerUsingBlock(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ, BlockType, BlockMeta)
-- dont check if the direction is in the air
if (BlockFace == BLOCK_FACE_NONE) then
return false
end
local HeldItem = Player:GetEquippedItem();
local HeldItemType = HeldItem.m_ItemType;
if (HeldItemType == E_BLOCK_REDSTONE_TORCH_ON) then
return OnUsingRedstoneTorch(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
end
end
function OnTakeDamage(Receiver, TDI)
-- Receiver is cPawn
-- TDI is TakeDamageInfo
-- LOG(Receiver:GetClass() .. " was dealt " .. DamageTypeToString(TDI.DamageType) .. " damage: Raw " .. TDI.RawDamage .. ", Final " .. TDI.FinalDamage .. " (" .. (TDI.RawDamage - TDI.FinalDamage) .. " covered by armor)");
return false;
end
function OnTick1()
-- For testing multiple hook handlers per plugin
LOGINFO("Tick1");
end
function OnTick2()
-- For testing multiple hook handlers per plugin
LOGINFO("Tick2");
end
--- When set to a positive number, the following OnTick() will perform GC and decrease until 0 again
GCOnTick = 0;
function OnTick()
-- Activate all dropspensers in the g_DropSpensersToActivate list:
local ActivateDrSp = function(DropSpenser)
if (DropSpenser:GetContents():GetFirstUsedSlot() == -1) then
return true;
end
DropSpenser:Activate();
return false;
end
-- Walk the list backwards, because we're removing some items
local idx = #g_DropSpensersToActivate;
for i = idx, 1, -1 do
local DrSp = g_DropSpensersToActivate[i];
if not(DrSp.World:DoWithDropSpenserAt(DrSp.x, DrSp.y, DrSp.z, ActivateDrSp)) then
table.remove(g_DropSpensersToActivate, i);
end
end
-- If GCOnTick > 0, do a garbage-collect and decrease by one
if (GCOnTick > 0) then
collectgarbage();
GCOnTick = GCOnTick - 1;
end
return false;
end
function OnWorldTick(a_World, a_Dt)
-- Report food stats, if switched on:
local Tick = a_World:GetWorldAge();
if (not(g_ShowFoodStats) or (math.mod(Tick, 10) ~= 0)) then
return false;
end
a_World:ForEachPlayer(
function(a_Player)
a_Player:SendMessage(
tostring(Tick / 10) ..
" > FS: fl " .. a_Player:GetFoodLevel() ..
"; sat " .. a_Player:GetFoodSaturationLevel() ..
"; exh " .. a_Player:GetFoodExhaustionLevel()
);
end
);
end
function OnChat(a_Player, a_Message)
return false, "blabla " .. a_Message;
end
function OnPlayerRightClickingEntity(a_Player, a_Entity)
LOG("Player " .. a_Player:GetName() .. " right-clicking entity ID " .. a_Entity:GetUniqueID() .. ", a " .. a_Entity:GetClass());
return false;
end
function OnPluginsLoaded()
LOG("All plugins loaded");
end
function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc)
-- Get the topmost block coord:
local Height = a_ChunkDesc:GetHeight(0, 0);
-- Create a sign there:
a_ChunkDesc:SetBlockTypeMeta(0, Height + 1, 0, E_BLOCK_SIGN_POST, 0);
local BlockEntity = a_ChunkDesc:GetBlockEntity(0, Height + 1, 0);
if (BlockEntity ~= nil) then
local SignEntity = tolua.cast(BlockEntity, "cSignEntity");
SignEntity:SetLines("Chunk:", tonumber(a_ChunkX) .. ", " .. tonumber(a_ChunkZ), "", "(Debuggers)");
end
-- Update the heightmap:
a_ChunkDesc:SetHeight(0, 0, Height + 1);
end
-- Function "round" copied from http://lua-users.org/wiki/SimpleRound
function round(num, idp)
local mult = 10^(idp or 0)
if num >= 0 then return math.floor(num * mult + 0.5) / mult
else return math.ceil(num * mult - 0.5) / mult end
end
function HandleNickCmd(Split, Player)
if (Split[2] == nil) then
Player:SendMessage("Usage: /nick [CustomName]");
return true;
end
Player:SetCustomName(Split[2]);
Player:SendMessageSuccess("Custom name setted to " .. Player:GetCustomName() .. "!")
return true
end
function HandleListEntitiesCmd(Split, Player)
local NumEntities = 0;
local ListEntity = function(Entity)
if (Entity:IsDestroyed()) then
-- The entity has already been destroyed, don't list it
return false;
end;
local cls = Entity:GetClass();
Player:SendMessage(" " .. Entity:GetUniqueID() .. ": " .. cls .. " {" .. round(Entity:GetPosX(), 2) .. ", " .. round(Entity:GetPosY(), 2) .. ", " .. round(Entity:GetPosZ(), 2) .."}");
if (cls == "cPickup") then
local Pickup = Entity;
tolua.cast(Pickup, "cPickup");
Player:SendMessage(" Age: " .. Pickup:GetAge() .. ", IsCollected: " .. tostring(Pickup:IsCollected()));
end
NumEntities = NumEntities + 1;
end
Player:SendMessage("Listing all entities...");
Player:GetWorld():ForEachEntity(ListEntity);
Player:SendMessage("List finished, " .. NumEntities .. " entities listed");
return true;
end
function HandleKillEntitiesCmd(Split, Player)
local NumEntities = 0;
local KillEntity = function(Entity)
-- kill everything except for players:
if (Entity:GetEntityType() ~= cEntity.etPlayer) then
Entity:Destroy();
NumEntities = NumEntities + 1;
end;
end
Player:SendMessage("Killing all entities...");
Player:GetWorld():ForEachEntity(KillEntity);
Player:SendMessage("Killed " .. NumEntities .. " entities.");
return true;
end
function HandleWoolCmd(Split, Player)
local Wool = cItem(E_BLOCK_WOOL, 1, E_META_WOOL_BLUE);
Player:GetInventory():SetArmorSlot(0, Wool);
Player:GetInventory():SetArmorSlot(1, Wool);
Player:GetInventory():SetArmorSlot(2, Wool);
Player:GetInventory():SetArmorSlot(3, Wool);
Player:SendMessage("You have been bluewooled :)");
return true;
end
function HandleTestWndCmd(a_Split, a_Player)
local WindowType = cWindow.wtHopper;
local WindowSizeX = 5;
local WindowSizeY = 1;
if (#a_Split == 4) then
WindowType = tonumber(a_Split[2]);
WindowSizeX = tonumber(a_Split[3]);
WindowSizeY = tonumber(a_Split[4]);
elseif (#a_Split ~= 1) then
a_Player:SendMessage("Usage: /testwnd [WindowType WindowSizeX WindowSizeY]");
return true;
end
-- Test out the OnClosing callback's ability to refuse to close the window
local attempt = 1;
local OnClosing = function(Window, Player, CanRefuse)
Player:SendMessage("Window closing attempt #" .. attempt .. "; CanRefuse = " .. tostring(CanRefuse));
attempt = attempt + 1;
return CanRefuse and (attempt <= 3); -- refuse twice, then allow, unless CanRefuse is set to true
end
-- Log the slot changes
local OnSlotChanged = function(Window, SlotNum)
LOG("Window \"" .. Window:GetWindowTitle() .. "\" slot " .. SlotNum .. " changed.");
end
local Window = cLuaWindow(WindowType, WindowSizeX, WindowSizeY, "TestWnd");
local Item2 = cItem(E_ITEM_DIAMOND_SWORD, 1, 0, "1=1");
local Item3 = cItem(E_ITEM_DIAMOND_SHOVEL);
Item3.m_Enchantments:SetLevel(cEnchantments.enchUnbreaking, 4);
local Item4 = cItem(Item3); -- Copy
Item4.m_Enchantments:SetLevel(cEnchantments.enchEfficiency, 3); -- Add enchantment
Item4.m_Enchantments:SetLevel(cEnchantments.enchUnbreaking, 5); -- Overwrite existing level
local Item5 = cItem(E_ITEM_DIAMOND_CHESTPLATE, 1, 0, "thorns=1;unbreaking=3");
Window:SetSlot(a_Player, 0, cItem(E_ITEM_DIAMOND, 64));
Window:SetSlot(a_Player, 1, Item2);
Window:SetSlot(a_Player, 2, Item3);
Window:SetSlot(a_Player, 3, Item4);
Window:SetSlot(a_Player, 4, Item5);
Window:SetOnClosing(OnClosing);
Window:SetOnSlotChanged(OnSlotChanged);
a_Player:OpenWindow(Window);
-- To make sure that the object has the correct life-management in Lua,
-- let's garbage-collect in the following few ticks
GCOnTick = 10;
return true;
end
function HandleGCCmd(a_Split, a_Player)
collectgarbage();
return true;
end
function HandleFastCmd(a_Split, a_Player)
if (a_Player:GetNormalMaxSpeed() <= 0.11) then
-- The player has normal speed, set double speed:
a_Player:SetNormalMaxSpeed(0.2);
a_Player:SendMessage("You are now fast");
else
-- The player has fast speed, set normal speed:
a_Player:SetNormalMaxSpeed(0.1);
a_Player:SendMessage("Back to normal speed");
end
return true;
end
function HandleDashCmd(a_Split, a_Player)
if (a_Player:GetSprintingMaxSpeed() <= 0.14) then
-- The player has normal sprinting speed, set double Sprintingspeed:
a_Player:SetSprintingMaxSpeed(0.4);
a_Player:SendMessage("You can now sprint very fast");
else
-- The player has fast sprinting speed, set normal sprinting speed:
a_Player:SetSprintingMaxSpeed(0.13);
a_Player:SendMessage("Back to normal sprinting");
end
return true;
end;
function HandleHungerCmd(a_Split, a_Player)
a_Player:SendMessage("FoodLevel: " .. a_Player:GetFoodLevel());
a_Player:SendMessage("FoodSaturationLevel: " .. a_Player:GetFoodSaturationLevel());
a_Player:SendMessage("FoodTickTimer: " .. a_Player:GetFoodTickTimer());
a_Player:SendMessage("FoodExhaustionLevel: " .. a_Player:GetFoodExhaustionLevel());
a_Player:SendMessage("FoodPoisonedTicksRemaining: " .. a_Player:GetFoodPoisonedTicksRemaining());
return true;
end
function HandlePoisonCmd(a_Split, a_Player)
a_Player:FoodPoison(15 * 20);
return true;
end
function HandleStarveCmd(a_Split, a_Player)
a_Player:SetFoodLevel(0);
a_Player:SendMessage("You are now starving");
return true;
end
function HandleFoodLevelCmd(a_Split, a_Player)
if (#a_Split ~= 2) then
a_Player:SendMessage("Missing an argument: the food level to set");
return true;
end
a_Player:SetFoodLevel(tonumber(a_Split[2]));
a_Player:SetFoodSaturationLevel(5);
a_Player:SetFoodExhaustionLevel(0);
a_Player:SendMessage(
"Food level set to " .. a_Player:GetFoodLevel() ..
", saturation reset to " .. a_Player:GetFoodSaturationLevel() ..
" and exhaustion reset to " .. a_Player:GetFoodExhaustionLevel()
);
return true;
end
function HandleSpideyCmd(a_Split, a_Player)
-- Place a line of cobwebs from the player's eyes until non-air block, in the line-of-sight of the player
local World = a_Player:GetWorld();
local Callbacks = {
OnNextBlock = function(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta)
if (a_BlockType ~= E_BLOCK_AIR) then
-- abort the trace
return true;
end
World:SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_COBWEB, 0);
end
};
local EyePos = a_Player:GetEyePosition();
local LookVector = a_Player:GetLookVector();
LookVector:Normalize();
-- Start cca 2 blocks away from the eyes
local Start = EyePos + LookVector + LookVector;
local End = EyePos + LookVector * 50;
cLineBlockTracer.Trace(World, Callbacks, Start.x, Start.y, Start.z, End.x, End.y, End.z);
return true;
end
function HandleEnchCmd(a_Split, a_Player)
local Wnd = cLuaWindow(cWindow.wtEnchantment, 1, 1, "Ench");
a_Player:OpenWindow(Wnd);
Wnd:SetProperty(0, 10);
Wnd:SetProperty(1, 15);
Wnd:SetProperty(2, 25);
return true;
end
function HandleFoodStatsCmd(a_Split, a_Player)
g_ShowFoodStats = not(g_ShowFoodStats);
return true;
end
function HandleArrowCmd(a_Split, a_Player)
local World = a_Player:GetWorld();
local Pos = a_Player:GetEyePosition();
local Speed = a_Player:GetLookVector();
Speed:Normalize();
Pos = Pos + Speed;
World:CreateProjectile(Pos.x, Pos.y, Pos.z, cProjectileEntity.pkArrow, a_Player, Speed * 10);
return true;
end
function HandleFireballCmd(a_Split, a_Player)
local World = a_Player:GetWorld();
local Pos = a_Player:GetEyePosition();
local Speed = a_Player:GetLookVector();
Speed:Normalize();
Pos = Pos + Speed * 2;
World:CreateProjectile(Pos.x, Pos.y, Pos.z, cProjectileEntity.pkGhastFireball, a_Player, Speed * 10);
return true;
end
function HandleAddExperience(a_Split, a_Player)
a_Player:DeltaExperience(200);
return true;
end
function HandleRemoveXp(a_Split, a_Player)
a_Player:SetCurrentExperience(0);
return true;
end
function HandleFill(a_Split, a_Player)
local World = a_Player:GetWorld();
local ChunkX = a_Player:GetChunkX();
local ChunkZ = a_Player:GetChunkZ();
World:ForEachBlockEntityInChunk(ChunkX, ChunkZ,
function(a_BlockEntity)
local BlockType = a_BlockEntity:GetBlockType();
if (
(BlockType == E_BLOCK_CHEST) or
(BlockType == E_BLOCK_DISPENSER) or
(BlockType == E_BLOCK_DROPPER) or
(BlockType == E_BLOCK_FURNACE) or
(BlockType == E_BLOCK_HOPPER)
) then
-- This block entity has items (inherits from cBlockEntityWithItems), fill it:
-- Note that we're not touching lit furnaces, don't wanna mess them up
local EntityWithItems = tolua.cast(a_BlockEntity, "cBlockEntityWithItems");
local ItemGrid = EntityWithItems:GetContents();
local NumSlots = ItemGrid:GetNumSlots();
local ItemToSet = cItem(E_ITEM_GOLD_NUGGET);
for i = 0, NumSlots - 1 do
if (ItemGrid:GetSlot(i):IsEmpty()) then
ItemGrid:SetSlot(i, ItemToSet);
end
end
end
end
);
return true;
end
function HandleFurnaceRecipe(a_Split, a_Player)
local HeldItem = a_Player:GetEquippedItem();
local Out, NumTicks, In = cRoot:GetFurnaceRecipe(HeldItem);
if (Out ~= nil) then
a_Player:SendMessage(
"Furnace turns " .. ItemToFullString(In) ..
" to " .. ItemToFullString(Out) ..
" in " .. NumTicks .. " ticks (" ..
tostring(NumTicks / 20) .. " seconds)."
);
else
a_Player:SendMessage("There is no furnace recipe that would smelt " .. ItemToString(HeldItem));
end
return true;
end
function HandleFurnaceFuel(a_Split, a_Player)
local HeldItem = a_Player:GetEquippedItem();
local NumTicks = cRoot:GetFurnaceFuelBurnTime(HeldItem);
if (NumTicks > 0) then
a_Player:SendMessage(
ItemToFullString(HeldItem) .. " would power a furnace for " .. NumTicks ..
" ticks (" .. tostring(NumTicks / 20) .. " seconds)."
);
else
a_Player:SendMessage(ItemToString(HeldItem) .. " will not power furnaces.");
end
return true;
end
function HandleSched(a_Split, a_Player)
local World = a_Player:GetWorld()
-- Schedule a broadcast of a countdown message:
for i = 1, 10 do
World:ScheduleTask(i * 20,
function(a_World)
a_World:BroadcastChat("Countdown: " .. 11 - i)
end
)
end
-- Schedule a broadcast of the final message and a note to the originating player
-- Note that we CANNOT use the a_Player in the callback - what if the player disconnected?
-- Therefore we store the player's EntityID
local PlayerID = a_Player:GetUniqueID()
World:ScheduleTask(220,
function(a_World)
a_World:BroadcastChat("Countdown: BOOM")
a_World:DoWithEntityByID(PlayerID,
function(a_Entity)
if (a_Entity:IsPlayer()) then
-- Although unlikely, it is possible that this player is not the originating player
-- However, I leave this as an excercise to you to fix this "bug"
local Player = tolua.cast(a_Entity, "cPlayer")
Player:SendMessage("Countdown finished")
end
end
)
end
)
return true
end
function HandleRMItem(a_Split, a_Player)
-- Check params:
if (a_Split[2] == nil) then
a_Player:SendMessage("Usage: /rmitem <Item> [Count]")
return true
end
-- Parse the item type:
local Item = cItem()
if (not StringToItem(a_Split[2], Item)) then
a_Player:SendMessageFailure(a_Split[2] .. " isn't a valid item")
return true
end
-- Parse the optional item count
if (a_Split[3] ~= nil) then
local Count = tonumber(a_Split[3])
if (Count == nil) then
a_Player:SendMessageFailure(a_Split[3] .. " isn't a valid number")
return true
end
Item.m_ItemCount = Count
end
-- Remove the item:
local NumRemovedItems = a_Player:GetInventory():RemoveItem(Item)
a_Player:SendMessageSuccess("Removed " .. NumRemovedItems .. " Items!")
return true
end
function HandleRequest_Debuggers(a_Request)
local FolderContents = cFile:GetFolderContents("./");
return "<p>The following objects have been returned by cFile:GetFolderContents():<ul><li>" .. table.concat(FolderContents, "</li><li>") .. "</li></ul></p>";
end
local g_Counter = 0
local g_JavaScript =
[[
<script>
function createXHR()
{
var request = false;
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2)
{
try
{
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3)
{
try
{
request = new XMLHttpRequest();
}
catch (err1)
{
request = false;
}
}
}
return request;
}
function RefreshCounter()
{
var xhr = createXHR();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
document.getElementById("cnt").innerHTML = xhr.responseText;
}
};
xhr.open("POST", "/~webadmin/Debuggers/StressTest", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("counter=true");
}
setInterval(RefreshCounter, 10)
</script>
]]
function HandleRequest_StressTest(a_Request)
if (a_Request.PostParams["counter"]) then
g_Counter = g_Counter + 1
return tostring(g_Counter)
end
return g_JavaScript .. "<p>The counter below should be reloading as fast as possible</p><div id='cnt'>0</div>"
end
function OnPluginMessage(a_Client, a_Channel, a_Message)
LOGINFO("Received a plugin message from client " .. a_Client:GetUsername() .. ": channel '" .. a_Channel .. "', message '" .. a_Message .. "'");
if (a_Channel == "REGISTER") then
if (a_Message:find("WECUI")) then
-- The client has WorldEditCUI mod installed, test the comm by sending a few WECUI messages:
--[[
WECUI messages have the following generic format:
<shape>|<params>
If shape is p (cuboid selection), the params are sent individually for each corner click and have the following format:
<point-index>|<x>|<y>|<z>|<volume>
point-index is 0 or 1 (lclk / rclk)
volume is the 3D volume of the current cuboid selected (all three coords' deltas multiplied), including the edge blocks; -1 if N/A
--]]
-- Select a 51 * 51 * 51 block cuboid:
a_Client:SendPluginMessage("WECUI", "p|0|50|50|50|-1");
a_Client:SendPluginMessage("WECUI", "p|1|100|100|100|132651"); -- 132651 = 51 * 51 * 51
end
end
end
function HandleChunkStay(a_Split, a_Player)
-- As an example of using ChunkStay, this call will load 3x3 chunks around the specified chunk coords,
-- then build an obsidian pillar in the middle of each one.
-- Once complete, the player will be teleported to the middle pillar
if (#a_Split ~= 3) then
a_Player:SendMessageInfo("Usage: /cs <ChunkX> <ChunkZ>")
return true
end
local ChunkX = tonumber(a_Split[2])
local ChunkZ = tonumber(a_Split[3])
if ((ChunkX == nil) or (ChunkZ == nil)) then
a_Player:SendMessageFailure("Invalid chunk coords.")
return true
end
local World = a_Player:GetWorld()
local PlayerID = a_Player:GetUniqueID()
a_Player:SendMessageInfo("Loading chunks, stand by...");
-- Set the wanted chunks:
local Chunks = {}
for z = -1, 1 do for x = -1, 1 do
table.insert(Chunks, {ChunkX + x, ChunkZ + z})
end end
-- The function that is called when all chunks are available
-- Will perform the actual action with all those chunks
-- Note that the player needs to be referenced using their EntityID - in case they disconnect before the chunks load
local OnAllChunksAvailable = function()
LOGINFO("ChunkStay all chunks now available")
-- Build something on the neighboring chunks, to verify:
for z = -1, 1 do for x = -1, 1 do
local BlockX = (ChunkX + x) * 16 + 8
local BlockZ = (ChunkZ + z) * 16 + 8
for y = 20, 80 do
World:SetBlock(BlockX, y, BlockZ, E_BLOCK_OBSIDIAN, 0)
end
end end
-- Teleport the player there for visual inspection:
World:DoWithEntityByID(PlayerID,
function (a_CallbackPlayer)
a_CallbackPlayer:TeleportToCoords(ChunkX * 16 + 8, 85, ChunkZ * 16 + 8)
a_CallbackPlayer:SendMessageSuccess("ChunkStay fully available")
end
)
end
-- This function will be called for each chunk that is made available
-- Note that the player needs to be referenced using their EntityID - in case they disconnect before the chunks load
local OnChunkAvailable = function(a_ChunkX, a_ChunkZ)
LOGINFO("ChunkStay now has chunk [" .. a_ChunkX .. ", " .. a_ChunkZ .. "]")
World:DoWithEntityByID(PlayerID,
function (a_CallbackPlayer)
a_CallbackPlayer:SendMessageInfo("ChunkStay now has chunk [" .. a_ChunkX .. ", " .. a_ChunkZ .. "]")
end
)
end
-- Process the ChunkStay:
World:ChunkStay(Chunks, OnChunkAvailable, OnAllChunksAvailable)
return true
end
function HandleCompo(a_Split, a_Player)
-- Send one composite message to self:
local msg = cCompositeChat()
msg:AddTextPart("Hello! ", "b@e") -- bold yellow
msg:AddUrlPart("MCServer", "http://mc-server.org")
msg:AddTextPart(" rules! ")
msg:AddRunCommandPart("Set morning", "/time set 0")
a_Player:SendMessage(msg)
-- Broadcast another one to the world:
local msg2 = cCompositeChat()
msg2:AddSuggestCommandPart(a_Player:GetName(), "/tell " .. a_Player:GetName() .. " ")
msg2:AddTextPart(" knows how to use cCompositeChat!");
a_Player:GetWorld():BroadcastChat(msg2)
return true
end
function HandleSetBiome(a_Split, a_Player)
local Biome = biJungle
local Size = 20
local SplitSize = #a_Split
if (SplitSize > 3) then
a_Player:SendMessage("Too many parameters. Usage: " .. a_Split[1] .. " <BiomeType>")
return true
end
if (SplitSize >= 2) then
Biome = StringToBiome(a_Split[2])
if (Biome == biInvalidBiome) then
a_Player:SendMessage("Unknown biome: '" .. a_Split[2] .. "'. Command ignored.")
return true
end
end
if (SplitSize >= 3) then
Size = tostring(a_Split[3])
if (Size == nil) then
a_Player:SendMessage("Unknown size: '" .. a_Split[3] .. "'. Command ignored.")
return true
end
end
local BlockX = math.floor(a_Player:GetPosX())
local BlockZ = math.floor(a_Player:GetPosZ())
a_Player:GetWorld():SetAreaBiome(BlockX - Size, BlockX + Size, BlockZ - Size, BlockZ + Size, Biome)
a_Player:SendMessage(
"Blocks {" .. (BlockX - Size) .. ", " .. (BlockZ - Size) ..
"} - {" .. (BlockX + Size) .. ", " .. (BlockZ + Size) ..
"} set to biome #" .. tostring(Biome) .. "."
)
return true
end
function HandleWESel(a_Split, a_Player)
-- Check if the selection is a cuboid:
local IsCuboid = cPluginManager:CallPlugin("WorldEdit", "IsPlayerSelectionCuboid")
if (IsCuboid == nil) then
a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, WorldEdit is not loaded"))
return true
elseif (IsCuboid == false) then
a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, the selection is not a cuboid"))
return true
end
-- Get the selection:
local SelCuboid = cCuboid()
local IsSuccess = cPluginManager:CallPlugin("WorldEdit", "GetPlayerCuboidSelection", a_Player, SelCuboid)
if not(IsSuccess) then
a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, WorldEdit reported failure while getting current selection"))
return true
end
-- Adjust the selection:
local NumBlocks = tonumber(a_Split[2] or "1") or 1
SelCuboid:Expand(NumBlocks, NumBlocks, 0, 0, NumBlocks, NumBlocks)
-- Set the selection:
IsSuccess = cPluginManager:CallPlugin("WorldEdit", "SetPlayerCuboidSelection", a_Player, SelCuboid)
if not(IsSuccess) then
a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, WorldEdit reported failure while setting new selection"))
return true
end
a_Player:SendMessage(cCompositeChat():SetMessageType(mtInformation):AddTextPart("Successfully adjusted the selection by " .. NumBlocks .. " block(s)"))
return true
end
function OnPlayerJoined(a_Player)
-- Test composite chat chaining:
a_Player:SendMessage(cCompositeChat()
:AddTextPart("Hello, ")
:AddUrlPart(a_Player:GetName(), "http://www.mc-server.org", "u@2")
:AddSuggestCommandPart(", and welcome.", "/help", "u")
:AddRunCommandPart(" SetDay", "/time set 0")
)
end
function OnProjectileHitBlock(a_Projectile, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_BlockHitPos)
-- Test projectile hooks by setting the blocks they hit on fire:
local BlockX, BlockY, BlockZ = AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace)
local World = a_Projectile:GetWorld()
World:SetBlock(BlockX, BlockY, BlockZ, E_BLOCK_FIRE, 0)
end
function OnChunkUnloading(a_World, a_ChunkX, a_ChunkZ)
-- Do not let chunk [0, 0] unload, so that it continues ticking [cWorld:SetChunkAlwaysTicked() test]
if ((a_ChunkX == 0) and (a_ChunkZ == 0)) then
return true
end
end
function OnWorldStarted(a_World)
-- Make the chunk [0, 0] in every world keep ticking [cWorld:SetChunkAlwaysTicked() test]
a_World:ChunkStay({{0, 0}}, nil,
function()
-- The chunk is loaded, make it always tick:
a_World:SetChunkAlwaysTicked(0, 0, true)
end
)
end
function OnProjectileHitBlock(a_ProjectileEntity, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_BlockHitPos)
-- This simple test is for testing issue #1326 - simply declaring this hook would crash the server upon call
LOG("Projectile hit block")
LOG(" Projectile EntityID: " .. a_ProjectileEntity:GetUniqueID())
LOG(" Block: {" .. a_BlockX .. ", " .. a_BlockY .. ", " .. a_BlockZ .. "}, face " .. a_BlockFace)
LOG(" HitPos: {" .. a_BlockHitPos.x .. ", " .. a_BlockHitPos.y .. ", " .. a_BlockHitPos.z .. "}")
end
local PossibleItems =
{
cItem(E_ITEM_DIAMOND),
cItem(E_ITEM_GOLD),
cItem(E_ITEM_IRON),
cItem(E_ITEM_DYE, 1, E_META_DYE_BLUE), -- Lapis lazuli
cItem(E_ITEM_COAL),
}
function HandlePickups(a_Split, a_Player)
local PlayerX = a_Player:GetPosX()
local PlayerY = a_Player:GetPosY()
local PlayerZ = a_Player:GetPosZ()
local World = a_Player:GetWorld()
local Range = 12
for x = 0, Range do for z = 0, Range do
local px = PlayerX + x - Range / 2
local pz = PlayerZ + z - Range / 2
local Items = cItems()
Items:Add(PossibleItems[math.random(#PossibleItems)])
World:SpawnItemPickups(Items, px, PlayerY, pz, 0)
end end -- for z, for x
return true
end
function HandlePoof(a_Split, a_Player)
local PlayerPos = Vector3d(a_Player:GetPosition()) -- Create a copy of the position
PlayerPos.y = PlayerPos.y - 1
local Box = cBoundingBox(PlayerPos, 4, 2)
local NumEntities = 0
a_Player:GetWorld():ForEachEntityInBox(Box,
function (a_Entity)
if not(a_Entity:IsPlayer()) then
local AddSpeed = a_Entity:GetPosition() - PlayerPos -- Speed away from the player
a_Entity:AddSpeed(AddSpeed * 32 / (AddSpeed:SqrLength() + 1)) -- The further away, the less speed to add
NumEntities = NumEntities + 1
end
end
)
a_Player:SendMessage("Poof! (" .. NumEntities .. " entities)")
return true
end
-- List of hashing functions to test:
local HashFunctions =
{
{"md5", md5 },
{"cCryptoHash.md5", cCryptoHash.md5 },
{"cCryptoHash.md5HexString", cCryptoHash.md5HexString },
{"cCryptoHash.sha1", cCryptoHash.sha1 },
{"cCryptoHash.sha1HexString", cCryptoHash.sha1HexString },
}
-- List of strings to try hashing:
local HashExamples =
{
"",
"\0",
"test",
}
function HandleConsoleHash(a_Split)
for _, str in ipairs(HashExamples) do
LOG("Hashing string \"" .. str .. "\":")
for _, hash in ipairs(HashFunctions) do
if not(hash[2]) then
LOG("Hash function " .. hash[1] .. " doesn't exist in the API!")
else
LOG(hash[1] .. "() = " .. hash[2](str))
end
end -- for hash - HashFunctions[]
end -- for str - HashExamples[]
return true
end
--- Monitors the state of the "inh" entity-spawning hook
-- if false, the hook is installed before the "inh" command processing
local isInhHookInstalled = false
function HandleConsoleInh(a_Split, a_FullCmd)
-- Check the param:
local kindStr = a_Split[2] or "pkArrow"
local kind = cProjectileEntity[kindStr]
if (kind == nil) then
return true, "There's no projectile kind '" .. kindStr .. "'."
end
-- Get the world to test in:
local world = cRoot:Get():GetDefaultWorld()
if (world == nil) then
return true, "Cannot test inheritance, no default world"
end
-- Install the hook, if needed:
if not(isInhHookInstalled) then
cPluginManager:AddHook(cPluginManager.HOOK_SPAWNING_ENTITY,
function (a_CBWorld, a_CBEntity)
LOG("New entity is spawning:")
LOG(" Lua type: '" .. type(a_CBEntity) .. "'")
LOG(" ToLua type: '" .. tolua.type(a_CBEntity) .. "'")
LOG(" GetEntityType(): '" .. a_CBEntity:GetEntityType() .. "'")
LOG(" GetClass(): '" .. a_CBEntity:GetClass() .. "'")
end
)
isInhHookInstalled = true
end
-- Create the projectile:
LOG("Creating a " .. kindStr .. " projectile in world " .. world:GetName() .. "...")
local msg
world:ChunkStay({{0, 0}},
nil,
function ()
-- Create a projectile at {8, 100, 8}:
local entityID = world:CreateProjectile(8, 100, 8, kind, nil, nil)
if (entityID < 0) then
msg = "Cannot test inheritance, projectile creation failed."
return
end
LOG("Entity created, ID #" .. entityID)
-- Call a function on the newly created entity:
local hasExecutedCallback = false
world:DoWithEntityByID(
entityID,
function (a_CBEntity)
LOG("Projectile created and found using the DoWithEntityByID() callback")
LOG("Lua type: '" .. type(a_CBEntity) .. "'")
LOG("ToLua type: '" .. tolua.type(a_CBEntity) .. "'")
LOG("GetEntityType(): '" .. a_CBEntity:GetEntityType() .. "'")
LOG("GetClass(): '" .. a_CBEntity:GetClass() .. "'")
hasExecutedCallback = true
end
)
if not(hasExecutedCallback) then
msg = "The callback failed to execute"
return
end
msg = "Inheritance test finished"
end
)
return true, msg
end
function HandleConsoleLoadChunk(a_Split)
-- Check params:
local numParams = #a_Split
if (numParams ~= 3) and (numParams ~= 4) then
return true, "Usage: " .. a_Split[1] .. " <ChunkX> <ChunkZ> [<WorldName>]"
end
-- Get the chunk coords:
local chunkX = tonumber(a_Split[2])
if (chunkX == nil) then
return true, "Not a number: '" .. a_Split[2] .. "'"
end
local chunkZ = tonumber(a_Split[3])
if (chunkZ == nil) then
return true, "Not a number: '" .. a_Split[3] .. "'"
end
-- Get the world:
local world
if (a_Split[4] == nil) then
world = cRoot:Get():GetDefaultWorld()
else
world = cRoot:Get():GetWorld(a_Split[4])
if (world == nil) then
return true, "There's no world named '" .. a_Split[4] .. "'."
end
end
-- Queue a ChunkStay for the chunk, log a message when the chunk is loaded:
world:ChunkStay({{chunkX, chunkZ}}, nil,
function()
LOG("Chunk [" .. chunkX .. ", " .. chunkZ .. "] is loaded")
end
)
return true
end
function HandleConsolePrepareChunk(a_Split)
-- Check params:
local numParams = #a_Split
if (numParams ~= 3) and (numParams ~= 4) then
return true, "Usage: " .. a_Split[1] .. " <ChunkX> <ChunkZ> [<WorldName>]"
end
-- Get the chunk coords:
local chunkX = tonumber(a_Split[2])
if (chunkX == nil) then
return true, "Not a number: '" .. a_Split[2] .. "'"
end
local chunkZ = tonumber(a_Split[3])
if (chunkZ == nil) then
return true, "Not a number: '" .. a_Split[3] .. "'"
end
-- Get the world:
local world
if (a_Split[4] == nil) then
world = cRoot:Get():GetDefaultWorld()
else
world = cRoot:Get():GetWorld(a_Split[4])
if (world == nil) then
return true, "There's no world named '" .. a_Split[4] .. "'."
end
end
-- Queue the chunk for preparing, log a message when prepared:
world:PrepareChunk(chunkX, chunkZ,
function(a_CBChunkX, a_CBChunkZ)
LOG("Chunk [" .. chunkX .. ", " .. chunkZ .. "] has been prepared")
end
)
return true
end
function HandleConsoleSchedule(a_Split)
local prev = os.clock()
LOG("Scheduling a task for 2 seconds in the future (current os.clock is " .. prev .. ")")
cRoot:Get():GetDefaultWorld():ScheduleTask(40,
function ()
local current = os.clock()
local diff = current - prev
LOG("Scheduled function is called. Current os.clock is " .. current .. ", difference is " .. diff .. ")")
end
)
return true, "Task scheduled"
end
--- Returns the square of the distance from the specified point to the specified line
local function SqDistPtFromLine(x, y, x1, y1, x2, y2)
local dx = x - x1
local dy = y - y1
local px = x2 - x1
local py = y2 - y1
local ss = px * dx + py * dy
local ds = px * px + py * py
if (ss < 0) then
-- Return sqdistance from point 1
return dx * dx + dy * dy
end
if (ss > ds) then
-- Return sqdistance from point 2
return ((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y))
end
-- Return sqdistance from the line
if ((px * px + py * py) == 0) then
return dx * dx + dy * dy
else
return (py * dx - px * dy) * (py * dx - px * dy) / (px * px + py * py)
end
end
function HandleConsoleTestTracer(a_Split, a_EntireCmd)
-- Check required params:
if not(a_Split[7]) then
return true, "Usage: " .. a_Split[1] .. " <x1> <y1> <z1> <x2> <y2> <z2> [<WorldName>]"
end
local Coords = {}
for i = 1, 6 do
local v = tonumber(a_Split[i + 1])
if not(v) then
return true, "Parameter " .. (i + 1) .. " (" .. tostring(a_Split[i + 1]) .. ") not a number "
end
Coords[i] = v
end
-- Get the world in which to test:
local World
if (a_Split[8]) then
World = cRoot:GetWorld(a_Split[2])
else
World = cRoot:Get():GetDefaultWorld()
end
if not(World) then
return true, "No such world"
end
-- Define the callbacks to use for tracing:
local Callbacks =
{
OnNextBlock = function(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_EntryFace)
LOG(string.format("{%d, %d, %d}: %s", a_BlockX, a_BlockY, a_BlockZ, ItemToString(cItem(a_BlockType, 1, a_BlockMeta))))
end,
OnNextBlockNoData = function(a_BlockX, a_BlockY, a_BlockZ, a_EntryFace)
LOG(string.format("{%d, %d, %d} (no data)", a_BlockX, a_BlockY, a_BlockZ))
end,
OnNoChunk = function()
LOG("Chunk not loaded")
end,
OnNoMoreHits = function()
LOG("Trace finished")
end,
OnOutOfWorld = function()
LOG("Out of world")
end,
OnIntoWorld = function()
LOG("Into world")
end,
}
-- Approximate the chunks needed for the trace by iterating over all chunks and measuring their center's distance from the traced line
local Chunks = {}
local sx = math.floor(Coords[1] / 16)
local sz = math.floor(Coords[3] / 16)
local ex = math.floor(Coords[4] / 16)
local ez = math.floor(Coords[6] / 16)
local sgnx = (sx < ex) and 1 or -1
local sgnz = (sz < ez) and 1 or -1
for z = sz, ez, sgnz do
local ChunkCenterZ = z * 16 + 8
for x = sx, ex, sgnx do
local ChunkCenterX = x * 16 + 8
local sqdist = SqDistPtFromLine(ChunkCenterX, ChunkCenterZ, Coords[1], Coords[3], Coords[4], Coords[6])
if (sqdist <= 128) then
table.insert(Chunks, {x, z})
end
end
end
-- Load the chunks and do the trace once loaded:
World:ChunkStay(Chunks,
nil,
function()
cLineBlockTracer:Trace(World, Callbacks, Coords[1], Coords[2], Coords[3], Coords[4], Coords[5], Coords[6])
end
)
return true
end
function HandleConsoleBBox(a_Split)
local bbox = cBoundingBox(0, 10, 0, 10, 0, 10)
local v1 = Vector3d(1, 1, 1)
local v2 = Vector3d(5, 5, 5)
local v3 = Vector3d(11, 11, 11)
if (bbox:IsInside(v1)) then
LOG("v1 is inside bbox")
else
LOG("v1 is not inside bbox")
end
if (bbox:IsInside(v2)) then
LOG("v2 is inside bbox")
else
LOG("v2 is not inside bbox")
end
if (bbox:IsInside(v3)) then
LOG("v3 is inside bbox")
else
LOG("v3 is not inside bbox")
end
if (bbox:IsInside(v1, v2)) then
LOG("v1*v2 is inside bbox")
else
LOG("v1*v2 is not inside bbox")
end
if (bbox:IsInside(v2, v1)) then
LOG("v2*v1 is inside bbox")
else
LOG("v2*v1 is not inside bbox")
end
if (bbox:IsInside(v1, v3)) then
LOG("v1*v3 is inside bbox")
else
LOG("v1*v3 is not inside bbox")
end
if (bbox:IsInside(v2, v3)) then
LOG("v2*v3 is inside bbox")
else
LOG("v2*v3 is not inside bbox")
end
return true
end
| apache-2.0 |
apletnev/koreader | frontend/ui/elements/screensaver_menu.lua | 3 | 7248 | local Screensaver = require("ui/screensaver")
local _ = require("gettext")
local function screensaverType() return G_reader_settings:readSetting("screensaver_type") end
local function screensaverDelay() return G_reader_settings:readSetting("screensaver_delay") end
local function lastFile()
local lfs = require("libs/libkoreader-lfs")
local last_file = G_reader_settings:readSetting("lastfile")
if last_file and lfs.attributes(last_file, "mode") == "file" then
return last_file
end
end
local function whiteBackground() return G_reader_settings:isTrue("screensaver_white_background") end
local function stretchImages() return G_reader_settings:isTrue("screensaver_stretch_images") end
return {
{
text = _("Use last book's cover as screensaver"),
enabled_func = function() return lastFile() ~= nil end,
checked_func = function()
if screensaverType() == "cover" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_type", "cover")
end
},
{
text = _("Use book status as screensaver"),
enabled_func = function() return lastFile() ~= nil end,
checked_func = function()
if screensaverType() == "bookstatus" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_type", "bookstatus")
end
},
{
text = _("Use random image from folder as screensaver"),
checked_func = function()
if screensaverType() == "random_image" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_type", "random_image")
end
},
{
text = _("Use reading progress as screensaver"),
enabled_func = function() return Screensaver.getReaderProgress ~= nil and lastFile() ~= nil end,
checked_func = function()
if screensaverType() == "readingprogress" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_type", "readingprogress")
end
},
{
text = _("Use message as screensaver"),
checked_func = function()
if screensaverType() == "message" or screensaverType() == nil then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_type", "message")
end
},
{
text = _("Leave screen as it is"),
checked_func = function()
if screensaverType() == "disable" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_type", "disable")
end
},
{
text = _("Settings"),
sub_item_table = {
{
text = _("Screensaver folder"),
callback = function()
Screensaver:chooseFolder()
end,
},
{
text = _("Screensaver message"),
callback = function()
Screensaver:setMessage()
end,
},
{
text = _("White background behind message and images"),
checked_func = whiteBackground,
callback = function()
G_reader_settings:saveSetting("screensaver_white_background", not whiteBackground())
end,
},
{
text = _("Stretch covers and images to fit screen"),
checked_func = stretchImages,
callback = function()
G_reader_settings:saveSetting("screensaver_stretch_images", not stretchImages())
end,
separator = true,
},
{
text = _("Delay when exit from screensaver"),
sub_item_table = {
{
text = _("Disable"),
checked_func = function()
if screensaverDelay() == nil or screensaverDelay() == "disable" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_delay", "disable")
end
},
{
text = _("1 second"),
checked_func = function()
if screensaverDelay() == "1" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_delay", "1")
end
},
{
text = _("3 seconds"),
checked_func = function()
if screensaverDelay() == "3" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_delay", "3")
end
},
{
text = _("5 seconds"),
checked_func = function()
if screensaverDelay() == "5" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_delay", "5")
end
},
{
text = _("Tap to exit screensaver"),
checked_func = function()
if screensaverDelay() == "tap" then
return true
else
return false
end
end,
callback = function()
G_reader_settings:saveSetting("screensaver_delay", "tap")
end
},
}
}
}
}
}
| agpl-3.0 |
kitala1/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Loillie.lua | 16 | 1449 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Loillie
-- @zone 80
-- @pos 78 -8 -23
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 8) then
if(trade:hasItemQty(2528,1) and trade:getItemCount() == 1) then
player:startEvent(0x01F) -- Gifts of Griffon Trade
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0265); -- Default Dialogue
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 == 0x01F) then -- Gifts Of Griffon Trade
player:tradeComplete();
player:setVar("GiftsOfGriffonProg",9);
end
end; | gpl-3.0 |
samgh1230/likwid | src/applications/likwid-pin.lua | 7 | 9275 | #!<PREFIX>/bin/likwid-lua
--[[
* =======================================================================================
*
* Filename: likwid-pin.lua
*
* Description: An application to pin a program including threads
*
* Version: <VERSION>
* Released: <DATE>
*
* Author: Thomas Roehl (tr), thomas.roehl@gmail.com
* Project: likwid
*
* Copyright (C) 2014 Thomas Roehl
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =======================================================================================]]
package.path = '<PREFIX>/share/lua/?.lua;' .. package.path
local likwid = require("likwid")
local function version()
print(string.format("likwid-pin.lua -- Version %d.%d",likwid.version,likwid.release))
end
local function examples()
print("Examples:")
print("There are three possibilities to provide a thread to processor list:")
print("1. Thread list with physical thread IDs")
print("Example: likwid-pin.lua -c 0,4-6 ./myApp")
print("Pins the application to cores 0,4,5 and 6")
print("2. Thread list with logical thread numberings in physical cores first sorted list.")
print("Example usage thread list: likwid-pin.lua -c N:0,4-6 ./myApp")
print("You can pin with the following numberings:")
print("\t2. Logical numbering inside node.\n\t e.g. -c N:0,1,2,3 for the first 4 physical cores of the node")
print("\t3. Logical numbering inside socket.\n\t e.g. -c S0:0-1 for the first 2 physical cores of the socket")
print("\t4. Logical numbering inside last level cache group.\n\t e.g. -c C0:0-3 for the first 4 physical cores in the first LLC")
print("\t5. Logical numbering inside NUMA domain.\n\t e.g. -c M0:0-3 for the first 4 physical cores in the first NUMA domain")
print("\tYou can also mix domains separated by @,\n\te.g. -c S0:0-3@S1:0-3 for the 4 first physical cores on both sockets.")
print("3. Expressions based thread list generation with compact processor numbering.")
print("Example usage expression: likwid-pin.lua -c E:N:8 ./myApp")
print("This will generate a compact list of thread to processor mapping for the node domain")
print("with eight threads.")
print("The following syntax variants are available:")
print("\t1. -c E:<thread domain>:<number of threads>")
print("\t2. -c E:<thread domain>:<number of threads>:<chunk size>:<stride>")
print("\tFor two SMT threads per core on a SMT 4 machine use e.g. -c E:N:122:2:4")
print("4. Scatter policy among thread domain type.")
print("Example usage scatter: likwid-pin.lua -c M:scatter ./myApp")
print("This will generate a thread to processor mapping scattered among all memory domains")
print("with physical cores first.")
print("")
print("likwid-pin sets OMP_NUM_THREADS with as many threads as specified")
print("in your pin expression if OMP_NUM_THREADS is not present in your environment.")
end
local function usage()
version()
print("An application to pin a program including threads.\n")
print("Options:")
print("-h, --help\t\t Help message")
print("-v, --version\t\t Version information")
print("-V, --verbose <level>\t Verbose output, 0 (only errors), 1 (info), 2 (details), 3 (developer)")
print("-i\t\t\t Set numa interleave policy with all involved numa nodes")
print("-S, --sweep\t\t Sweep memory and LLC of involved NUMA nodes")
print("-c <list>\t\t Comma separated processor IDs or expression")
print("-s, --skip <hex>\t Bitmask with threads to skip")
print("-p\t\t\t Print available domains with mapping on physical IDs")
print("\t\t\t If used together with -p option outputs a physical processor IDs.")
print("-d <string>\t\t Delimiter used for using -p to output physical processor list, default is comma.")
print("-q, --quiet\t\t Silent without output")
print("\n")
examples()
end
delimiter = ','
quiet = 0
sweep_sockets = false
interleaved_policy = false
print_domains = false
cpu_list = {}
skip_mask = "0x0"
affinity = nil
num_threads = 0
config = likwid.getConfiguration()
cputopo = likwid.getCpuTopology()
affinity = likwid.getAffinityInfo()
if (#arg == 0) then
usage()
os.exit(0)
end
for opt,arg in likwid.getopt(arg, {"c:", "d:", "h", "i", "p", "q", "s:", "S", "t:", "v", "V:", "verbose:", "help", "version", "skip","sweep", "quiet"}) do
if opt == "h" or opt == "help" then
usage()
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(0)
elseif opt == "v" or opt == "version" then
version()
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(0)
elseif opt == "V" or opt == "verbose" then
verbose = tonumber(arg)
likwid.setVerbosity(verbose)
elseif (opt == "c") then
if (affinity ~= nil) then
num_threads,cpu_list = likwid.cpustr_to_cpulist(arg)
else
num_threads,cpu_list = likwid.cpustr_to_cpulist_physical(arg)
end
if (num_threads == 0) then
print("Failed to parse cpulist " .. arg)
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(1)
end
elseif (opt == "d") then
delimiter = arg
elseif opt == "S" or opt == "sweep" then
if (affinity == nil) then
print("Option -S is not supported for unknown processor!")
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(1)
end
sweep_sockets = true
elseif (opt == "i") then
interleaved_policy = true
elseif (opt == "p") then
print_domains = true
elseif opt == "s" or opt == "skip" then
local s,e = arg:find("0x")
if s == nil then
print("Skip mask must be given in hex, hence start with 0x")
os.exit(1)
end
skip_mask = arg
elseif opt == "q" or opt == "quiet" then
likwid.setenv("LIKWID_SILENT","true")
quiet = 1
elseif opt == "?" then
print("Invalid commandline option -"..arg)
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(1)
end
end
if print_domains and num_threads > 0 then
outstr = ""
for i, cpu in pairs(cpu_list) do
outstr = outstr .. delimiter .. cpu
end
print(outstr:sub(2,outstr:len()))
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(0)
elseif print_domains then
for k,v in pairs(affinity["domains"]) do
print(string.format("Domain %s:", v["tag"]))
print("\t" .. table.concat(v["processorList"], ","))
print("")
end
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(0)
end
if num_threads == 0 then
num_threads, cpu_list = likwid.cpustr_to_cpulist("N:0-"..cputopo["numHWThreads"]-1)
end
if interleaved_policy then
print("Set mem_policy to interleaved")
likwid.setMemInterleaved(num_threads, cpu_list)
end
if sweep_sockets then
print("Sweeping memory")
likwid.memSweep(num_threads, cpu_list)
end
local omp_threads = os.getenv("OMP_NUM_THREADS")
if omp_threads == nil then
likwid.setenv("OMP_NUM_THREADS",tostring(num_threads))
elseif num_threads > tonumber(omp_threads) then
print(string.format("Environment variable OMP_NUM_THREADS already set to %s but %d cpus required", omp_threads,num_threads))
end
if num_threads > 1 then
local preload = os.getenv("LD_PRELOAD")
local pinString = tostring(cpu_list[2])
for i=3,likwid.tablelength(cpu_list) do
pinString = pinString .. "," .. cpu_list[i]
end
pinString = pinString .. "," .. cpu_list[1]
skipString = skip_mask
likwid.setenv("KMP_AFFINITY","disabled")
likwid.setenv("LIKWID_PIN", pinString)
likwid.setenv("LIKWID_SKIP",skipString)
if preload == nil then
likwid.setenv("LD_PRELOAD",likwid.pinlibpath)
else
likwid.setenv("LD_PRELOAD",likwid.pinlibpath .. ":" .. preload)
end
end
likwid.pinProcess(cpu_list[1], quiet)
local exec = table.concat(arg," ",1, likwid.tablelength(arg)-2)
local err
err = os.execute(exec)
if (err == false) then
print("Failed to execute command: ".. exec)
likwid.putTopology()
likwid.putAffinityInfo()
likwid.putConfiguration()
os.exit(1)
end
likwid.putAffinityInfo()
likwid.putTopology()
likwid.putConfiguration()
os.exit(0)
| gpl-3.0 |
Mechaniston/FibaroHC_mechHomeBcfg | BR_buttonBed (209, maxInst = 3).lua | 1 | 5980 | --[[
%% properties
206 sceneActivation
%% globals
--]]
-- CONSTS --
local buttonID = 206;
local lightBigRoomGenDevID = 40;
local lightBRLeftID = 41;
local lightBRCenterID = 42;
local lightBRRightID = 43;
local lightBRBedID = 44;
local bedIsDownID = 205;
local vdLightBRID = 195;
local vdLightBRSwitchBtn = "6";
local vdLightBRBedSwitchBtn = "16";
local lightValFullOn = "1";
local lightValFOrNOn = "101"; -- full or night val
local lightValHOrNOn = "151"; -- half or night val - used for Hall
-- button/BinSens scnActs codes
local btnScnActOn = 10; -- toggle switch only
local btnScnActOff = 11; -- toggle switch only
local btnScnActClick = 16; -- momentary switch only
local btnScnActDblClick = 14;
local btnScnActTrplClick = 15;
local btnScnActHold = 12; -- momentary switch only
local btnScnActRelease = 13; -- momentary switch only
local btnKind_OneTwo = 10; -- use 0 for FIRST channel or 10 for SECOND channel
local debugMode = false;
-- GET ENVS --
fibaro:sleep(50); -- to prevent kill all instances
if ( fibaro:countScenes() > 1 ) then
if ( debugMode ) then fibaro:debug("Double start"
.. "(" .. tostring(fibaro:countScenes()) .. ").. Abort dup!"); end
fibaro:abort();
end
local scrTrigger = fibaro:getSourceTrigger();
if ( scrTrigger["type"] ~= "property" ) then
if ( debugMode ) then fibaro:debug("Incorrect call.. Abort!"); end
fibaro:abort();
end
local sceneActID = tonumber(fibaro:getValue(buttonID, "sceneActivation"));
if ( debugMode ) then
fibaro:debug(
"sceneActID = " .. tostring(sceneActID) .. ", "
.. "btnValue = " .. fibaro:getValue(buttonID, "value")
);
end;
if ( fibaro:getValue(205, "value") == "0" ) then
if ( debugMode ) then fibaro:debug("Bed is closed.. Abort!"); end
fibaro:abort();
end
if ( ((btnKind_OneTwo == 0) and (sceneActID >= 20))
or ((btnKind_OneTwo == 10) and (sceneActID < 20)) ) then
if ( debugMode ) then fibaro:debug("Another button.. Abort!"); end
fibaro:abort();
end
local lightLeft = tonumber(fibaro:getValue(lightBRLeftID, "value"));
local lightCenter = tonumber(fibaro:getValue(lightBRCenterID, "value"));
local lightRight = tonumber(fibaro:getValue(lightBRRightID, "value"));
local lightBed = tonumber(fibaro:getValue(lightBRBedID, "value"));
local bedIsDown = tonumber(fibaro:getValue(bedIsDownID, "value"));
if ( debugMode ) then
fibaro:debug(
"lightLeft = " .. tostring(lightLeft) .. ", "
.. "lightCenter = " .. tostring(lightCenter) .. ", "
.. "lightRight = " .. tostring(lightRight) .. ", "
.. "lightBed = " .. tostring(lightBed) .. "; "
.. "bedIsDown = " .. tostring(bedIsDown)
);
end
-- PROCESS --
if ( (sceneActID == btnScnActClick + btnKind_OneTwo)
or (sceneActID == btnScnActOn + btnKind_OneTwo)
or (sceneActID == btnScnActOff + btnKind_OneTwo) ) then -------------
fibaro:call(vdLightBRID, "pressButton", vdLightBRSwitchBtn); -- vd.Ñâåò:ÁÊ-îñí SWITCH
elseif ( sceneActID == btnScnActDblClick + btnKind_OneTwo ) then -------------
local lightsActions = "";
-- change ÁÊ lights
if ( (lightLeft > 0) and (lightCenter > 0) and (lightRight > 0) )
then
lightsActions = lightsActions .. lightBRCenterID .. ",0;";
elseif ( (lightLeft > 0) and (lightCenter == 0) and (lightRight > 0) )
then
lightsActions = lightsActions .. lightBRCenterID .. "," .. tostring(lightLeft) .. ";" .. lightBRRightID .. ",0;";
elseif ( (lightLeft > 0) and (lightCenter > 0) and (lightRight == 0) )
then
lightsActions = lightsActions .. lightBRRightID .. "," .. tostring(lightCenter) .. ";" .. lightBRLeftID .. ",0;";
elseif ( (lightLeft == 0) and (lightCenter > 0) and (lightRight > 0) )
then
lightsActions = lightsActions .. lightBRCenterID .. "," .. tostring(lightRight) .. ",0;";
elseif ( (lightLeft == 0) and (lightCenter > 0) and (lightRight == 0) )
then
lightsActions = lightsActions .. lightBRLeftID .. "," .. tostring(lightCenter) .. ";" .. lightBRCenterID .. ",0";
elseif ( (lightLeft > 0) and (lightCenter == 0) and (lightRight == 0) )
then
lightsActions = lightsActions .. lightBRRightID .. "," .. tostring(lightLeft) .. ";" .. lightBRLeftID .. ",0";
elseif ( (lightLeft == 0) and (lightCenter == 0) and (lightRight > 0) )
then
if ( lightBed == 0 )
then
lightsActions = lightsActions .. lightBRBedID .. "," .. lightValFOrNOn .. ";" .. lightBRRightID .. ",0";
else
lightsActions = lightsActions .. lightBRLeftID .. "," .. tostring(lightRight) .. ";" .. lightBRCenterID .. "," .. tostring(lightRight) .. ";";
end
else
lightsActions = lightsActions .. lightBRLeftID .. "," .. lightValFOrNOn .. ";" .. lightBRCenterID .. "," .. lightValFOrNOn .. ";" .. lightBRRightID .. "," .. lightValFOrNOn .. ";";
end
--[[
if ( (bedLight == 0) and bedIsDown )
then
fibaro:call(195, "pressButton", "8"); -- ÁÊ_Êðîâàòü light ON
elseif ( (valueLight == 0) and (bedLight ~= 0) )
then
fibaro:call(195, "pressButton", "10"); -- ÁÊ_Êðîâàòü light OFF
fibaro:sleep(3000);
fibaro:call(195, "pressButton", "2"); -- ÁÊ light ON
elseif ( (valueLight ~= 0) and (bedLight ~= 0) )
then
fibaro:call(195, "pressButton", "4"); -- ÁÊ light OFF
else
fibaro:call(195, "pressButton", "2"); -- ÁÊ light ON
fibaro:sleep(3000);
fibaro:call(195, "pressButton", "8"); -- ÁÊ_Êðîâàòü light ON
end
--]]
if ( debugMode ) then
fibaro:debug("lightsActions = <" .. lightsActions .. ">");
end
fibaro:setGlobal("lightsQueue", fibaro:getGlobalValue("lightsQueue")
.. lightsActions);
elseif ( sceneActID == btnScnActTrplClick + btnKind_OneTwo ) then -------------
fibaro:call(vdLightBR, "pressButton", vdLightBRBedSwitchBtn);
end
| mit |
kitala1/darkstar | scripts/zones/Southern_San_dOria/npcs/Cahaurme.lua | 17 | 1922 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Cahaurme
-- Involved in Quest: A Knight's Test, Lost Chick
-- @zone 230
-- @pos 55.749 -8.601 -29.354
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(BOOK_OF_TASKS) and player:hasKeyItem(BOOK_OF_THE_EAST) == false) then
player:startEvent(0x0279);
else
player:showText(npc, 7817); -- nothing to report
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 == 0x0279) then
player:addKeyItem(BOOK_OF_THE_EAST);
player:messageSpecial(KEYITEM_OBTAINED, BOOK_OF_THE_EAST);
end
end;
--- for future use
-- player:startEvent(0x034f) --are you the chicks owner | gpl-3.0 |
kitala1/darkstar | scripts/zones/Oldton_Movalpolos/npcs/Tarnotik.lua | 19 | 1742 | -----------------------------------
-- Area: Oldton Movalpolos
-- NPC: Tarnotik
-- Type: Standard NPC
-- @pos 160.896 10.999 -55.659 11
-----------------------------------
package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Oldton_Movalpolos/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getCurrentMission(COP) >= THREE_PATHS) then
if(trade:getItemCount() == 1 and trade:hasItemQty(1725,1)) then
player:tradeComplete();
player:startEvent(0x0020);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 7 )then
player:startEvent(0x0022);
else
if(math.random()<0.5)then -- this isnt retail at all.
player:startEvent(0x001e);
else
player:startEvent(0x001f);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x0020)then
player:setPos(-116,-119,-620,253,13);
elseif(csid == 0x0022)then
player:setVar("COP_Louverance_s_Path",8);
end
end;
| gpl-3.0 |
tetoali605/THETETOO_A7A | plugins/addreplay.lua | 7 | 3428 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY tetoo ▀▄ ▄▀
▀▄ ▄▀ BY nmore (@l_l_lo) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY l_l_ll ▀▄ ▄▀
▀▄ ▄▀ broadcast : اضـف رد ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function get_variables_hash(msg)
if msg.to.type == 'chat' or msg.to.type == 'channel' then
return 'chat:bot:variables'
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
local function list_chats(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = '🎀🎖الـــردود هــي: ️\n\n'
for i=1, #names do
text = text..'🎀🎖'..names[i]..'\n'
end
return text
else
return
end
end
local function save_value(msg, name, value)
if (not name or not value) then
return "Usage: !set var_name value"
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hset(hash, name, value)
return '('..name..')\n تــم اضـافةة الـرد 💃تابـع قنـاةة السـورس @no_no2️ '
end
end
local function del_value(msg, name)
if not name then
return
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hdel(hash, name)
return '('..name..')\n تــم حــذف الـرد 💃تابـع قنـاةة السـورس @no_no2'
end
end
local function delallchats(msg)
local hash = 'chat:bot:variables'
if hash then
local names = redis:hkeys(hash)
for i=1, #names do
redis:hdel(hash,names[i])
end
return "saved!"
else
return
end
end
local function run(msg, matches)
if is_sudo(msg) then
local name = matches[3]
local value = matches[4]
if matches[2] == 'حذف الجميع' then
local output = delallchats(msg)
return output
end
if matches[2] == 'اضف' then
local name1 = user_print_name(msg.from)
savelog(msg.to.id, name1.." ["..msg.from.id.."] saved ["..name.."] as > "..value )
local text = save_value(msg, name, value)
return text
elseif matches[2] == 'حذف' then
local text = del_value(msg,name)
return text
end
end
if matches[1] == 'الردود' then
local output = list_chats(msg)
return output
else
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /get ".. matches[1])-- save to logs
local text = get_value(msg, matches[1])
return reply_msg(msg.id,text,ok_cb,false)
end
end
return {
patterns = {
"^(الردود)$",
"^(رد) (اضف) ([^%s]+) (.+)$",
"^(رد) (حذف الجميع)$",
"^(رد) (حذف) (.*)$",
"^(.+)$",
"^(رد) (اضف) ([^%s]+) ([^%s]+) (.+) (.+)$",
},
run = run
}
| gpl-2.0 |
yemahuang/OpenBird | cocos2d/cocos/scripting/lua/script/Opengl.lua | 49 | 6870 | require "OpenglConstants"
gl = gl or {}
--Create functions
function gl.createTexture()
local retTable = {}
retTable.texture_id = gl._createTexture()
return retTable
end
function gl.createBuffer()
local retTable = {}
retTable.buffer_id = gl._createBuffer()
return retTable
end
function gl.createRenderbuffer()
local retTable = {}
retTable.renderbuffer_id = gl._createRenderuffer()
return retTable
end
function gl.createFramebuffer( )
local retTable = {}
retTable.framebuffer_id = gl._createFramebuffer()
return retTable
end
function gl.createProgram()
local retTable = {}
retTable.program_id = gl._createProgram()
return retTable
end
function gl.createShader(shaderType)
local retTable = {}
retTable.shader_id = gl._createShader(shaderType)
return retTable
end
--Delete Fun
function gl.deleteTexture(texture)
local texture_id = 0
if "number" == type(texture) then
texture_id = texture
elseif "table" == type(texture) then
texture_id = texture.texture_id
end
gl._deleteTexture(texture_id)
end
function gl.deleteBuffer(buffer)
local buffer_id = 0
if "number" == type(buffer) then
buffer_id = buffer
elseif "table" == type(buffer) then
buffer_id = buffer.buffer_id
end
gl._deleteBuffer(buffer_id)
end
function gl.deleteRenderbuffer(buffer)
local renderbuffer_id = 0
if "number" == type(buffer) then
renderbuffer_id = buffer
elseif "table" == type(buffer) then
renderbuffer_id = buffer.renderbuffer_id
end
gl._deleteRenderbuffer(renderbuffer_id)
end
function gl.deleteFramebuffer(buffer)
local framebuffer_id = 0
if "number" == type(buffer) then
framebuffer_id = buffer
elseif "table" == type(buffer) then
framebuffer_id = buffer.framebuffer_id
end
gl._deleteFramebuffer(framebuffer_id)
end
function gl.deleteProgram( program )
local program_id = 0
if "number" == type(buffer) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
gl._deleteProgram(program_id)
end
function gl.deleteShader(shader)
local shader_id = 0
if "number" == type(shader) then
shader_id = shader
elseif "table" == type(shader) then
shader_id = shader.shader_id
end
gl._deleteShader(shader_id)
end
--Bind Related
function gl.bindTexture(target, texture)
local texture_id = 0
if "number" == type(texture) then
texture_id = texture
elseif "table" == type(texture) then
texture_id = texture.texture_id
end
gl._bindTexture(target,texture_id)
end
function gl.bindBuffer( target,buffer )
local buffer_id = 0
if "number" == type(buffer) then
buffer_id = buffer
elseif "table" == type(buffer) then
buffer_id = buffer.buffer_id
end
gl._bindBuffer(target, buffer_id)
end
function gl.bindRenderBuffer(target, buffer)
local buffer_id = 0
if "number" == type(buffer) then
buffer_id = buffer;
elseif "table" == type(buffer) then
buffer_id = buffer.buffer_id
end
gl._bindRenderbuffer(target, buffer_id)
end
function gl.bindFramebuffer(target, buffer)
local buffer_id = 0
if "number" == type(buffer) then
buffer_id = buffer
elseif "table" == type(buffer) then
buffer_id = buffer.buffer_id
end
gl._bindFramebuffer(target, buffer_id)
end
--Uniform related
function gl.getUniform(program, location)
local program_id = 0
local location_id = 0
if "number" == type(program) then
program_id = program
else
program_id = program.program_id
end
if "number" == type(location) then
location_id = location
else
location_id = location.location_id
end
return gl._getUniform(program_id, location_id)
end
--shader related
function gl.compileShader(shader)
gl._compileShader( shader.shader_id)
end
function gl.shaderSource(shader, source)
gl._shaderSource(shader.shader_id, source)
end
function gl.getShaderParameter(shader, e)
return gl._getShaderParameter(shader.shader_id,e)
end
function gl.getShaderInfoLog( shader )
return gl._getShaderInfoLog(shader.shader_id)
end
--program related
function gl.attachShader( program, shader )
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
gl._attachShader(program_id, shader.shader_id)
end
function gl.linkProgram( program )
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
gl._linkProgram(program_id)
end
function gl.getProgramParameter(program, e)
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
return gl._getProgramParameter(program_id, e)
end
function gl.useProgram(program)
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
gl._useProgram (program_id)
end
function gl.getAttribLocation(program, name )
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
return gl._getAttribLocation(program_id, name)
end
function gl.getUniformLocation( program, name )
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
return gl._getUniformLocation(program_id,name)
end
function gl.getActiveAttrib( program, index )
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
return gl._getActiveAttrib(program_id, index);
end
function gl.getActiveUniform( program, index )
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
return gl._getActiveUniform(program_id, index)
end
function gl.getAttachedShaders(program)
local program_id = 0
if "number" == type(program) then
program_id = program
elseif "table" == type(program) then
program_id = program.program_id
end
return gl._getAttachedShaders(program_id)
end
function gl.glNodeCreate()
return cc.GLNode:create()
end
| mit |
jjimenezg93/ai-state_machines | moai/3rdparty/luasocket-2.0.2/src/smtp.lua | 142 | 7961 | -----------------------------------------------------------------------------
-- SMTP client support for the Lua language.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id: smtp.lua,v 1.46 2007/03/12 04:08:40 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local coroutine = require("coroutine")
local string = require("string")
local math = require("math")
local os = require("os")
local socket = require("socket")
local tp = require("socket.tp")
local ltn12 = require("ltn12")
local mime = require("mime")
module("socket.smtp")
-----------------------------------------------------------------------------
-- Program constants
-----------------------------------------------------------------------------
-- timeout for connection
TIMEOUT = 60
-- default server used to send e-mails
SERVER = "localhost"
-- default port
PORT = 25
-- domain used in HELO command and default sendmail
-- If we are under a CGI, try to get from environment
DOMAIN = os.getenv("SERVER_NAME") or "localhost"
-- default time zone (means we don't know)
ZONE = "-0000"
---------------------------------------------------------------------------
-- Low level SMTP API
-----------------------------------------------------------------------------
local metat = { __index = {} }
function metat.__index:greet(domain)
self.try(self.tp:check("2.."))
self.try(self.tp:command("EHLO", domain or DOMAIN))
return socket.skip(1, self.try(self.tp:check("2..")))
end
function metat.__index:mail(from)
self.try(self.tp:command("MAIL", "FROM:" .. from))
return self.try(self.tp:check("2.."))
end
function metat.__index:rcpt(to)
self.try(self.tp:command("RCPT", "TO:" .. to))
return self.try(self.tp:check("2.."))
end
function metat.__index:data(src, step)
self.try(self.tp:command("DATA"))
self.try(self.tp:check("3.."))
self.try(self.tp:source(src, step))
self.try(self.tp:send("\r\n.\r\n"))
return self.try(self.tp:check("2.."))
end
function metat.__index:quit()
self.try(self.tp:command("QUIT"))
return self.try(self.tp:check("2.."))
end
function metat.__index:close()
return self.tp:close()
end
function metat.__index:login(user, password)
self.try(self.tp:command("AUTH", "LOGIN"))
self.try(self.tp:check("3.."))
self.try(self.tp:command(mime.b64(user)))
self.try(self.tp:check("3.."))
self.try(self.tp:command(mime.b64(password)))
return self.try(self.tp:check("2.."))
end
function metat.__index:plain(user, password)
local auth = "PLAIN " .. mime.b64("\0" .. user .. "\0" .. password)
self.try(self.tp:command("AUTH", auth))
return self.try(self.tp:check("2.."))
end
function metat.__index:auth(user, password, ext)
if not user or not password then return 1 end
if string.find(ext, "AUTH[^\n]+LOGIN") then
return self:login(user, password)
elseif string.find(ext, "AUTH[^\n]+PLAIN") then
return self:plain(user, password)
else
self.try(nil, "authentication not supported")
end
end
-- send message or throw an exception
function metat.__index:send(mailt)
self:mail(mailt.from)
if base.type(mailt.rcpt) == "table" then
for i,v in base.ipairs(mailt.rcpt) do
self:rcpt(v)
end
else
self:rcpt(mailt.rcpt)
end
self:data(ltn12.source.chain(mailt.source, mime.stuff()), mailt.step)
end
function open(server, port, create)
local tp = socket.try(tp.connect(server or SERVER, port or PORT,
TIMEOUT, create))
local s = base.setmetatable({tp = tp}, metat)
-- make sure tp is closed if we get an exception
s.try = socket.newtry(function()
s:close()
end)
return s
end
-- convert headers to lowercase
local function lower_headers(headers)
local lower = {}
for i,v in base.pairs(headers or lower) do
lower[string.lower(i)] = v
end
return lower
end
---------------------------------------------------------------------------
-- Multipart message source
-----------------------------------------------------------------------------
-- returns a hopefully unique mime boundary
local seqno = 0
local function newboundary()
seqno = seqno + 1
return string.format('%s%05d==%05u', os.date('%d%m%Y%H%M%S'),
math.random(0, 99999), seqno)
end
-- send_message forward declaration
local send_message
-- yield the headers all at once, it's faster
local function send_headers(headers)
local h = "\r\n"
for i,v in base.pairs(headers) do
h = i .. ': ' .. v .. "\r\n" .. h
end
coroutine.yield(h)
end
-- yield multipart message body from a multipart message table
local function send_multipart(mesgt)
-- make sure we have our boundary and send headers
local bd = newboundary()
local headers = lower_headers(mesgt.headers or {})
headers['content-type'] = headers['content-type'] or 'multipart/mixed'
headers['content-type'] = headers['content-type'] ..
'; boundary="' .. bd .. '"'
send_headers(headers)
-- send preamble
if mesgt.body.preamble then
coroutine.yield(mesgt.body.preamble)
coroutine.yield("\r\n")
end
-- send each part separated by a boundary
for i, m in base.ipairs(mesgt.body) do
coroutine.yield("\r\n--" .. bd .. "\r\n")
send_message(m)
end
-- send last boundary
coroutine.yield("\r\n--" .. bd .. "--\r\n\r\n")
-- send epilogue
if mesgt.body.epilogue then
coroutine.yield(mesgt.body.epilogue)
coroutine.yield("\r\n")
end
end
-- yield message body from a source
local function send_source(mesgt)
-- make sure we have a content-type
local headers = lower_headers(mesgt.headers or {})
headers['content-type'] = headers['content-type'] or
'text/plain; charset="iso-8859-1"'
send_headers(headers)
-- send body from source
while true do
local chunk, err = mesgt.body()
if err then coroutine.yield(nil, err)
elseif chunk then coroutine.yield(chunk)
else break end
end
end
-- yield message body from a string
local function send_string(mesgt)
-- make sure we have a content-type
local headers = lower_headers(mesgt.headers or {})
headers['content-type'] = headers['content-type'] or
'text/plain; charset="iso-8859-1"'
send_headers(headers)
-- send body from string
coroutine.yield(mesgt.body)
end
-- message source
function send_message(mesgt)
if base.type(mesgt.body) == "table" then send_multipart(mesgt)
elseif base.type(mesgt.body) == "function" then send_source(mesgt)
else send_string(mesgt) end
end
-- set defaul headers
local function adjust_headers(mesgt)
local lower = lower_headers(mesgt.headers)
lower["date"] = lower["date"] or
os.date("!%a, %d %b %Y %H:%M:%S ") .. (mesgt.zone or ZONE)
lower["x-mailer"] = lower["x-mailer"] or socket._VERSION
-- this can't be overriden
lower["mime-version"] = "1.0"
return lower
end
function message(mesgt)
mesgt.headers = adjust_headers(mesgt)
-- create and return message source
local co = coroutine.create(function() send_message(mesgt) end)
return function()
local ret, a, b = coroutine.resume(co)
if ret then return a, b
else return nil, a end
end
end
---------------------------------------------------------------------------
-- High level SMTP API
-----------------------------------------------------------------------------
send = socket.protect(function(mailt)
local s = open(mailt.server, mailt.port, mailt.create)
local ext = s:greet(mailt.domain)
s:auth(mailt.user, mailt.password, ext)
s:send(mailt)
s:quit()
return s:close()
end)
| mit |
arekinath/loglunatic | lunatic/reactor.lua | 1 | 8373 | --[[
loglunatic -- logstash for lunatics
Copyright (c) 2013, Alex Wilson, the University of Queensland
Distributed under a BSD license -- see the LICENSE file in the root of the distribution.
]]
local exports = {}
local ffi = require("ffi")
local bit = require("bit")
local POLLIN = 0x01
local POLLOUT = 0x04
ffi.cdef[[
struct pollfd {
int fd;
short events;
short revents;
};
int read(int fd, void *buf, int size);
int write(int fd, const void *buf, int bytes);
int poll(struct pollfd *fds, unsigned long nfds, int timeout);
int write(int fd, const void *buf, int bytes);
int close(int fd);
void *malloc(int size);
void free(void *ptr);
struct sockaddr {
uint8_t sa_len;
uint8_t sa_family;
char sa_data[14];
};
struct sockaddr_in {
uint8_t sin_len;
uint8_t sin_family;
uint16_t sin_port;
char sin_pad[32];
};
struct timeval {
long tv_sec;
long tv_usec;
};
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res);
void freeaddrinfo(struct addrinfo *ai);
int socket(int family, int type, int protocol);
int connect(int sock, struct sockaddr *name, int namelen);
int gettimeofday(struct timeval *tp, struct timezone *tzp);
char *strerror(int errno);
]]
if ffi.os == "OSX" then
ffi.cdef[[
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
int ai_addrlen;
char *ai_canonname;
struct sockaddr *ai_addr;
struct addrinfo *ai_next;
};
]]
else
ffi.cdef[[
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
int ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
]]
end
local function write(str)
return ffi.C.write(1, str, #str)
end
local Reactor = {}
Reactor.__index = Reactor
function Reactor.new()
local reac = {}
setmetatable(reac, Reactor)
reac.channels = {}
reac.timers = {}
reac.timer_id = 0
return reac
end
function Reactor:add(chan)
table.insert(self.channels, chan)
end
function Reactor:remove(rchan)
local ri = {}
for i,chan in ipairs(self.channels) do
if chan.fd == rchan.fd then
table.insert(ri, i)
end
end
for x,i in ipairs(ri) do
table.remove(self.channels, i)
end
rchan:cleanup()
end
function Reactor:add_timer(timeout, handler)
local id = self.timer_id
self.timer_id = self.timer_id + 1
local tv = ffi.new("struct timeval")
assert(ffi.C.gettimeofday(tv, nil) == 0)
local t = {
["time"] = timeout + tonumber(tv.tv_sec) + tonumber(tv.tv_usec) / 1.0e6,
["handler"] = handler
}
self.timers[id] = t
return id
end
function Reactor:remove_timer(id)
self.timers[id] = nil
end
function Reactor:run()
local nfds = table.getn(self.channels)
local nowtv = ffi.new("struct timeval")
local pollfds = ffi.new("struct pollfd[?]", nfds)
while nfds > 0 do
for i,chan in ipairs(self.channels) do
chan:fill_pollfd(pollfds[i-1])
end
local ret = ffi.C.poll(pollfds, nfds, 500)
if ret < 0 then
error("poll: " .. ffi.string(ffi.C.strerror(ffi.errno())))
end
if ret > 0 then
for i,chan in ipairs(self.channels) do
if bit.band(pollfds[i-1].revents, POLLIN) == POLLIN then
chan:read_data(self)
end
if bit.band(pollfds[i-1].revents, POLLOUT) == POLLOUT then
chan:write_data(self)
end
end
end
assert(ffi.C.gettimeofday(nowtv, nil) == 0)
now = tonumber(nowtv.tv_sec) + tonumber(nowtv.tv_usec) / 1.0e6
for id,timer in pairs(self.timers) do
if timer.time < now then
local h = timer.handler
self.timers[id] = nil
h:on_timeout(self)
end
end
local new_nfds = table.getn(self.channels)
if new_nfds ~= nfds then
nfds = new_nfds
if nfds > 0 then
pollfds = ffi.new("struct pollfd[?]", nfds)
end
end
end
end
exports.Reactor = Reactor
ffi.cdef[[
int uname(char *);
int fcntl(int, int, ...);
]]
local sysnamebuf = ffi.new("char[?]", 16384)
assert(ffi.C.uname(sysnamebuf) == 0)
local sysname = ffi.string(sysnamebuf)
local F_GETFL = 0x03
local F_SETFL = 0x04
local O_NONBLOCK = 0x04
local EAGAIN = 35
if ffi.os == "Linux" or string.match(sysname, "Linux") then
O_NONBLOCK = 0x800
EAGAIN = 11
end
if ffi.os == "Solaris" or string.match(sysname, "SunOS") then
O_NONBLOCK = 0x80
EAGAIN = 11
end
local Channel = {}
Channel.__index = Channel
Channel.read_buf = 32768
function Channel.new(fd)
local chan = {
["fd"] = fd,
buffer = ffi.new("char[?]", Channel.read_buf),
bufused = 0,
wrdata = {},
}
local flags = ffi.C.fcntl(fd, F_GETFL, 0)
if flags == -1 then
return nil
end
flags = bit.bor(flags, O_NONBLOCK)
if ffi.C.fcntl(fd, F_SETFL, ffi.new("int", flags)) == -1 then
return nil
end
setmetatable(chan, Channel)
chan.on_line = function (chan, rtor, line)
io.write(string.format("reactor: fd %d got line: '%s'\n", chan.fd, line))
end
chan.on_close = function (chan, rtor)
io.write("reactor: fd " .. chan.fd .. " reached eof or error\n")
ffi.C.close(chan.fd)
end
return chan
end
function Channel:cleanup()
return
end
function Channel:fill_pollfd(s)
s.fd = self.fd
if self.wrdata.first ~= nil or self.on_writeable ~= nil then
s.events = bit.bor(POLLOUT, POLLIN)
else
s.events = POLLIN
end
s.revents = 0
return s
end
function Channel:write(str)
local len = #str
local buf = {["data"] = ffi.new("char[?]", len)}
buf.size = len
buf.pos = 0
ffi.copy(buf.data, str, len)
local lastbuf = self.wrdata.last
if lastbuf ~= nil then
lastbuf.next = buf
self.wrdata.last = buf
else
self.wrdata.last = buf
self.wrdata.first = buf
end
end
function Channel:write_data(rtor)
local buf = self.wrdata.first
if buf == nil then
if self.on_writeable ~= nil then
self:on_writeable(rtor)
end
else
local ret = ffi.C.write(self.fd, buf.data + buf.pos, buf.size - buf.pos)
if ret < 0 then
if ffi.errno() == EAGAIN then
return
end
io.write("reactor: write error on fd " .. self.fd .. "\n")
self:on_close(rtor)
rtor:remove(self)
else
buf.pos = buf.pos + ret
if buf.pos >= buf.size then
self.wrdata.first = buf.next
if buf.next == nil then
self.wrdata.last = nil
end
end
end
end
end
function Channel:read_data(rtor)
local start = self.bufused
local limit = Channel.read_buf - self.bufused
local ret = ffi.C.read(self.fd, self.buffer + start, limit)
if ret == 0 then
io.write("reactor: eof on fd " .. self.fd .. "\n")
self:on_close(rtor)
rtor:remove(self)
return
elseif ret < 0 then
if ffi.errno() == EAGAIN then
return
else
io.write("reactor: read error on fd " .. self.fd .. ": " .. ffi.string(ffi.C.strerror(ffi.errno())) .. "\n")
self:on_close(rtor)
rtor:remove(self)
end
end
self.bufused = self.bufused + ret
local i = start
while i < self.bufused do
if self.buffer[i] == 10 then
local line = ffi.string(self.buffer, i)
self:on_line(rtor, line)
for j = i+1, self.bufused, 1 do
self.buffer[j - (i+1)] = self.buffer[j]
end
self.bufused = self.bufused - (i + 1)
i = 0
start = 0
end
i = i + 1
end
end
exports.Channel = Channel
local SOCK_STREAM = 1
local SOCK_DGRAM = 2
local AI_NUMERICHOST = 4
local AI_NUMERICSERV = 16
if ffi.os == "Linux" then
AI_NUMERICSERV = 0x0400
end
if ffi.os == "OSX" then
AI_NUMERICSERV = 0x1000
end
local TcpChannel = {}
TcpChannel.__index = Channel
function TcpChannel.new(host, port)
local hints = ffi.new("struct addrinfo[?]", 1)
hints[0].ai_flags = AI_NUMERICSERV
hints[0].ai_socktype = SOCK_STREAM
local ai = ffi.new("struct addrinfo*[?]", 1)
local ret = ffi.C.getaddrinfo(host, tostring(port), hints, ai)
if ret ~= 0 then error("getaddrinfo: " .. ffi.string(ffi.C.strerror(ffi.errno()))) end
local firstai = ai[0]
local lasterrno = 0
if firstai == nil then error("failed looking up " .. host) end
ai = ai[0]
while ai ~= nil do
local s = ffi.C.socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
if s <= 0 then error("socket: " .. ffi.string(ffi.C.strerror(ffi.errno()))) end
local ret = ffi.C.connect(s, ai.ai_addr, ai.ai_addrlen)
if ret == 0 then
ffi.C.freeaddrinfo(firstai)
local chan = Channel.new(s)
return chan
end
lasterrno = ffi.errno()
ffi.C.close(s)
ai = ai.ai_next
end
ffi.C.freeaddrinfo(firstai)
error("connect: " .. ffi.string(ffi.C.strerror(lasterrno)))
end
exports.TcpChannel = TcpChannel
return exports
| bsd-3-clause |
king98tm/mohammadking98 | plugins/msg-checks.lua | 1 | 11921 |
local TIME_CHECK = 2
local function pre_process(msg)
local data = load_data(_config.moderation.data)
local chat = msg.to.id
local user = msg.from.id
local is_channel = msg.to.type == "channel"
local is_chat = msg.to.type == "chat"
local auto_leave = 'auto_leave_bot'
local hash = "gp_lang:"..chat
local lang = redis:get(hash)
if is_channel or is_chat then
if msg.text then
if msg.text:match("(.*)") then
if not data[tostring(msg.to.id)] and not redis:get(auto_leave) and not is_admin(msg) then
tdcli.sendMessage(msg.to.id, "", 0, "_This Is Not One Of My_ *Groups*", 0, "md")
tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil)
end
end
end
if data[tostring(chat)] and data[tostring(chat)]['mutes'] then
mutes = data[tostring(chat)]['mutes']
else
return
end
if mutes.mute_all then
mute_all = mutes.mute_all
else
mute_all = 'no'
end
if mutes.mute_gif then
mute_gif = mutes.mute_gif
else
mute_gif = 'no'
end
if mutes.mute_photo then
mute_photo = mutes.mute_photo
else
mute_photo = 'no'
end
if mutes.mute_sticker then
mute_sticker = mutes.mute_sticker
else
mute_sticker = 'no'
end
if mutes.mute_contact then
mute_contact = mutes.mute_contact
else
mute_contact = 'no'
end
if mutes.mute_inline then
mute_inline = mutes.mute_inline
else
mute_inline = 'no'
end
if mutes.mute_game then
mute_game = mutes.mute_game
else
mute_game = 'no'
end
if mutes.mute_text then
mute_text = mutes.mute_text
else
mute_text = 'no'
end
if mutes.mute_keyboard then
mute_keyboard = mutes.mute_keyboard
else
mute_keyboard = 'no'
end
if mutes.mute_forward then
mute_forward = mutes.mute_forward
else
mute_forward = 'no'
end
if mutes.mute_location then
mute_location = mutes.mute_location
else
mute_location = 'no'
end
if mutes.mute_document then
mute_document = mutes.mute_document
else
mute_document = 'no'
end
if mutes.mute_voice then
mute_voice = mutes.mute_voice
else
mute_voice = 'no'
end
if mutes.mute_audio then
mute_audio = mutes.mute_audio
else
mute_audio = 'no'
end
if mutes.mute_video then
mute_video = mutes.mute_video
else
mute_video = 'no'
end
if mutes.mute_tgservice then
mute_tgservice = mutes.mute_tgservice
else
mute_tgservice = 'no'
end
if data[tostring(chat)] and data[tostring(chat)]['settings'] then
settings = data[tostring(chat)]['settings']
else
return
end
if settings.lock_link then
lock_link = settings.lock_link
else
lock_link = 'no'
end
if settings.lock_tag then
lock_tag = settings.lock_tag
else
lock_tag = 'no'
end
if settings.lock_pin then
lock_pin = settings.lock_pin
else
lock_pin = 'no'
end
if settings.lock_arabic then
lock_arabic = settings.lock_arabic
else
lock_arabic = 'no'
end
if settings.lock_mention then
lock_mention = settings.lock_mention
else
lock_mention = 'no'
end
if settings.lock_edit then
lock_edit = settings.lock_edit
else
lock_edit = 'no'
end
if settings.lock_spam then
lock_spam = settings.lock_spam
else
lock_spam = 'no'
end
if settings.flood then
lock_flood = settings.flood
else
lock_flood = 'no'
end
if settings.lock_markdown then
lock_markdown = settings.lock_markdown
else
lock_markdown = 'no'
end
if settings.lock_webpage then
lock_webpage = settings.lock_webpage
else
lock_webpage = 'no'
end
if msg.adduser or msg.joinuser or msg.deluser then
if mute_tgservice == "yes" then
del_msg(chat, tonumber(msg.id))
end
end
if msg.pinned and is_channel then
if lock_pin == "yes" then
if is_owner(msg) then
return
end
if tonumber(msg.from.id) == our_id then
return
end
local pin_msg = data[tostring(chat)]['pin']
if pin_msg then
tdcli.pinChannelMessage(msg.to.id, pin_msg, 1)
elseif not pin_msg then
tdcli.unpinChannelMessage(msg.to.id)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>شما اجازه دسترسی به سنجاق پیام را ندارید، به همین دلیل پیام قبلی مجدد سنجاق میگردد</i>', 0, "html")
elseif not lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>You Have Not Permission To Pin Message, Last Message Has Been Pinned Again</i>', 0, "html")
end
end
end
if not is_mod(msg) then
if msg.edited and lock_edit == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.forward_info_ and mute_forward == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.photo_ and mute_photo == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.video_ and mute_video == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.document_ and mute_document == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.sticker_ and mute_sticker == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.animation_ and mute_gif == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.contact_ and mute_contact == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.location_ and mute_location == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.voice_ and mute_voice == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.content_ and mute_keyboard == "yes" then
if msg.reply_markup_ and msg.reply_markup_.ID == "ReplyMarkupInlineKeyboard" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if tonumber(msg.via_bot_user_id_) ~= 0 and mute_inline == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.game_ and mute_game == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.audio_ and mute_audio == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.media.caption then
local link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.media.caption:match("[Tt].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_caption
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_caption = msg.media.caption:match("@") or msg.media.caption:match("#")
if tag_caption and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.media.caption) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_caption = msg.media.caption:match("[\216-\219][\128-\191]")
if arabic_caption and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.text then
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
local _nl, real_digits = string.gsub(msg.text, '%d', '')
if lock_spam == "yes" then
if string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
local link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.text:match("[Tt].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_msg
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_msg = msg.text:match("@") or msg.text:match("#")
if tag_msg and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.text) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_msg = msg.text:match("[\216-\219][\128-\191]")
if arabic_msg and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.text:match("(.*)")
and mute_text == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if mute_all == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.content_.entities_ and msg.content_.entities_[0] then
if msg.content_.entities_[0].ID == "MessageEntityMentionName" then
if lock_mention == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityUrl" or msg.content_.entities_[0].ID == "MessageEntityTextUrl" then
if lock_webpage == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityBold" or msg.content_.entities_[0].ID == "MessageEntityCode" or msg.content_.entities_[0].ID == "MessageEntityPre" or msg.content_.entities_[0].ID == "MessageEntityItalic" then
if lock_markdown == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
end
if msg.to.type ~= 'pv' then
if lock_flood == "yes" then
local hash = 'user:'..user..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local NUM_MSG_MAX = 5
if data[tostring(chat)] then
if data[tostring(chat)]['settings']['num_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(chat)]['settings']['num_msg_max'])
end
end
if msgs > NUM_MSG_MAX then
if is_mod(msg) then
return
end
if msg.adduser and msg.from.id then
return
end
if msg.from.username then
user_name = "@"..msg.from.username
else
user_name = msg.from.first_name
end
if redis:get('sender:'..user..':flood') then
return
else
del_msg(chat, msg.id)
kick_user(user, chat)
if not lang then
tdcli.sendMessage(chat, msg.id, 0, "_User_ "..user_name.." `[ "..user.." ]` _has been_ *kicked* _because of_ *flooding*", 0, "md")
elseif lang then
tdcli.sendMessage(chat, msg.id, 0, "_کاربر_ "..user_name.." `[ "..user.." ]` _به دلیل ارسال پیام های مکرر اخراج شد_", 0, "md")
end
redis:setex('sender:'..user..':flood', 30, true)
end
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
end
end
end
return {
patterns = {},
pre_process = pre_process
}
| gpl-3.0 |
mohammads15/new-super | plugins/owners.lua | 194 | 23755 | local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_arabic(msg, data, target)
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_links(msg, data, target)
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'Contact posting is already locked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'Contact posting has been locked'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'Contact posting is already unlocked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'Contact posting has been unlocked'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['strict']
if strict == 'yes' then
return 'Settings are already strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'Settings will be strictly enforced'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['strict']
if strict == 'no' then
return 'Settings will not be strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'Settings are not strictly enforced'
end
end
-- Show group settings
local function show_group_settingsmod(msg, data, target)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(target)]['settings']['lock_bots'] then
bots_protection = data[tostring(target)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(target)]['settings']['leave_ban'] then
leave_ban = data[tostring(target)]['settings']['leave_ban']
end
local public = "no"
if data[tostring(target)]['settings'] then
if data[tostring(target)]['settings']['public'] then
public = data[tostring(target)]['settings']['public']
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection.."\nPublic: "..public
return text
end
-- Show SuperGroup settings
local function show_super_group_settings(msg, data, target)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type == 'user' then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", " ")
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], chat_id)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
channel_set_about(receiver, about_text, ok_cb, false)
return "About has been cleaned"
end
if matches[3] == 'mutelist' then
chat_id = string.match(matches[1], '^%d+$')
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "Mutelist Cleaned"
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
local group_type = data[tostring(matches[1])]['group_type']
if matches[3] == 'name' then
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[3] == 'arabic' then
savelog(matches[1], name.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
savelog(matches[1], name.." ["..msg.from.id.."] locked links ")
return lock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
savelog(matches[1], name.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
savelog(matches[1], name.." ["..msg.from.id.."] locked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
savelog(matches[1], name.." ["..msg.from.id.."] locked sticker")
return lock_group_sticker(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
local group_type = data[tostring(matches[1])]['group_type']
if matches[3] == 'name' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[3] == 'arabic' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[3] == 'links' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked links ")
return unlock_group_links(msg, data, target)
end
if matches[3] == 'spam' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked spam ")
return unlock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked sticker")
return unlock_group_sticker(msg, data, target)
end
if matches[3] == 'contacts' and group_type == "SuperGroup" then
savelog(matches[1], name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[3] == 'strict' and group_type == "SuperGroup" then
savelog(matches[1], name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
local group_type = data[tostring(matches[1])]['group_type']
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback_grouplink (extra , success, result)
local receiver = 'chat#id'..matches[1]
if success == 0 then
send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.')
end
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local function callback_superlink (extra , success, result)
vardump(result)
local receiver = 'channel#id'..matches[1]
local user = extra.user
if success == 0 then
data[tostring(matches[1])]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
return send_large_msg(user, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it')
else
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return send_large_msg(user, "Created a new link")
end
end
if group_type == "Group" then
local receiver = 'chat#id'..matches[1]
savelog(matches[1], name.." ["..msg.from.id.."] created/revoked group link ")
export_chat_link(receiver, callback_grouplink, false)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
elseif group_type == "SuperGroup" then
local receiver = 'channel#id'..matches[1]
local user = 'user#id'..msg.from.id
savelog(matches[1], name.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_superlink, {user = user})
end
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] then
if not is_owner2(msg.from.id, matches[2]) then
return "You are not the owner of this group"
end
local group_type = data[tostring(matches[2])]['group_type']
if group_type == "Group" or group_type == "Realm" then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
elseif group_type == "SuperGroup" then
local channel = 'channel#id'..matches[2]
local about_text = matches[3]
local data_cat = 'description'
local target = matches[2]
channel_set_about(channel, about_text, ok_cb, false)
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(matches[2], name.." ["..msg.from.id.."] has changed SuperGroup description to ["..matches[3].."]")
return "Description has been set for ["..matches[2]..']'
end
end
if matches[1] == 'viewsettings' and data[tostring(matches[2])]['settings'] then
if not is_owner2(msg.from.id, matches[2]) then
return "You are not the owner of this group"
end
local target = matches[2]
local group_type = data[tostring(matches[2])]['group_type']
if group_type == "Group" or group_type == "Realm" then
savelog(matches[2], name.." ["..msg.from.id.."] requested group settings ")
return show_group_settings(msg, data, target)
elseif group_type == "SuperGroup" then
savelog(matches[2], name.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_super_group_settings(msg, data, target)
end
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
save_data(_config.moderation.data, data)
local chat_to_rename = 'chat#id'..matches[2]
local channel_to_rename = 'channel#id'..matches[2]
savelog(matches[2], "Group name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(chat_to_rename, group_name_set, ok_cb, false)
rename_channel(channel_to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "log file created by owner/support/admin")
send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[#!/]owners (%d+) ([^%s]+) (.*)$",
"^[#!/]owners (%d+) ([^%s]+)$",
"^[#!/](changeabout) (%d+) (.*)$",
"^[#!/](changerules) (%d+) (.*)$",
"^[#!/](changename) (%d+) (.*)$",
"^[#!/](viewsettings) (%d+)$",
"^[#!/](loggroup) (%d+)$"
},
run = run
} | gpl-2.0 |
kitala1/darkstar | scripts/zones/Temenos/mobs/Skadi.lua | 17 | 1191 | -----------------------------------
-- Area: Temenos N T
-- NPC: Skadi
-----------------------------------
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)
GetMobByID(16928783):updateEnmity(target);
GetMobByID(16928782):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if(IsMobDead(16928781)==true and IsMobDead(16928782)==true and IsMobDead(16928783)==true )then
GetNPCByID(16928768+19):setPos(200,-82,495);
GetNPCByID(16928768+19):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+153):setPos(206,-82,495);
GetNPCByID(16928768+153):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+210):setPos(196,-82,495);
GetNPCByID(16928768+210):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
cjkoenig/packages | net/luci-app-sqm/files/sqm-cbi.lua | 7 | 8239 | --[[
LuCI - Lua Configuration Interface
Copyright 2014 Steven Barth <steven@midlink.org>
Copyright 2014 Dave Taht <dave.taht@bufferbloat.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
local net = require "luci.model.network".init()
local sys = require "luci.sys"
--local ifaces = net:get_interfaces()
local ifaces = sys.net:devices()
local path = "/usr/lib/sqm"
m = Map("sqm", translate("Smart Queue Management"),
translate("With <abbr title=\"Smart Queue Management\">SQM</abbr> you " ..
"can enable traffic shaping, better mixing (Fair Queueing)," ..
" active queue length management (AQM) " ..
" and prioritisation on one " ..
"network interface."))
s = m:section(TypedSection, "queue", translate("Queues"))
s:tab("tab_basic", translate("Basic Settings"))
s:tab("tab_qdisc", translate("Queue Discipline"))
s:tab("tab_linklayer", translate("Link Layer Adaptation"))
s.addremove = true -- set to true to allow adding SQM instances in the GUI
s.anonymous = true
-- BASIC
e = s:taboption("tab_basic", Flag, "enabled", translate("Enable"))
e.rmempty = false
n = s:taboption("tab_basic", ListValue, "interface", translate("Interface name"))
-- sm lifted from luci-app-wol, the original implementation failed to show pppoe-ge00 type interface names
for _, iface in ipairs(ifaces) do
-- if iface:is_up() then
-- n:value(iface:name())
-- end
if iface ~= "lo" then
n:value(iface)
end
end
n.rmempty = false
dl = s:taboption("tab_basic", Value, "download", translate("Download speed (kbit/s) (ingress) set to 0 to selectively disable ingress shaping:"))
dl.datatype = "and(uinteger,min(0))"
dl.rmempty = false
ul = s:taboption("tab_basic", Value, "upload", translate("Upload speed (kbit/s) (egress) set to 0 to selectively disable egress shaping:"))
ul.datatype = "and(uinteger,min(0))"
ul.rmempty = false
-- QDISC
c = s:taboption("tab_qdisc", ListValue, "qdisc", translate("Queueing discipline"))
c:value("fq_codel", "fq_codel ("..translate("default")..")")
c:value("efq_codel")
c:value("nfq_codel")
c:value("sfq")
c:value("codel")
c:value("ns2_codel")
c:value("pie")
c:value("sfq")
c.default = "fq_codel"
c.rmempty = false
local qos_desc = ""
sc = s:taboption("tab_qdisc", ListValue, "script", translate("Queue setup script"))
for file in fs.dir(path) do
if string.find(file, ".qos$") then
sc:value(file)
end
if string.find(file, ".qos.help$") then
fh = io.open(path .. "/" .. file, "r")
qos_desc = qos_desc .. "<p><b>" .. file:gsub(".help$", "") .. ":</b><br />" .. fh:read("*a") .. "</p>"
end
end
sc.default = "simple.qos"
sc.rmempty = false
sc.description = qos_desc
ad = s:taboption("tab_qdisc", Flag, "qdisc_advanced", translate("Show and Use Advanced Configuration"))
ad.default = false
ad.rmempty = true
squash_dscp = s:taboption("tab_qdisc", ListValue, "squash_dscp", translate("Squash DSCP on inbound packets (ingress):"))
squash_dscp:value("1", "SQUASH")
squash_dscp:value("0", "DO NOT SQUASH")
squash_dscp.default = "1"
squash_dscp.rmempty = true
squash_dscp:depends("qdisc_advanced", "1")
squash_ingress = s:taboption("tab_qdisc", ListValue, "squash_ingress", translate("Ignore DSCP on ingress:"))
squash_ingress:value("1", "Ignore")
squash_ingress:value("0", "Allow")
squash_ingress.default = "1"
squash_ingress.rmempty = true
squash_ingress:depends("qdisc_advanced", "1")
iecn = s:taboption("tab_qdisc", ListValue, "ingress_ecn", translate("Explicit congestion notification (ECN) status on inbound packets (ingress):"))
iecn:value("ECN", "ECN ("..translate("default")..")")
iecn:value("NOECN")
iecn.default = "ECN"
iecn.rmempty = true
iecn:depends("qdisc_advanced", "1")
eecn = s:taboption("tab_qdisc", ListValue, "egress_ecn", translate("Explicit congestion notification (ECN) status on outbound packets (egress)."))
eecn:value("NOECN", "NOECN ("..translate("default")..")")
eecn:value("ECN")
eecn.default = "NOECN"
eecn.rmempty = true
eecn:depends("qdisc_advanced", "1")
ad2 = s:taboption("tab_qdisc", Flag, "qdisc_really_really_advanced", translate("Show and Use Dangerous Configuration"))
ad2.default = false
ad2.rmempty = true
ad2:depends("qdisc_advanced", "1")
ilim = s:taboption("tab_qdisc", Value, "ilimit", translate("Hard limit on ingress queues; leave empty for default."))
-- ilim.default = 1000
ilim.isnumber = true
ilim.datatype = "and(uinteger,min(0))"
ilim.rmempty = true
ilim:depends("qdisc_really_really_advanced", "1")
elim = s:taboption("tab_qdisc", Value, "elimit", translate("Hard limit on egress queues; leave empty for default."))
-- elim.default = 1000
elim.datatype = "and(uinteger,min(0))"
elim.rmempty = true
elim:depends("qdisc_really_really_advanced", "1")
itarg = s:taboption("tab_qdisc", Value, "itarget", translate("Latency target for ingress, e.g 5ms [units: s, ms, or us]; leave empty for automatic selection, put in the word default for the qdisc's default."))
itarg.datatype = "string"
itarg.rmempty = true
itarg:depends("qdisc_really_really_advanced", "1")
etarg = s:taboption("tab_qdisc", Value, "etarget", translate("Latency target for egress, e.g. 5ms [units: s, ms, or us]; leave empty for automatic selection, put in the word default for the qdisc's default."))
etarg.datatype = "string"
etarg.rmempty = true
etarg:depends("qdisc_really_really_advanced", "1")
iqdisc_opts = s:taboption("tab_qdisc", Value, "iqdisc_opts", translate("Advanced option string to pass to the ingress queueing disciplines; no error checking, use very carefully."))
iqdisc_opts.rmempty = true
iqdisc_opts:depends("qdisc_really_really_advanced", "1")
eqdisc_opts = s:taboption("tab_qdisc", Value, "eqdisc_opts", translate("Advanced option string to pass to the egress queueing disciplines; no error checking, use very carefully."))
eqdisc_opts.rmempty = true
eqdisc_opts:depends("qdisc_really_really_advanced", "1")
-- LINKLAYER
ll = s:taboption("tab_linklayer", ListValue, "linklayer", translate("Which link layer to account for:"))
ll:value("none", "none ("..translate("default")..")")
ll:value("ethernet", "Ethernet with overhead: select for e.g. VDSL2.")
ll:value("atm", "ATM: select for e.g. ADSL1, ADSL2, ADSL2+.")
-- ll:value("adsl") -- reduce the options
ll.default = "none"
po = s:taboption("tab_linklayer", Value, "overhead", translate("Per Packet Overhead (byte):"))
po.datatype = "and(integer,min(-1500))"
po.default = 0
po.isnumber = true
po.rmempty = true
po:depends("linklayer", "ethernet")
-- po:depends("linklayer", "adsl")
po:depends("linklayer", "atm")
adll = s:taboption("tab_linklayer", Flag, "linklayer_advanced", translate("Show Advanced Linklayer Options, (only needed if MTU > 1500)"))
adll.rmempty = true
adll:depends("linklayer", "ethernet")
-- adll:depends("linklayer", "adsl")
adll:depends("linklayer", "atm")
smtu = s:taboption("tab_linklayer", Value, "tcMTU", translate("Maximal Size for size and rate calculations, tcMTU (byte); needs to be >= interface MTU + overhead:"))
smtu.datatype = "and(uinteger,min(0))"
smtu.default = 2047
smtu.isnumber = true
smtu.rmempty = true
smtu:depends("linklayer_advanced", "1")
stsize = s:taboption("tab_linklayer", Value, "tcTSIZE", translate("Number of entries in size/rate tables, TSIZE; for ATM choose TSIZE = (tcMTU + 1) / 16:"))
stsize.datatype = "and(uinteger,min(0))"
stsize.default = 128
stsize.isnumber = true
stsize.rmempty = true
stsize:depends("linklayer_advanced", "1")
smpu = s:taboption("tab_linklayer", Value, "tcMPU", translate("Minimal packet size, MPU (byte); needs to be > 0 for ethernet size tables:"))
smpu.datatype = "and(uinteger,min(0))"
smpu.default = 0
smpu.isnumber = true
smpu.rmempty = true
smpu:depends("linklayer_advanced", "1")
lla = s:taboption("tab_linklayer", ListValue, "linklayer_adaptation_mechanism", translate("Which linklayer adaptation mechanism to use; for testing only"))
lla:value("htb_private")
lla:value("tc_stab", "tc_stab ("..translate("default")..")")
lla.default = "tc_stab"
lla.rmempty = true
lla:depends("linklayer_advanced", "1")
-- PRORITIES?
return m
| gpl-2.0 |
darrenatdesignory/CG | scripts/scrollView.lua | 1 | 9034 | -- scrollView.lua
--
-- Version 1.0
---module(..., package.seeall)
-- set some global values for width and height of the screen
local screenW, screenH = display.contentWidth, display.contentHeight
local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight
local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight
local prevTime = 0
function new(params)
-- setup a group to be the scrolling screen
local scrollView = display.newGroup()
scrollView.top = params.top or 0
scrollView.bottom = params.bottom or 0
function scrollView:touch(event)
local phase = event.phase
print(phase)
if( phase == "began" ) then
print(scrollView.y)
self.startPos = event.y
self.prevPos = event.y
self.delta, self.velocity = 0, 0
if self.tween then transition.cancel(self.tween) end
Runtime:removeEventListener("enterFrame", scrollView )
self.prevTime = 0
self.prevY = 0
transition.to(self.scrollBar, { time=200, alpha=1 } )
-- Start tracking velocity
Runtime:addEventListener("enterFrame", trackVelocity)
-- Subsequent touch events will target button even if they are outside the stageBounds of button
display.getCurrentStage():setFocus( self )
self.isFocus = true
elseif( self.isFocus ) then
if( phase == "moved" ) then
local bottomLimit = screenH - self.height - self.bottom
self.delta = event.y - self.prevPos
self.prevPos = event.y
if ( self.y > self.top or self.y < bottomLimit ) then
self.y = self.y + self.delta/2
else
self.y = self.y + self.delta
end
scrollView:moveScrollBar()
elseif( phase == "ended" or phase == "cancelled" ) then
local dragDistance = event.y - self.startPos
self.lastTime = event.time
Runtime:addEventListener("enterFrame", scrollView )
Runtime:removeEventListener("enterFrame", trackVelocity)
-- Allow touch events to be sent normally to the objects they "hit"
display.getCurrentStage():setFocus( nil )
self.isFocus = false
end
end
return true
end
function scrollView:enterFrame(event)
local friction = 0.9
local timePassed = event.time - self.lastTime
self.lastTime = self.lastTime + timePassed
--turn off scrolling if velocity is near zero
if math.abs(self.velocity) < .01 then
self.velocity = 0
Runtime:removeEventListener("enterFrame", scrollView )
transition.to(self.scrollBar, { time=400, alpha=0 } )
end
self.velocity = self.velocity*friction
self.y = math.floor(self.y + self.velocity*timePassed)
local upperLimit = self.top
local bottomLimit = screenH - self.height - self.bottom
if ( self.y > upperLimit ) then
self.velocity = 0
Runtime:removeEventListener("enterFrame", scrollView )
self.tween = transition.to(self, { time=400, y=upperLimit, transition=easing.outQuad})
transition.to(self.scrollBar, { time=400, alpha=0 } )
elseif ( self.y < bottomLimit and bottomLimit < 0 ) then
self.velocity = 0
Runtime:removeEventListener("enterFrame", scrollView )
self.tween = transition.to(self, { time=400, y=bottomLimit, transition=easing.outQuad})
transition.to(self.scrollBar, { time=400, alpha=0 } )
elseif ( self.y < bottomLimit ) then
self.velocity = 0
Runtime:removeEventListener("enterFrame", scrollView )
self.tween = transition.to(self, { time=400, y=upperLimit, transition=easing.outQuad})
transition.to(self.scrollBar, { time=400, alpha=0 } )
end
scrollView:moveScrollBar()
return true
end
function scrollView:moveScrollBar()
if self.scrollBar then
local scrollBar = self.scrollBar
scrollBar.y = -self.y*self.yRatio + scrollBar.height*0.5 + self.top
if scrollBar.y < 5 + self.top + scrollBar.height*0.5 then
scrollBar.y = 5 + self.top + scrollBar.height*0.5
end
if scrollBar.y > screenH - self.bottom - 5 - scrollBar.height*0.5 then
scrollBar.y = screenH - self.bottom - 5 - scrollBar.height*0.5
end
end
end
function trackVelocity(event)
local timePassed = event.time - scrollView.prevTime
scrollView.prevTime = scrollView.prevTime + timePassed
if scrollView.prevY then
scrollView.velocity = (scrollView.y - scrollView.prevY)/timePassed
end
scrollView.prevY = scrollView.y
end
scrollView.y = scrollView.top
-- setup the touch listener
scrollView:addEventListener( "touch", scrollView )
function scrollView:addScrollBar(r,g,b,a)
if self.scrollBar then self.scrollBar:removeSelf() end
local scrollColorR = r or 0
local scrollColorG = g or 0
local scrollColorB = b or 0
local scrollColorA = a or 120
local viewPortH = screenH - self.top - self.bottom
local scrollH = viewPortH*self.height/(self.height*2 - viewPortH)
local scrollBar = display.newRoundedRect(viewableScreenW-8,0,5,scrollH,2)
scrollBar:setFillColor(scrollColorR, scrollColorG, scrollColorB, scrollColorA)
local yRatio = scrollH/self.height
self.yRatio = yRatio
scrollBar.y = scrollBar.height*0.5 + self.top
self.scrollBar = scrollBar
transition.to(scrollBar, { time=400, alpha=0 } )
end
function scrollView:removeScrollBar()
if self.scrollBar then
self.scrollBar:removeSelf()
self.scrollBar = nil
end
end
function scrollView:cleanUp()
Runtime:removeEventListener("enterFrame", trackVelocity)
Runtime:removeEventListener( "touch", scrollView )
Runtime:removeEventListener("enterFrame", scrollView )
scrollView:removeScrollBar()
end
return scrollView
end | mit |
crabman77/minetest-minetestforfun-server | mods/plantlife_modpack/ferns/crafting.lua | 7 | 3927 | -----------------------------------------------------------------------------------------------
-- Ferns - Crafting 0.0.5
-----------------------------------------------------------------------------------------------
-- (by Mossmanikin)
-- License (everything): WTFPL
-----------------------------------------------------------------------------------------------
minetest.register_craft({
type = "shapeless",
output = "ferns:fiddlehead 3",
recipe = {"ferns:fern_01"},
replacements = {
{"ferns:fern_01", "ferns:ferntuber"}
},
})
minetest.register_craft({
type = "shapeless",
output = "ferns:fiddlehead 3",
recipe = {"ferns:tree_fern_leaves"},
replacements = {
{"ferns:tree_fern_leaves", "ferns:sapling_tree_fern"}
},
})
-----------------------------------------------------------------------------------------------
-- FIDDLEHEAD
-----------------------------------------------------------------------------------------------
minetest.register_alias("archaeplantae:fiddlehead", "ferns:fiddlehead")
minetest.register_craftitem("ferns:fiddlehead", {
description = "Fiddlehead",
inventory_image = "ferns_fiddlehead.png",
on_use = minetest.item_eat(-1), -- slightly poisonous when raw
})
minetest.register_craft({
type = "cooking",
output = "ferns:fiddlehead_roasted",
recipe = "ferns:fiddlehead",
cooktime = 1,
})
minetest.register_craftitem("ferns:fiddlehead_roasted", {
description = "Roasted Fiddlehead",
inventory_image = "ferns_fiddlehead_roasted.png",
on_use = minetest.item_eat(1), -- edible when cooked
})
-----------------------------------------------------------------------------------------------
-- FERN TUBER
-----------------------------------------------------------------------------------------------
minetest.register_alias("archaeplantae:ferntuber", "ferns:ferntuber")
minetest.register_craftitem("ferns:ferntuber", {
description = "Fern Tuber",
inventory_image = "ferns_ferntuber.png",
})
minetest.register_craft({
type = "cooking",
output = "ferns:ferntuber_roasted",
recipe = "ferns:ferntuber",
cooktime = 3,
})
minetest.register_alias("archaeplantae:ferntuber_roasted", "ferns:ferntuber_roasted")
minetest.register_craftitem("ferns:ferntuber_roasted", {
description = "Roasted Fern Tuber",
inventory_image = "ferns_ferntuber_roasted.png",
on_use = minetest.item_eat(3),
})
-----------------------------------------------------------------------------------------------
-- HORSETAIL (EQUISETUM) --> GREEN DYE https://en.wikipedia.org/wiki/Equisetum
-----------------------------------------------------------------------------------------------
minetest.register_craft({
type = "shapeless",
output = "dye:green",
recipe = {"group:horsetail"},
})
-----------------------------------------------------------------------------------------------
-- GLUE WOODEN TOOLS with RESIN & POLISH them with HORSETAIL (planned)
-----------------------------------------------------------------------------------------------
--[[minetest.register_craft({
type = "shapeless",
output = "default:pick_wood",
recipe = {"default:pick_wood","group:horsetail","farming:string","default:stick"},
})
minetest.register_craft({
type = "shapeless",
output = "default:shovel_wood",
recipe = {"default:shovel_wood","group:horsetail","farming:string","default:stick"},
})
minetest.register_craft({
type = "shapeless",
output = "default:axe_wood",
recipe = {"default:axe_wood","group:horsetail","farming:string","default:stick"},
})
minetest.register_craft({
type = "shapeless",
output = "default:sword_wood",
recipe = {"default:sword_wood","group:horsetail","farming:string","default:stick"},
})
minetest.register_craft({
type = "shapeless",
output = "farming:hoe_wood",
recipe = {"farming:hoe_wood","group:horsetail","farming:string","default:stick"},
})]]
| unlicense |
aminkinghakerlifee/wolf-team | plugins/azan.lua | 3 | 3158 | --[[
#
# @GPMOD
# @Dragon_Born
#
]]
do
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
function get_staticmap(area)
local api = base_api .. "/staticmap?"
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
local receiver = get_receiver(msg)
local city = matches[1]
if matches[1] == 'praytime' then
city = 'Tehran'
end
local lat,lng,url = get_staticmap(city)
local dumptime = run_bash('date +%s')
local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7')
local jdat = json:decode(code)
local data = jdat.data.timings
local text = '⛪️شهر: '..city
text = text..'\n🕌اذان صبح: '..data.Fajr
text = text..'\n🕌طلوع آفتاب: '..data.Sunrise
text = text..'\n🕌اذان ظهر: '..data.Dhuhr
text = text..'\n🕌غروب آفتاب: '..data.Sunset
text = text..'\n🕌اذان مغرب: '..data.Maghrib
text = text..'\n🕌عشاء : '..data.Isha
if string.match(text, '0') then text = string.gsub(text, '0', '۰') end
if string.match(text, '1') then text = string.gsub(text, '1', '۱') end
if string.match(text, '2') then text = string.gsub(text, '2', '۲') end
if string.match(text, '3') then text = string.gsub(text, '3', '۳') end
if string.match(text, '4') then text = string.gsub(text, '4', '۴') end
if string.match(text, '5') then text = string.gsub(text, '5', '۵') end
if string.match(text, '6') then text = string.gsub(text, '6', '۶') end
if string.match(text, '7') then text = string.gsub(text, '7', '۷') end
if string.match(text, '8') then text = string.gsub(text, '8', '۸') end
if string.match(text, '9') then text = string.gsub(text, '9', '۹') end
return text
end
return {
patterns = {"^[#/!][Pp]raytime (.*)$","^[#/!](praytime)$"},
run = run
}
end | gpl-3.0 |
nicodinh/cuberite | lib/tolua++/src/bin/lua/typedef.lua | 44 | 1696 | -- tolua: typedef class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Typedef class
-- Represents a type synonym.
-- The 'de facto' type replaces the typedef before the
-- remaining code is parsed.
-- The following fields are stored:
-- utype = typedef name
-- type = 'the facto' type
-- mod = modifiers to the 'de facto' type
classTypedef = {
utype = '',
mod = '',
type = ''
}
classTypedef.__index = classTypedef
-- Print method
function classTypedef:print (ident,close)
print(ident.."Typedef{")
print(ident.." utype = '"..self.utype.."',")
print(ident.." mod = '"..self.mod.."',")
print(ident.." type = '"..self.type.."',")
print(ident.."}"..close)
end
-- Return it's not a variable
function classTypedef:isvariable ()
return false
end
-- Internal constructor
function _Typedef (t)
setmetatable(t,classTypedef)
t.type = resolve_template_types(t.type)
appendtypedef(t)
return t
end
-- Constructor
-- Expects one string representing the type definition.
function Typedef (s)
if strfind(string.gsub(s, '%b<>', ''),'[%*&]') then
tolua_error("#invalid typedef: pointers (and references) are not supported")
end
local o = {mod = ''}
if string.find(s, "[<>]") then
_,_,o.type,o.utype = string.find(s, "^%s*([^<>]+%b<>[^%s]*)%s+(.-)$")
else
local t = split(gsub(s,"%s%s*"," ")," ")
o = {
utype = t[t.n],
type = t[t.n-1],
mod = concat(t,1,t.n-2),
}
end
return _Typedef(o)
end
| apache-2.0 |
AliKhodadad/wildman | plugins/anti_spam.lua | 923 | 3750 |
--An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
local data = load_data(_config.moderation.data)
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is one or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
local chat = msg.to.id
local user = msg.from.id
-- Return end if user was kicked before
if kicktable[user] == true then
return
end
kick_user(user, chat)
local name = user_print_name(msg.from)
--save it to log file
savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ")
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
local username = " "
if msg.from.username ~= nil then
username = msg.from.username
end
local name = user_print_name(msg.from)
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)")
local log_group = 1 --set log group caht id
--send it to log group
send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)")
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
kitala1/darkstar | scripts/globals/items/piece_of_witch_nougat.lua | 35 | 1290 | -----------------------------------------
-- ID: 5645
-- Item: piece_of_witch_nougat
-- Food Effect: 1hour, All Races
-----------------------------------------
-- HP 50
-- Intelligence 3
-- Agility -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5645);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 50);
target:addMod(MOD_INT, 3);
target:addMod(MOD_AGI, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 50);
target:delMod(MOD_INT, 3);
target:delMod(MOD_AGI, -3);
end;
| gpl-3.0 |
kitala1/darkstar | scripts/zones/Western_Adoulin/Zone.lua | 33 | 1246 | -----------------------------------
--
-- Zone: Western Adoulin
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-142,4,-18,4);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
ZenityRTS/Zenity | libs/lcs/quickTour.lua | 1 | 8606 | -- Copyright (c) 2012 Roland Yonaba
--[[
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
--]]
---------------------------------------------------------------------------------------------
--[[
quickTour Program for Lua Class System
Copyright (C) 2012.
Written by Roland Yonaba - E-mail: roland[dot]yonaba[at]gmail[dot]com
--]]
----------------------------------------------------------------------------------------------
local Topics = {
'Loading LCS',
'Creating Classes',
'Library-defined Functions For Classes',
'Instantiation',
'Adding Methods To Classes',
'Single Inheritance',
'Library-defined Functions For Inheritance relationships',
'End'
}
local samples = {
[Topics[1]] =
[[
-- Copy 'LCS.lua' file inside your project folder
-- Use require to have LCS library loaded
LCS = require 'LCS']],
[Topics[2]] =
[[
-- Creating a simple class called Account
-- we can add members to this class
Account = LCS.class {balance = 100, owner = 'Boss'}
print(Account.balance,Account.owner)]],
[Topics[3]] =
[[
-- You can check if a var is a class is_A function
print('is Account a class ? ',LCS.is_A(Account))
print('is Account a class ? ',LCS.is_A(Account,'class'))
]],
[Topics[4]] =
[[
-- Objects can be created the easy way, by calling the class, or using the new operator.
print('\nwe create two accounts')
myAccount = Account()
yourAccount = Account:new()
-- Objects share common properties with their mother class while being different one from another
-- We can act on each object properties
print('setting myAccount balance to 45')
myAccount.balance = 45
print('setting yourAccount owner name to \'You\'')
yourAccount.owner = 'You'
print('myAccount','balance '..myAccount.balance,'owner '..myAccount.owner)
print('yourAccount','balance '..yourAccount.balance,'owner '..yourAccount.owner)
-- Objects can also be instantiated and customized at the same time by calling the class itself, though a special method name init.
print( '\nLet\'s reset new objects')
print('setting myAccount with balance of 250 and owner name \'Roland\'')
function Account:init(balance,owner)
self.balance = balance
self.owner = owner
end
myAccount = Account (250,'Roland')
print('setting \'yourAccount\' with balance of 150')
yourAccount = Account:new(150)
print('myAccount','balance '..myAccount.balance,'owner '..myAccount.owner)
print('yourAccount','balance '..yourAccount.balance,'owner '..yourAccount.owner)
-- We can check if 'object' is an instance using is_A
print('\nis myAccount an instance ?',LCS.is_A(myAccount))
print('\nis myAccount an instance ?',LCS.is_A(yourAccount,'object'))
-- We can check if 'object' is an instance of 'class' using is_A()
print('is myAccount an instance of class Account ?',myAccount:is_A(Account))
-- We can also call getClass() default method to return the class from which an object was instantiated
print('is myAccount an instance of class Account ?',myAccount:getClass() == Account )
-- A class can be abstract.
print('\nWe set a new abstractAccount class')
abstractAccount = LCS.class.abstract{ owner = 'staticMe', balance = 500}
print('Now, trying to instantiate from abstractAccount will throw an error!')
print('ERROR when executing "myAccount = abstractAccount()" : ',select(2,pcall(abstractAccount)))
]],
--
[Topics[5]] =
[[
--Let's redefine the Account class
print('We create a class named Account')
Account = LCS.class {balance = 100,owner = 'Noone'}
-- Let's add a new members to the class Account.
print('we add a member \'maximum_balance\' to this class')
Account.maximum_balance = 500
-- Let's add methods to the class account
print('Adding method withdraw() to Account class')
function Account:withdraw(s)
if self.balance >= s then
self.balance = self.balance - s
else
print('[WARNING] : It remains only '..self.balance..', you moron! You cannot withdraw '..s)
end
end
print('Adding method deposit() to Account class')
function Account:deposit(s)
if self.balance + s <= self.maximum_balance then
self.balance = self.balance + s
else
print('[WARNING] : Your account balance is currently '..self.balance..' and is limited to '..self.maximum_balance)
end
end
print('we create Account with default balance of 100')
myAccount = Account()
print('Let\'s try to withdraw 200, more than the balance!')
myAccount:withdraw(200)
print('Let\'s try to make a huge deposit or 1000!')
myAccount:deposit(1000)
print('Now we make a reasonable deposit of 100')
myAccount:deposit(100)
print('current balance is',myAccount.balance)
print('Now we make a reasonable withdraw of 5')
myAccount:withdraw(5)
print('current balance is',myAccount.balance)
]],
[Topics[6]]=
[[
-- First, remember our previous class Account has methods withdraw() and deposit()
-- We have defined them so that it is not possible to withdraw more than the account balance
-- or deposit more than an authorized maximum_deposit.
-- Now let's create a new class called vipAccount.
-- This class will inherit from Account
VipAccount = Account:extends()
print('vipAccount','balance '..VipAccount.balance,'owner '..VipAccount.owner,'maximum balance '..VipAccount.maximum_balance)
print('we create an instance of vipAccount')
myVipAccount = VipAccount()
-- The subclass vipAccount can use its superclass Account methods
print('myVipAccount current balance is',myVipAccount.balance)
print('making a deposit in a vipAccount')
myVipAccount:deposit(100)
print('myVipAccount current balance is',myVipAccount.balance)
-- We can even redefine superclass methods in a subclass
print('now we redefine deposit() method in VipAccount class so that a VipAccount can hold more money than the maximum_balance')
function VipAccount:deposit(s)
self.balance = self.balance + s
end
print('Let\'s try to make a huge deposit of 1000!')
myVipAccount:deposit(1000)
print('myVipAccount current balance is',myVipAccount.balance,' the maximum balance is still ',myVipAccount.maximum_balance,'and I don\'t care!')
-- Now, the awesome stuff, we can still call the original deposit() method in the superclass Account
print('Calling the original deposit() method in the superclass from the subclass to make a deposit of 1 in the vipAccount')
myVipAccount:super('deposit',1)
]],
[Topics[7]] =
[[
-- We have seen previously that all classes are granted default methods
-- Some lets you identity subclass/superclass relationships between classes.
print('is VipAccount a subclass of class Account ?',VipAccount:getClass() == Account)
print('is Account a superclass of class VipAccount ?',(Account:getSubClasses())[VipAccount])
-- We can get the whole list of subclasses of a class
print('\nList of subclasses of Account')
local l = Account:getSubClasses()
for k,v in pairs(l) do
print(k,v)
end
-- We can create final classes.
-- A final class is a class from which derivation is not possible.
print('\nWe create a new finalVipAccount class')
finalVipAccount = LCS.class.final()
print('Now trying to make a new class inherit from finalVipAccount will throw an error')
print('ERROR when executing "vipAccountNew = (finalVipAccount:extends())" : ',select(2,pcall(finalVipAccount.extends,finalVipAccount)))
]],
[Topics[8]] =
[[
print('\n The quick tour is complete!\n Now, enjoy using LCS.\nFeel free to report any comment/bugs/suggestions at :\n roland[dot]yonaba[at]gmail[dot]com')
]]
}
for i,topic in ipairs(Topics) do
local sample = samples[topic]
if os.getenv('os') then os.execute('cls') end
print('=== Topic : '..topic..' ===\n')
if topic~='End' then
print(sample)
print('\n=== Output === \n')
end
local exec,failed = pcall(loadstring(sample))
if not exec then
output = ''
print('\n Failed to run a sample.\nPlease report the following error to the author.\n')
print(failed)
end
print('\nPress Enter to run the next sample')
io.read()
end
| gpl-2.0 |
crabman77/minetest-minetestforfun-server | mods/broomstick/init.lua | 9 | 3960 | local broomstick_time = 120 -- Seconds
local broomstick_mana = 190
local broomstick_actual_users = {}
local had_fly_privilege = {}
local privs = {}
-- broomstick file
users_file = minetest.get_worldpath() .. "/broomstick_users.txt"
--load broomstick file
local file = io.open(users_file, "r")
if file then
had_fly_privilege = minetest.deserialize(file:read("*all"))
file:close()
file = nil
if not had_fly_privilege or type(had_fly_privilege) ~= "table" then
had_fly_privilege = {}
end
else
minetest.log("error", "[broomstick] Can not open broomstick_users.txt file !")
end
-- funtion save broomstick file
local function save()
local input = io.open(users_file, "w")
if input then
input:write(minetest.serialize(had_fly_privilege))
input:close()
else
minetest.log("error","[broomstick] Open failed (mode:w) of " .. users_file)
end
end
-- on join_player remove priv fly
minetest.register_on_joinplayer(function(player)
local playername = player:get_player_name()
if had_fly_privilege[playername] ~= nil then
privs = minetest.get_player_privs(playername)
privs.fly = nil
minetest.set_player_privs(playername, privs)
had_fly_privilege[playername] = nil
save()
end
end)
-- Broomstick timer
local function broomstick_end(playername)
minetest.chat_send_player(playername, "WARNING ! You'll fall in 10 seconds !")
minetest.after(10, function(playername)
-- Send a message...
minetest.chat_send_player(playername, "End of broomstick. I hope you're not falling down...")
-- Set player privs...
privs = minetest.get_player_privs(playername)
privs["fly"] = nil
minetest.set_player_privs(playername, privs)
-- Remove the player in the list.
for i = 1, #broomstick_actual_users do
if broomstick_actual_users[i] == playername then
table.remove(broomstick_actual_users, i)
end
end
-- Rewrite the broomstick_users.txt file.
had_fly_privilege[playername] = nil
save()
end, playername)
end
-- Register broomstick
minetest.register_craftitem("broomstick:broomstick", {
description = "Broomstick",
inventory_image = "broomstick.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
local playername = user:get_player_name()
if mana.get(playername) >= broomstick_mana then
local has_already_a_broomstick = false
for i = 1, #broomstick_actual_users do
if broomstick_actual_users[i] == playername then
has_already_a_broomstick = true
end
end
if not has_already_a_broomstick then
privs = minetest.get_player_privs(playername)
-- Set player privs...
if not privs.fly == true then
-- Rewrite the broomstick_users.txt file.
had_fly_privilege[playername] = true
save()
privs.fly = true
minetest.set_player_privs(playername, privs)
else
minetest.chat_send_player(playername, "You known you can fly by yourself, don't you?")
return
end
-- Send a message...
minetest.chat_send_player(playername, "You can now fly during " .. tostring(broomstick_time) .. " seconds.")
minetest.log("action", "Player " .. playername .. " has use a broomstick.")
-- Subtract mana...
mana.subtract(playername, broomstick_mana)
-- Insert player in the list.
table.insert(broomstick_actual_users, playername)
-- And add the function in queue
minetest.after(broomstick_time-10, broomstick_end, playername)
-- Remove broomstick.
return ItemStack("")
else
minetest.chat_send_player(playername, "You already have a broomstick ! Please wait until the end of your actual broomstick.")
end
else
minetest.chat_send_player(playername, "You must have " .. tostring(broomstick_mana) .. " of mana to use a broomstick !")
end
end,
})
-- Craft
minetest.register_craft({
output = "broomstick:broomstick",
recipe = {{"","","farming:string",},
{"default:stick","default:stick","mobs:minotaur_lots_of_fur",},
{"","","farming:string",},},
})
minetest.log("info", "[OK] broomstick")
| unlicense |
kitala1/darkstar | scripts/zones/Aht_Urhgan_Whitegate/TextIDs.lua | 5 | 4950 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 217; -- You cannot obtain the item. Come back after sorting your inventory.?Prompt?
ITEM_CANNOT_BE_OBTAINEDX = 218; -- You cannot obtain the ?Possible Special Code: 01??Possible Special Code: 05?#?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?. Try trading again after sorting your inventory.?Prompt?
ITEM_OBTAINED = 219; -- Obtained: <item>
ITEM_OBTAINEDX = 228; -- You obtain ?Numeric Parameter 1? ?Possible Special Code: 01??Speaker Name?)??BAD CHAR: 80??BAD CHAR: 80??BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?!?Prompt?
GIL_OBTAINED = 220; -- Obtained <number> gil
KEYITEM_OBTAINED = 222; -- Obtained key item: <keyitem>
NOT_HAVE_ENOUGH_GIL = 224; -- You do not have enough gil
FISHING_MESSAGE_OFFSET = 873; -- You can't fish here
HOMEPOINT_SET = 1328; -- Home point set!
IMAGE_SUPPORT = 1361; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ?Multiple Choice (Parameter 2)?[a little/ever so slightly/ever so slightly].?Prompt?
-- Conquest system
SANCTION = 9755; -- You have received the Empire's Sanction.
-- Quest dialogs
ZASSHAL_DIALOG = 10949; -- 'ang about. Looks like the permit you got was the last one I 'ad, so it might take me a bit o' time to scrounge up some more. 'ere, don't gimme that look. I'll be restocked before you know it.
MUSHAYRA_DIALOG = 4918; -- Sorry for all the trouble. Please ignore Hadahda the next time he asks you to do something.
HADAHDA_DIALOG = 4869; -- Hey, think you could help me out?
-- Other Dialogs
ITEM_DELIVERY_DIALOG = 9305; -- You have something you want delivered?
RUNIC_PORTAL = 4538; -- You cannot use the runic portal without the Empire's authorization.
IMAGE_SUPPORT_ACTIVE = 1359; -- You have to wait a bit longer before asking for synthesis image support again.
-- Shop Texts
UGRIHD_PURCHASE_DIALOGUE = 4599; -- Salaheem's Sentinels values your contribution to the success of the company. Please come again!
GAVRIE_SHOP_DIALOG = 9219; -- Remember to take your medicine in small doses... Sometimes you can get a little too much of a good thing!
MALFUD_SHOP_DIALOG = 9220; -- Welcome, welcome! Flavor your meals with Malfud's ingredients!
RUBAHAH_SHOP_DIALOG = 9221; -- Flour! Flooour! Corn! Rice and beans! Get your rice and beans here! If you're looking for grain, you've come to the right place!
MULNITH_SHOP_DIALOG = 9222; -- Drawn in by my shop's irresistible aroma, were you? How would you like some of the Near East's famous skewers to enjoy during your journeys?
SALUHWA_SHOP_DIALOG = 9223; -- Looking for undentable shields? This shop's got the best of 'em! These are absolute must-haves for a mercenary's dangerous work!
DWAGO_SHOP_DIALOG = 9224; -- Buy your goods here...or you'll regret it!
KULHAMARIYO_SHOP_DIALOG = 9225; -- Some fish to savorrr while you enjoy the sights of Aht Urhgan?
KHAFJHIFANM_SHOP_DIALOG = 9226; -- How about a souvenir for back home? There's nothing like dried dates to remind you of good times in Al Zahbi!
HAGAKOFF_SHOP_DIALOG = 9227; -- Welcome! Fill all your destructive needs with my superb weaponry! No good mercenary goes without a good weapon!
BAJAHB_SHOP_DIALOG = 9228; -- Good day! If you want to live long, you'll buy your armor here.
MAZWEEN_SHOP_DIALOG = 9229; -- Magic scrolls! Get your magic scrolls here!
FAYEEWAH_SHOP_DIALOG = 9230; -- Why not sit back a spell and enjoy the rich aroma and taste of a cup of chai?
YAFAAF_SHOP_DIALOG = 9231; -- There's nothing like the mature taste and luxurious aroma of coffee... Would you like a cup
WAHNID_SHOP_DIALOG = 9232; -- All the fishing gear you'll ever need, here in one place!
WAHRAGA_SHOP_DIALOG = 9233; -- Welcome to the Alchemists' Guild.
-- Automaton
AUTOMATON_RENAME = 5784; -- Your automaton has a new name.
AUTOMATON_VALOREDGE_UNLOCK = 9543; -- You obtain the Valoredge X-900 head and frame!
AUTOMATON_SHARPSHOT_UNLOCK = 9548; -- You obtain the Sharpshot Z-500 head and frame!
AUTOMATON_STORMWAKER_UNLOCK = 9553; -- You obtain the Stormwaker Y-700 head and frame!
AUTOMATON_SOULSOOTHER_UNLOCK = 9585; -- You obtain the Soulsoother C-1000 head!
AUTOMATON_SPIRITREAVER_UNLOCK = 9586; -- You obtain the Spiritreaver M-400 head!
AUTOMATON_ATTACHMENT_UNLOCK = 9602; -- You can now equip your automaton with
-- Assault
RYTAAL_MISSION_COMPLETE = 5606; -- Congratulations. You have been awarded Assault Points for the successful completion of your mission.
RYTAAL_MISSION_FAILED = 5607; -- Your mission was not successful; however, the Empire recognizes your contribution and has awarded you Assault Points.
-- Porter Moogle
RETRIEVE_DIALOG_ID = 13468; -- You retrieve a <item> from the porter moogle's care.
| gpl-3.0 |
aidenkeating/mongrel2 | examples/bbs/bbs.lua | 96 | 4552 | local strict = require 'strict'
local m2 = require 'mongrel2'
local ui = require 'ui'
local engine = require 'engine'
local db = require 'db'
local function new_user(conn, req, user, password)
req = ui.prompt(conn, req, 'new_user')
while req.data.msg ~= password do
req = ui.prompt(conn, req, 'repeat_pass')
end
db.register_user(user, password)
ui.screen(conn, req, 'welcome_newbie')
end
local function read_long_message(conn, req, user)
local msg = {}
ui.screen(conn, req, 'leave_msg')
req = ui.ask(conn, req, 'From: ' .. user .. '\n---', '')
while req.data.msg ~= '.' and #msg < 24 do
table.insert(msg, req.data.msg)
req = ui.ask(conn, req, '', '')
end
return msg
end
local function message_iterator(db, i)
if i > 0 then
return i-1, db.message_read(i-1)
end
end
local function messages(db)
local count = assert(db.message_count())
return message_iterator, db, count
end
local function list_all_messages(conn, req)
for i, msg in messages(db) do
ui.display(conn, req, ('---- #%d -----'):format(i))
ui.display(conn, req, msg .. '\n')
if i == 0 then
ui.ask(conn, req, "No more messages; Enter for MAIN MENU.", '> ')
else
req = ui.ask(conn, req, "Enter, or Q to stop reading.", '> ')
if req.data.msg:upper() == 'Q' then
ui.display(conn, req, "Done reading.")
break
end
end
end
end
local MAINMENU = {
['1'] = function(conn, req, user)
local msg = read_long_message(conn, req, user)
db.post_message(user, msg)
ui.screen(conn, req, 'posted')
end,
['2'] = function(conn, req, user)
ui.screen(conn, req, 'read_msg')
local count = assert(db.message_count())
if count == 0 then
ui.display(conn, req, "There are no messages!")
else
list_all_messages(conn, req)
end
end,
['3'] = function (conn, req, user)
req = ui.ask(conn, req, 'Who do you want to send it to?', '> ')
local to = req.data.msg
local exists = assert(db.user_exists(to))
if exists then
local msg = read_long_message(conn, req, user)
db.send_to(to, user, msg)
ui.display(conn, req, "Message sent to " .. to)
else
ui.display(conn, req, 'Sorry, that user does not exit.')
end
end,
['4'] = function(conn, req, user)
local count = assert(db.inbox_count(user))
if count == 0 then
ui.display(conn, req, 'No messages for you. Try back later.')
return
end
while db.inbox_count(user) > 0 do
local msg = assert(db.read_inbox(user))
ui.display(conn, req, msg)
ui.ask(conn, req, "Enter to continue.", '> ')
end
end,
['Q'] = function(conn, req, user)
ui.exit(conn, req, 'bye')
end
}
local function m2bbs(conn)
local req = coroutine.yield() -- Wait for data
ui.screen(conn, req, 'welcome')
-- Have the user log in
req = ui.prompt(conn, req, 'name')
local user = req.data.msg
req = ui.prompt(conn, req, 'password')
local password = req.data.msg
print('login attempt', user, password)
local exists, error = db.user_exists(user)
if error then
print("ERROR:", error)
ui.display(conn, req, 'We had an error, sorry. Try again.')
return
elseif not exists then
new_user(conn, req, user, password)
elseif not db.auth_user(user, password) then
ui.exit(conn, req, 'bad_pass')
return
end
-- Display the MoTD and wait for the user to hit Enter.
ui.prompt(conn, req, 'motd')
repeat
req = ui.prompt(conn, req, 'menu')
local selection = MAINMENU[req.data.msg:upper()]
print("message:", req.data.msg)
if selection then
selection(conn, req, user)
else
ui.screen(conn, req, 'menu_error')
end
until req.data.msg:upper() == "Q"
end
do
-- Load configuration properties
local config = {}
setfenv(assert(loadfile('config.lua')), config)()
-- Connect to the Mongrel2 server
print("connecting", config.sender_id, config.sub_addr, config.pub_addr)
local ctx = mongrel2.new(config.io_threads)
local conn = ctx:new_connection(config.sender_id, config.sub_addr, config.pub_addr)
-- Run the BBS engine
engine.run(conn, m2bbs)
end
| bsd-3-clause |
hanxi/cocos2d-x-v3.1 | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ActionCamera.lua | 3 | 1664 |
--------------------------------
-- @module ActionCamera
-- @extend ActionInterval
--------------------------------
-- overload function: setEye(float, float, float)
--
-- overload function: setEye(cc.Vec3)
--
-- @function [parent=#ActionCamera] setEye
-- @param self
-- @param #float float
-- @param #float float
-- @param #float float
--------------------------------
-- @function [parent=#ActionCamera] getEye
-- @param self
-- @return Vec3#Vec3 ret (return value: cc.Vec3)
--------------------------------
-- @function [parent=#ActionCamera] setUp
-- @param self
-- @param #cc.Vec3 vec3
--------------------------------
-- @function [parent=#ActionCamera] getCenter
-- @param self
-- @return Vec3#Vec3 ret (return value: cc.Vec3)
--------------------------------
-- @function [parent=#ActionCamera] setCenter
-- @param self
-- @param #cc.Vec3 vec3
--------------------------------
-- @function [parent=#ActionCamera] getUp
-- @param self
-- @return Vec3#Vec3 ret (return value: cc.Vec3)
--------------------------------
-- @function [parent=#ActionCamera] startWithTarget
-- @param self
-- @param #cc.Node node
--------------------------------
-- @function [parent=#ActionCamera] clone
-- @param self
-- @return ActionCamera#ActionCamera ret (return value: cc.ActionCamera)
--------------------------------
-- @function [parent=#ActionCamera] reverse
-- @param self
-- @return ActionCamera#ActionCamera ret (return value: cc.ActionCamera)
--------------------------------
-- @function [parent=#ActionCamera] ActionCamera
-- @param self
return nil
| mit |
apletnev/koreader | spec/unit/background_task_plugin_spec.lua | 3 | 4469 | describe("BackgroundTaskPlugin", function()
require("commonrequire")
local BackgroundTaskPlugin = require("ui/plugin/background_task_plugin")
local MockTime = require("mock_time")
local UIManager = require("ui/uimanager")
setup(function()
MockTime:install()
local Device = require("device")
Device.input.waitEvent = function() end
UIManager._run_forever = true
requireBackgroundRunner()
end)
teardown(function()
MockTime:uninstall()
package.unloadAll()
stopBackgroundRunner()
end)
local createTestPlugin = function(executable)
return BackgroundTaskPlugin:new({
name = "test_plugin",
default_enable = true,
when = 2,
executable = executable,
})
end
local TestPlugin2 = BackgroundTaskPlugin:extend()
function TestPlugin2:new(o)
o = o or {}
o.name = "test_plugin2"
o.default_enable = true
o.when = 2
o.executed = 0
o.executable = function()
o.executed = o.executed + 1
end
o = BackgroundTaskPlugin.new(self, o)
return o
end
it("should be able to create a plugin", function()
local executed = 0
local test_plugin = createTestPlugin(function()
executed = executed + 1
end)
MockTime:increase(2)
UIManager:handleInput()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(1, executed)
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(2, executed)
test_plugin:flipSetting()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(3, executed) -- The last job is still pending.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(3, executed)
test_plugin:flipSetting()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(3, executed) -- The new job has just been inserted.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(4, executed)
-- Fake a settings_id increment.
test_plugin:_init()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(5, executed) -- The job is from last settings_id.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(5, executed) -- The new job has just been inserted.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(6, executed) -- The job is from current settings_id.
-- Ensure test_plugin is stopped.
test_plugin:flipSetting()
MockTime:increase(2)
UIManager:handleInput()
end)
it("should be able to create a derived plugin", function()
local test_plugin = TestPlugin2:new()
MockTime:increase(2)
UIManager:handleInput()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(1, test_plugin.executed)
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(2, test_plugin.executed)
test_plugin:flipSetting()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(3, test_plugin.executed) -- The last job is still pending.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(3, test_plugin.executed)
test_plugin:flipSetting()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(3, test_plugin.executed) -- The new job has just been inserted.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(4, test_plugin.executed)
-- Fake a settings_id increment.
test_plugin:_init()
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(5, test_plugin.executed) -- The job is from last settings_id.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(5, test_plugin.executed) -- The new job has just been inserted.
MockTime:increase(2)
UIManager:handleInput()
assert.are.equal(6, test_plugin.executed) -- The job is from current settings_id.
-- Ensure test_plugin is stopped.
test_plugin:flipSetting()
MockTime:increase(2)
UIManager:handleInput()
end)
end)
| agpl-3.0 |
kitala1/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Amajal.lua | 33 | 1032 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Amajal
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02A3);
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 |
tynaut/EggstraClucks | objects/eggstra/tamingpost/tamingpost.lua | 2 | 1276 | function main()
if entity.id() then
local container = entity.id()
local item = world.containerItemAt(container, 0)
if canTame(item) then
if storage.incubationTime == nil then storage.incubationTime = os.time() end
--TODO update time to config
local hatchTime = 1200
local delta = os.time() - storage.incubationTime
if delta > hatchTime then
spawnTamed()
storage.incubationTime = nil
end
else
storage.incubationTime = nil
end
end
end
function canTame(item)
if item and item.name == "filledcapturepod" then return true end
return false
end
function spawnTamed()
local container = entity.id()
local item = world.containerItemAt(container, 0)
if canTame(item) then
local data = item.data
if data == nil then return end
data = data.projectileConfig
if data == nil then return end
data = data.actionOnReap
if data == nil then return end
local params = data[1].arguments
local mtype = data[1]["type"]
local p = entity.position()
params.ownerUuid = nil
local mId = world.spawnMonster(mtype, {p[1], p[2] + 2}, params)
if mId then
world.containerTakeAt(container, 0)
end
end
end | apache-2.0 |
kitala1/darkstar | scripts/zones/Northern_San_dOria/npcs/Emeige_AMAN.lua | 65 | 1182 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Emeige A.M.A.N.
-- Type: Mentor Recruiter
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local var = 0;
if (player:getMentor() == 0) then
if (player:getMainLvl() >= 30 and player:getPlaytime() >= 648000) then
var = 1;
end
elseif (player:getMentor() >= 1) then
var = 2;
end
player:startEvent(0x02E3, var);
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 == 0x02E3 and option == 0) then
player:setMentor(1);
end
end;
| gpl-3.0 |
cjkoenig/packages | net/mwan3-luci/files/usr/lib/lua/luci/controller/mwan3.lua | 36 | 10850 | module("luci.controller.mwan3", package.seeall)
sys = require "luci.sys"
ut = require "luci.util"
function index()
if not nixio.fs.access("/etc/config/mwan3") then
return
end
entry({"admin", "network", "mwan"},
alias("admin", "network", "mwan", "overview"),
_("Load Balancing"), 600)
entry({"admin", "network", "mwan", "overview"},
alias("admin", "network", "mwan", "overview", "overview_interface"),
_("Overview"), 10)
entry({"admin", "network", "mwan", "overview", "overview_interface"},
template("mwan/overview_interface"))
entry({"admin", "network", "mwan", "overview", "interface_status"},
call("interfaceStatus"))
entry({"admin", "network", "mwan", "overview", "overview_detailed"},
template("mwan/overview_detailed"))
entry({"admin", "network", "mwan", "overview", "detailed_status"},
call("detailedStatus"))
entry({"admin", "network", "mwan", "configuration"},
alias("admin", "network", "mwan", "configuration", "interface"),
_("Configuration"), 20)
entry({"admin", "network", "mwan", "configuration", "interface"},
arcombine(cbi("mwan/interface"), cbi("mwan/interfaceconfig")),
_("Interfaces"), 10).leaf = true
entry({"admin", "network", "mwan", "configuration", "member"},
arcombine(cbi("mwan/member"), cbi("mwan/memberconfig")),
_("Members"), 20).leaf = true
entry({"admin", "network", "mwan", "configuration", "policy"},
arcombine(cbi("mwan/policy"), cbi("mwan/policyconfig")),
_("Policies"), 30).leaf = true
entry({"admin", "network", "mwan", "configuration", "rule"},
arcombine(cbi("mwan/rule"), cbi("mwan/ruleconfig")),
_("Rules"), 40).leaf = true
entry({"admin", "network", "mwan", "advanced"},
alias("admin", "network", "mwan", "advanced", "hotplugscript"),
_("Advanced"), 100)
entry({"admin", "network", "mwan", "advanced", "hotplugscript"},
form("mwan/advanced_hotplugscript"))
entry({"admin", "network", "mwan", "advanced", "mwanconfig"},
form("mwan/advanced_mwanconfig"))
entry({"admin", "network", "mwan", "advanced", "networkconfig"},
form("mwan/advanced_networkconfig"))
entry({"admin", "network", "mwan", "advanced", "diagnostics"},
template("mwan/advanced_diagnostics"))
entry({"admin", "network", "mwan", "advanced", "diagnostics_display"},
call("diagnosticsData"), nil).leaf = true
entry({"admin", "network", "mwan", "advanced", "troubleshooting"},
template("mwan/advanced_troubleshooting"))
entry({"admin", "network", "mwan", "advanced", "troubleshooting_display"},
call("troubleshootingData"))
end
function getInterfaceStatus(ruleNumber, interfaceName)
if ut.trim(sys.exec("uci -p /var/state get mwan3." .. interfaceName .. ".enabled")) == "1" then
if ut.trim(sys.exec("ip route list table " .. ruleNumber)) ~= "" then
if ut.trim(sys.exec("uci -p /var/state get mwan3." .. interfaceName .. ".track_ip")) ~= "" then
return "online"
else
return "notMonitored"
end
else
return "offline"
end
else
return "notEnabled"
end
end
function getInterfaceName()
local ruleNumber, status = 0, ""
uci.cursor():foreach("mwan3", "interface",
function (section)
ruleNumber = ruleNumber+1
status = status .. section[".name"] .. "[" .. getInterfaceStatus(ruleNumber, section[".name"]) .. "]"
end
)
return status
end
function interfaceStatus()
local ntm = require "luci.model.network".init()
local mArray = {}
-- overview status
local statusString = getInterfaceName()
if statusString ~= "" then
mArray.wans = {}
wansid = {}
for wanName, interfaceState in string.gfind(statusString, "([^%[]+)%[([^%]]+)%]") do
local wanInterfaceName = ut.trim(sys.exec("uci -p /var/state get network." .. wanName .. ".ifname"))
if wanInterfaceName == "" then
wanInterfaceName = "X"
end
local wanDeviceLink = ntm:get_interface(wanInterfaceName)
wanDeviceLink = wanDeviceLink and wanDeviceLink:get_network()
wanDeviceLink = wanDeviceLink and wanDeviceLink:adminlink() or "#"
wansid[wanName] = #mArray.wans + 1
mArray.wans[wansid[wanName]] = { name = wanName, link = wanDeviceLink, ifname = wanInterfaceName, status = interfaceState }
end
end
-- overview status log
local mwanLog = ut.trim(sys.exec("logread | grep mwan3 | tail -n 50 | sed 'x;1!H;$!d;x'"))
if mwanLog ~= "" then
mArray.mwanlog = { mwanLog }
end
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
function detailedStatus()
local mArray = {}
-- detailed mwan status
local detailStatusInfo = ut.trim(sys.exec("/usr/sbin/mwan3 status"))
if detailStatusInfo ~= "" then
mArray.mwandetail = { detailStatusInfo }
end
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
function diagnosticsData(interface, tool, task)
function getInterfaceNumber()
local number = 0
uci.cursor():foreach("mwan3", "interface",
function (section)
number = number+1
if section[".name"] == interface then
interfaceNumber = number
end
end
)
end
local mArray = {}
local results = ""
if tool == "service" then
os.execute("/usr/sbin/mwan3 " .. task)
if task == "restart" then
results = "MWAN3 restarted"
elseif task == "stop" then
results = "MWAN3 stopped"
else
results = "MWAN3 started"
end
else
local interfaceDevice = ut.trim(sys.exec("uci -p /var/state get network." .. interface .. ".ifname"))
if interfaceDevice ~= "" then
if tool == "ping" then
local gateway = ut.trim(sys.exec("route -n | awk '{if ($8 == \"" .. interfaceDevice .. "\" && $1 == \"0.0.0.0\" && $3 == \"0.0.0.0\") print $2}'"))
if gateway ~= "" then
if task == "gateway" then
local pingCommand = "ping -c 3 -W 2 -I " .. interfaceDevice .. " " .. gateway
results = pingCommand .. "\n\n" .. sys.exec(pingCommand)
else
local tracked = ut.trim(sys.exec("uci -p /var/state get mwan3." .. interface .. ".track_ip"))
if tracked ~= "" then
for z in tracked:gmatch("[^ ]+") do
local pingCommand = "ping -c 3 -W 2 -I " .. interfaceDevice .. " " .. z
results = results .. pingCommand .. "\n\n" .. sys.exec(pingCommand) .. "\n\n"
end
else
results = "No tracking IP addresses configured on " .. interface
end
end
else
results = "No default gateway for " .. interface .. " found. Default route does not exist or is configured incorrectly"
end
elseif tool == "rulechk" then
getInterfaceNumber()
local rule1 = sys.exec("ip rule | grep $(echo $((" .. interfaceNumber .. " + 1000)))")
local rule2 = sys.exec("ip rule | grep $(echo $((" .. interfaceNumber .. " + 2000)))")
if rule1 ~= "" and rule2 ~= "" then
results = "All required interface IP rules found:\n\n" .. rule1 .. rule2
elseif rule1 ~= "" or rule2 ~= "" then
results = "Missing 1 of the 2 required interface IP rules\n\n\nRules found:\n\n" .. rule1 .. rule2
else
results = "Missing both of the required interface IP rules"
end
elseif tool == "routechk" then
getInterfaceNumber()
local routeTable = sys.exec("ip route list table " .. interfaceNumber)
if routeTable ~= "" then
results = "Interface routing table " .. interfaceNumber .. " was found:\n\n" .. routeTable
else
results = "Missing required interface routing table " .. interfaceNumber
end
elseif tool == "hotplug" then
if task == "ifup" then
os.execute("/usr/sbin/mwan3 ifup " .. interface)
results = "Hotplug ifup sent to interface " .. interface .. "..."
else
os.execute("/usr/sbin/mwan3 ifdown " .. interface)
results = "Hotplug ifdown sent to interface " .. interface .. "..."
end
end
else
results = "Unable to perform diagnostic tests on " .. interface .. ". There is no physical or virtual device associated with this interface"
end
end
if results ~= "" then
results = ut.trim(results)
mArray.diagnostics = { results }
end
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
function troubleshootingData()
local ver = require "luci.version"
local mArray = {}
-- software versions
local wrtRelease = ut.trim(ver.distversion)
if wrtRelease ~= "" then
wrtRelease = "OpenWrt - " .. wrtRelease
else
wrtRelease = "OpenWrt - unknown"
end
local luciRelease = ut.trim(ver.luciversion)
if luciRelease ~= "" then
luciRelease = "\nLuCI - " .. luciRelease
else
luciRelease = "\nLuCI - unknown"
end
local mwanVersion = ut.trim(sys.exec("opkg info mwan3 | grep Version | awk '{print $2}'"))
if mwanVersion ~= "" then
mwanVersion = "\n\nmwan3 - " .. mwanVersion
else
mwanVersion = "\n\nmwan3 - unknown"
end
local mwanLuciVersion = ut.trim(sys.exec("opkg info luci-app-mwan3 | grep Version | awk '{print $2}'"))
if mwanLuciVersion ~= "" then
mwanLuciVersion = "\nmwan3-luci - " .. mwanLuciVersion
else
mwanLuciVersion = "\nmwan3-luci - unknown"
end
mArray.versions = { wrtRelease .. luciRelease .. mwanVersion .. mwanLuciVersion }
-- mwan config
local mwanConfig = ut.trim(sys.exec("cat /etc/config/mwan3"))
if mwanConfig == "" then
mwanConfig = "No data found"
end
mArray.mwanconfig = { mwanConfig }
-- network config
local networkConfig = ut.trim(sys.exec("cat /etc/config/network | sed -e 's/.*username.*/ USERNAME HIDDEN/' -e 's/.*password.*/ PASSWORD HIDDEN/'"))
if networkConfig == "" then
networkConfig = "No data found"
end
mArray.netconfig = { networkConfig }
-- ifconfig
local ifconfig = ut.trim(sys.exec("ifconfig"))
if ifconfig == "" then
ifconfig = "No data found"
end
mArray.ifconfig = { ifconfig }
-- route -n
local routeShow = ut.trim(sys.exec("route -n"))
if routeShow == "" then
routeShow = "No data found"
end
mArray.routeshow = { routeShow }
-- ip rule show
local ipRuleShow = ut.trim(sys.exec("ip rule show"))
if ipRuleShow == "" then
ipRuleShow = "No data found"
end
mArray.iprule = { ipRuleShow }
-- ip route list table 1-250
local routeList, routeString = ut.trim(sys.exec("ip rule | sed 's/://g' | awk '$1>=2001 && $1<=2250' | awk '{print $NF}'")), ""
if routeList ~= "" then
for line in routeList:gmatch("[^\r\n]+") do
routeString = routeString .. line .. "\n" .. sys.exec("ip route list table " .. line)
end
routeString = ut.trim(routeString)
else
routeString = "No data found"
end
mArray.routelist = { routeString }
-- default firewall output policy
local firewallOut = ut.trim(sys.exec("uci -p /var/state get firewall.@defaults[0].output"))
if firewallOut == "" then
firewallOut = "No data found"
end
mArray.firewallout = { firewallOut }
-- iptables
local iptables = ut.trim(sys.exec("iptables -L -t mangle -v -n"))
if iptables == "" then
iptables = "No data found"
end
mArray.iptables = { iptables }
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
| gpl-2.0 |
kitala1/darkstar | scripts/zones/Bastok-Jeuno_Airship/npcs/Michele.lua | 12 | 1994 | -----------------------------------
-- Area: Bastok-Jeuno Airship
-- NPC: Michele
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Bastok-Jeuno_Airship/TextIDs"] = nil;
require("scripts/zones/Bastok-Jeuno_Airship/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local vHour = VanadielHour();
local vMin = VanadielMinute();
while vHour >= 6 do
vHour = vHour - 6;
end
local message = WILL_REACH_BASTOK;
if (vHour == 0) then
if (vMin >= 13) then
vHour = 3;
message = WILL_REACH_JEUNO;
end
elseif (vHour == 1) then
vHour = 2;
message = WILL_REACH_JEUNO;
elseif (vHour == 2) then
vHour = 1;
message = WILL_REACH_JEUNO;
elseif (vHour == 3) then
if (vMin <= 11) then
vHour = 0;
message = WILL_REACH_JEUNO;
end
elseif (vHour == 4) then
vHour = 2;
elseif (vHour == 5) then
vHour = 1;
end
local vMinutes = 0;
if (message == WILL_REACH_JEUNO) then
vMinutes = (vHour * 60) + 11 - vMin;
else -- WILL_REACH_BASTOK
vMinutes = (vHour * 60) + 13 - vMin;
end
if (vMinutes <= 30) then
if( message == WILL_REACH_BASTOK) then
message = IN_BASTOK_MOMENTARILY;
else -- WILL_REACH_JEUNO
message = IN_JEUNO_MOMENTARILY;
end
elseif (vMinutes < 60) then
vHour = 0;
end
player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5));
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
fqrouter/luci | modules/niu/luasrc/model/cbi/niu/traffic/routes1.lua | 48 | 1869 | --[[
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$
]]--
m = Map("network", translate("Manage Traffic Routing"),
translate("With additional static routes you allow computers on your network to reach unannounced remote hosts or networks."))
local routes6 = luci.sys.net.routes6()
local bit = require "bit"
m:append(Template("niu/network/rtable"))
s = m:section(TypedSection, "route", "Static IPv4 Routes")
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface1 = s:option(ListValue, "interface", translate("Interface"))
s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network"))
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true
s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway"))
if routes6 then
s = m:section(TypedSection, "route6", "Static IPv6 Routes")
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface2 = s:option(ListValue, "interface", translate("Interface"))
s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)"))
s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true
end
m.uci:foreach("network", "interface", function(s)
if s[".name"] ~= "loopback" then
iface:value(s[".name"])
if iface2 then
iface2:value(s[".name"])
end
end
end)
return m
| apache-2.0 |
ithoq/afrimesh | villagebus/lua/common.lua | 5 | 3004 |
--[[ includes ]]------------------------------------------------------------
require "socket"
http = require "socket.http"
ltn12 = require("ltn12")
--[[ helpers ]]-------------------------------------------------------------
require "urlcode"
function getcgi(name)
local value = os.getenv(name)
return value and value or ""
end
function fail(message, module)
if module then
log:error("module " .. module .. ": " .. message)
else
log:error(message)
end
return json.encode({ error = message })
end
module("common", package.seeall)
-- Return the output of a shell command as a string
function os.pexecute(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
-- Perform requests against REST API's
function REST(request, continuation) -- { host, port, verb, path, query, data }
-- build url
if not request.port then
request.port = 80
end
local url = "http://" .. request.host .. ":" .. request.port .. request.path
if request.query then
url = url .. "?" .. urlcode.encodetable(request.query)
end
print(request.verb .. " " .. url)
-- unless I can figure out how to access header data in ltn12 we have to buffer the remote server response :-/
local content = ""
function sink(chunk, err)
if chunk then content = content .. chunk end
return 1
end
local chunk = true
function source()
if not chunk then return nil end
chunk = false
return request.data
end
-- build the request body
log:info(request.verb .. " " .. url)
local body = {
method = request.verb,
url = url,
sink = sink
}
if request.data then
request.data = json.encode(request.data)
body.headers = {}
body.headers["content-type"] = "application/json"
body.headers["content-length"] = string.len(request.data)
body.source = source
end
-- fire the request
local result = 0
local code = 0
local headers = {}
local reply = ""
-- http.USERAGENT = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-us)"
result, code, headers, reply = http.request(body)
if not headers then
return fail("request returned no headers", "http")
end
-- output response
if not headers["content-length"] then
log:debug("Adding 'content-length : " .. string.len(content) .. "' header")
headers["content-length"] = string.len(content)
end
if headers["transfer-encoding"] == "chunked" then
log:debug("Stripping transfer-encoding header")
headers["transfer-encoding"] = nil
end
log:debug("------------------------------------------------")
for key, val in pairs(headers) do
print(key .. ": " .. val)
log:debug(key .. ": " .. val)
end
print()
print(content)
log:debug("")
log:debug(content)
log:debug("------------------------------------------------")
return nil
end
| bsd-3-clause |
kitala1/darkstar | scripts/zones/Qufim_Island/npcs/Sasa_IM.lua | 28 | 3140 | -----------------------------------
-- Area: Qufim Island
-- NPC: Sasa, I.M.
-- Type: Outpost Conquest Guards
-- @pos -245.366 -20.344 299.502 126
-------------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Qufim_Island/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = QUFIMISLAND;
local csid = 0x7ff9;
-----------------------------------
-- 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 |
Eternym/psychoactive2 | data/actions/scripts/other/potions.lua | 11 | 5877 | local ultimateHealthPot = 8473
local greatHealthPot = 7591
local greatManaPot = 7590
local greatSpiritPot = 8472
local strongHealthPot = 7588
local strongManaPot = 7589
local healthPot = 7618
local manaPot = 7620
local smallHealthPot = 8704
local antidotePot = 8474
local greatEmptyPot = 7635
local strongEmptyPot = 7634
local emptyPot = 7636
local antidote = Combat()
antidote:setParameter(COMBAT_PARAM_TYPE, COMBAT_HEALING)
antidote:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE)
antidote:setParameter(COMBAT_PARAM_TARGETCASTERORTOPMOST, true)
antidote:setParameter(COMBAT_PARAM_AGGRESSIVE, false)
antidote:setParameter(COMBAT_PARAM_DISPEL, CONDITION_POISON)
local exhaust = Condition(CONDITION_EXHAUST_HEAL)
exhaust:setParameter(CONDITION_PARAM_TICKS, (configManager.getNumber(configKeys.EX_ACTIONS_DELAY_INTERVAL) - 100))
-- 1000 - 100 due to exact condition timing. -100 doesn't hurt us, and players don't have reminding ~50ms exhaustion.
function onUse(player, item, fromPosition, target, toPosition, isHotkey)
if target == nil or not target:isPlayer() then
return true
end
if player:getCondition(CONDITION_EXHAUST_HEAL) then
player:sendTextMessage(MESSAGE_STATUS_SMALL, Game.getReturnMessage(RETURNVALUE_YOUAREEXHAUSTED))
return true
end
local itemId = item:getId()
if itemId == antidotePot then
if not antidote:execute(target, numberToVariant(target:getId())) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(emptyPot, 1)
elseif itemId == smallHealthPot then
if not doTargetCombatHealth(0, target, COMBAT_HEALING, 60, 90, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(emptyPot, 1)
elseif itemId == healthPot then
if not doTargetCombatHealth(0, target, COMBAT_HEALING, 125, 175, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(emptyPot, 1)
elseif itemId == manaPot then
if not doTargetCombatMana(0, target, 75, 125, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(emptyPot, 1)
elseif itemId == strongHealthPot then
if (not isInArray({3, 4, 7, 8}, target:getVocation():getId()) or target:getLevel() < 50) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then
player:say("This potion can only be consumed by paladins and knights of level 50 or higher.", TALKTYPE_MONSTER_SAY)
return true
end
if not doTargetCombatHealth(0, target, COMBAT_HEALING, 250, 350, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(strongEmptyPot, 1)
elseif itemId == strongManaPot then
if (not isInArray({1, 2, 3, 5, 6, 7}, target:getVocation():getId()) or target:getLevel() < 50) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then
player:say("This potion can only be consumed by sorcerers, druids and paladins of level 50 or higher.", TALKTYPE_MONSTER_SAY)
return true
end
if not doTargetCombatMana(0, target, 115, 185, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(strongEmptyPot, 1)
elseif itemId == greatSpiritPot then
if (not isInArray({3, 7}, target:getVocation():getId()) or target:getLevel() < 80) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then
player:say("This potion can only be consumed by paladins of level 80 or higher.", TALKTYPE_MONSTER_SAY)
return true
end
if not doTargetCombatHealth(0, target, COMBAT_HEALING, 250, 350, CONST_ME_MAGIC_BLUE) or not doTargetCombatMana(0, target, 100, 200, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(greatEmptyPot, 1)
elseif itemId == greatHealthPot then
if (not isInArray({4, 8}, target:getVocation():getId()) or target:getLevel() < 80) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then
player:say("This potion can only be consumed by knights of level 80 or higher.", TALKTYPE_MONSTER_SAY)
return true
end
if not doTargetCombatHealth(0, target, COMBAT_HEALING, 425, 575, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(greatEmptyPot, 1)
elseif itemId == greatManaPot then
if (not isInArray({1,2,5,6}, target:getVocation():getId()) or target:getLevel() < 80) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then
player:say("This potion can only be consumed by sorcerers and druids of level 80 or higher.", TALKTYPE_MONSTER_SAY)
return true
end
if not doTargetCombatMana(0, target, 150, 250, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(greatEmptyPot, 1)
elseif itemId == ultimateHealthPot then
if (not isInArray({4, 8}, target:getVocation():getId()) or target:getLevel() < 130) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then
player:say("This potion can only be consumed by knights of level 130 or higher.", TALKTYPE_MONSTER_SAY)
return true
end
if not doTargetCombatHealth(0, target, COMBAT_HEALING, 650, 850, CONST_ME_MAGIC_BLUE) then
return false
end
player:addCondition(exhaust)
target:say("Aaaah...", TALKTYPE_MONSTER_SAY)
item:remove(1)
player:addItem(greatEmptyPot, 1)
end
return true
end
| gpl-2.0 |
kitala1/darkstar | scripts/zones/The_Sanctuary_of_ZiTah/npcs/Calliope_IM.lua | 30 | 3070 | -----------------------------------
-- Area: The Sanctuary of Zi'Tah
-- NPC: Calliope, I.M.
-- Outpost Conquest Guards
-- @pos -40.079 -0.642 -148.785 121
-----------------------------------
package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = LITELOR;
local csid = 0x7ff9;
-----------------------------------
-- 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 |
kitala1/darkstar | scripts/zones/Northern_San_dOria/npcs/Beriphaule.lua | 21 | 1946 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Beriphaule
-- Type: Allegiance Changer NPC
-- @pos -247.422 7.000 28.992 231
-----------------------------------
require("scripts/globals/conquest");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local new_nation = SANDORIA;
local old_nation = player:getNation();
local rank = getNationRank(new_nation);
if(old_nation == new_nation) then
player:startEvent(0x0260,0,0,0,old_nation);
elseif(player:getCurrentMission(old_nation) ~= 255 or player:getVar("MissionStatus") ~= 0) then
player:startEvent(0x025f,0,0,0,new_nation);
elseif(old_nation ~= new_nation) then
local has_gil = 0;
local cost = 0;
if(rank == 1) then
cost = 40000;
elseif(rank == 2) then
cost = 12000;
elseif(rank == 3) then
cost = 4000;
end
if(player:getGil() >= cost) then
has_gil = 1
end
player:startEvent(0x025e,0,1,player:getRank(),new_nation,has_gil,cost);
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 == 0x025e and option == 1) then
local new_nation = SANDORIA;
local rank = getNationRank(new_nation);
local cost = 0;
if(rank == 1) then
cost = 40000;
elseif(rank == 2) then
cost = 12000;
elseif(rank == 3) then
cost = 4000;
end
player:setNation(new_nation)
player:setGil(player:getGil() - cost);
player:setRankPoints(0);
end
end; | gpl-3.0 |
kitala1/darkstar | scripts/zones/Windurst_Waters/npcs/Upih_Khachla.lua | 30 | 2226 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Upih Khachla
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
onHalloweenTrade(player,trade,npc);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,UPIHKHACHLA_SHOP_DIALOG);
stock = {
0x43A1, 1107,1, --Grenade
0x1010, 837,1, --Potion
0x03B7, 108,1, --Wijnruit
0x027C, 119,2, --Chamomile
0x1037, 736,2, --Echo Drops
0x1020, 4445,2, --Ether
0x1034, 290,3, --Antidote
0x0764, 3960,3, --Desalinator
0x026E, 44,3, --Dried Marjoram
0x1036, 2387,3, --Eye Drops
0x025D, 180,3, --Pickaxe
0x0765, 3960,3, --Salinator
0x03FC, 276,3, --Sickle
0x04D9, 354,3 --Twinkle Powder
}
rank = getNationRank(WINDURST);
if (rank ~= 1) then
table.insert(stock,0x03fe); --Thief's Tools
table.insert(stock,3643);
table.insert(stock,3);
end
if (rank == 3) then
table.insert(stock,0x03ff); --Living Key
table.insert(stock,5520);
table.insert(stock,3);
end
showNationShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
kitala1/darkstar | scripts/globals/items/serving_of_newt_flambe.lua | 35 | 1565 | -----------------------------------------
-- ID: 4329
-- Item: serving_of_newt_flambe
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity 4
-- Mind -3
-- Attack % 18
-- Attack Cap 65
-- Virus Resist 5
-- Curse Resist 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4329);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -3);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_VIRUSRES, 5);
target:addMod(MOD_CURSERES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -3);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_VIRUSRES, 5);
target:delMod(MOD_CURSERES, 5);
end;
| gpl-3.0 |
amiraga/amirbot-supergroups | plugins/plugins.lua | 6 | 4678 | do
to_id = ""
-- 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_plugins(only_enabled)
local text = '💢 Plugins :\n'
local psum = 0
for k, v in pairs( plugins_names( )) do local status = '🚫'
psum = psum+1
pact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '⭕️'
end
pact = pact+1
end
if not only_enabled or status == '⭕️' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..status..' '..v..'\n'
end
end
local text = text..'\n'
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 '💢 plugins '..plugin_name..' does not exists.'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return '💢 plugins '..name..' does not exists.'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return '💢 plugin '..name..' disabled on this chat.'
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.'
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)
to_id = msg.to.id
-- Show the available plugins
if permissions(msg.from.id, msg.to.id, "plugins") then
if matches[1] == '#plugins' then
return list_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' then
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' then
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' then
return reload_plugins(true)
end
else
return
end
end
return {
patterns = {
"^#plugins$",
"^#plugins? (enable) ([%w_%.%-]+)$",
"^#plugins? (disable) ([%w_%.%-]+)$",
"^#plugins? (enable) ([%w_%.%-]+) (chat)",
"^#plugins? (disable) ([%w_%.%-]+) (chat)",
"^#plugins? (reload)$" },
run = run
}
end
| gpl-2.0 |
paulosalvatore/maruim_server | data/creaturescripts/scripts/offlinetraining.lua | 17 | 2368 | function onLogin(player)
local lastLogout = player:getLastLogout()
local offlineTime = lastLogout ~= 0 and math.min(os.time() - lastLogout, 86400 * 21) or 0
local offlineTrainingSkill = player:getOfflineTrainingSkill()
if offlineTrainingSkill == -1 then
player:addOfflineTrainingTime(offlineTime * 1000)
return true
end
player:setOfflineTrainingSkill(-1)
if offlineTime < 600 then
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "You must be logged out for more than 10 minutes to start offline training.")
return true
end
local trainingTime = math.max(0, math.min(offlineTime, math.min(43200, player:getOfflineTrainingTime() / 1000)))
player:removeOfflineTrainingTime(trainingTime * 1000)
local remainder = offlineTime - trainingTime
if remainder > 0 then
player:addOfflineTrainingTime(remainder * 1000)
end
if trainingTime < 60 then
return true
end
local text = "During your absence you trained for"
local hours = math.floor(trainingTime / 3600)
if hours > 1 then
text = string.format("%s %d hours", text, hours)
elseif hours == 1 then
text = string.format("%s 1 hour", text)
end
local minutes = math.floor((trainingTime % 3600) / 60)
if minutes ~= 0 then
if hours ~= 0 then
text = string.format("%s and", text)
end
if minutes > 1 then
text = string.format("%s %d minutes", text, minutes)
else
text = string.format("%s 1 minute", text)
end
end
text = string.format("%s.", text)
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, text)
local vocation = player:getVocation()
local promotion = vocation:getPromotion()
local topVocation = not promotion and vocation or promotion
local updateSkills = false
if isInArray({SKILL_CLUB, SKILL_SWORD, SKILL_AXE, SKILL_DISTANCE}, offlineTrainingSkill) then
local modifier = topVocation:getAttackSpeed() / 1000
updateSkills = player:addOfflineTrainingTries(offlineTrainingSkill, (trainingTime / modifier) / (offlineTrainingSkill == SKILL_DISTANCE and 4 or 2))
elseif offlineTrainingSkill == SKILL_MAGLEVEL then
local gainTicks = topVocation:getManaGainTicks() * 2
if gainTicks == 0 then
gainTicks = 1
end
updateSkills = player:addOfflineTrainingTries(SKILL_MAGLEVEL, trainingTime * (vocation:getManaGainAmount() / gainTicks))
end
if updateSkills then
player:addOfflineTrainingTries(SKILL_SHIELD, trainingTime / 4)
end
return true
end
| gpl-2.0 |
ZenityRTS/Zenity | libs/chiliui/luaui/chili/chili/handlers/skinhandler.lua | 2 | 4943 | --//=============================================================================
--// Theme
SkinHandler = {}
--//=============================================================================
--// load shared skin utils
local SkinUtilsEnv = {}
setmetatable(SkinUtilsEnv,{__index = getfenv()})
VFS.Include(CHILI_DIRNAME .. "headers/skinutils.lua", SkinUtilsEnv)
--//=============================================================================
--// translates the skin's FileNames to the correct FilePaths
--// (skins just define the name not the path!)
local function SplitImageOptions(str)
local options, str2 = str:match "^(:.*:)(.*)"
if (options) then
return options, str2
else
return "", str
end
end
local function TranslateFilePaths(skinConfig, dirs)
for i,v in pairs(skinConfig) do
if (i == "info") then
--// nothing
elseif istable(v) then
TranslateFilePaths(v, dirs)
elseif isstring(v) then
local opt, fileName = SplitImageOptions(v)
for _,dir in ipairs(dirs) do
local filePath = dir .. fileName
if VFS.FileExists(filePath) then
skinConfig[i] = opt .. filePath
break
end
end
end
end
end
--//=============================================================================
--// load all skins
knownSkins = {}
SkinHandler.knownSkins = knownSkins
local n = 1
local skinDirs = VFS.SubDirs(SKIN_DIRNAME , "*", VFS.RAW_FIRST)
for i,dir in ipairs(skinDirs) do
local skinCfgFile = dir .. 'skin.lua'
if (VFS.FileExists(skinCfgFile, VFS.RAW_FIRST)) then
--// use a custom enviroment (safety + auto loads skin utils)
local senv = {SKINDIR = dir}
setmetatable(senv,{__index = SkinUtilsEnv})
--// load the skin
local skinConfig = VFS.Include(skinCfgFile,senv, VFS.RAW_FIRST)
if (skinConfig)and(type(skinConfig)=="table")and(type(skinConfig.info)=="table") then
skinConfig.info.dir = dir
SkinHandler.knownSkins[n] = skinConfig
SkinHandler.knownSkins[skinConfig.info.name:lower()] = skinConfig
n = n + 1
end
end
end
--//FIXME handle multiple-dependencies correctly! (atm it just works with 1 level!)
--// translate filepaths and handle dependencies
for i,skinConfig in ipairs(SkinHandler.knownSkins) do
local dirs = { skinConfig.info.dir }
--// translate skinName -> skinDir and remove broken dependencies
local brokenDependencies = {}
for i,dependSkinName in ipairs(skinConfig.info.depend or {}) do
local dependSkin = SkinHandler.knownSkins[dependSkinName:lower()]
if (dependSkin) then
dirs[#dirs+1] = dependSkin.info.dir
table.merge(skinConfig, dependSkin)
else
Spring.Log("Chili", "error", "Skin " .. skinConfig.info.name .. " depends on an unknown skin named " .. dependSkinName .. ".")
end
end
--// add the default skindir to the end
dirs[#dirs+1] = SKIN_DIRNAME .. 'default/'
--// finally translate all paths
TranslateFilePaths(skinConfig, dirs)
end
--//=============================================================================
--// Internal
local function GetSkin(skinname)
return SkinHandler.knownSkins[tostring(skinname):lower()]
end
SkinHandler.defaultSkin = GetSkin('default')
--//=============================================================================
--// API
function SkinHandler.IsValidSkin(skinname)
return (not not GetSkin(skinname))
end
function SkinHandler.GetSkinInfo()
local sk = GetSkin(skinname)
if (sk) then
return table.shallowcopy(sk.info)
end
return {}
end
function SkinHandler.GetAvailableSkins()
local skins = {}
local knownSkins = SkinHandler.knownSkins
for i=1,#knownSkins do
skins[i] = knownSkins[i].info.name
end
return skins
end
local function MergeProperties(obj, skin, classname)
local skinclass = skin[classname]
if not skinclass then return end
BackwardCompa(skinclass)
table.merge(obj, skinclass)
MergeProperties(obj, skin, skinclass.clone)
end
function SkinHandler.LoadSkin(control, class)
local skin = GetSkin(control.skinName)
local defskin = SkinHandler.defaultSkin
local found = false
local inherited = class.inherited
local classname = control.classname
repeat
--FIXME scan whole `depend` table
if (skin) then
--if (skin[classname]) then
MergeProperties(control, skin, classname) -- per-class defaults
MergeProperties(control, skin, "general")
if (skin[classname]) then
found = true
end
end
if (defskin[classname]) then
MergeProperties(control, defskin, classname) -- per-class defaults
MergeProperties(control, defskin, "general")
found = true
end
if inherited then
classname = inherited.classname
inherited = inherited.inherited
else
found = true
end
until (found)
end | gpl-2.0 |
kitala1/darkstar | scripts/zones/Quicksand_Caves/npcs/_5s9.lua | 19 | 1272 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -345 0 820 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-352);
local difZ = player:getZPos()-(820);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if(Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
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 |
kitala1/darkstar | scripts/commands/changesjob.lua | 26 | 1952 | ---------------------------------------------------------------------------------------------------
-- func: changesjob
-- desc: Changes the players current subjob.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "si"
};
function onTrigger(player, job, level)
local jobList =
{
["war"] = 1,
["mnk"] = 2,
["whm"] = 3,
["blm"] = 4,
["rdm"] = 5,
["thf"] = 6,
["pld"] = 7,
["drk"] = 8,
["bst"] = 9,
["brd"] = 10,
["rng"] = 11,
["sam"] = 12,
["nin"] = 13,
["drg"] = 14,
["smn"] = 15,
["blu"] = 16,
["cor"] = 17,
["pup"] = 18,
["dnc"] = 19,
["sch"] = 20,
["geo"] = 21,
["run"] = 22
};
if (job == nil) then
player:PrintToPlayer("You must enter a job id or short-name.");
return;
end
local jobId = 0;
if (tonumber(job) ~= nil and tonumber(job) ~= 0) then
jobId = job;
else
jobId = jobList[ string.lower( job ) ];
if (jobId == nil) then
player:PrintToPlayer( string.format( "Invalid job '%s' given. Use short name or id. e.g. WAR", job ) );
return;
end
end
-- Ensure player entered a valid id..
if (jobId <= 0 or jobId > 22) then
player:PrintToPlayer( "Invalid job id given; must be between 1 and 22. Or use a short name e.g. WAR" );
return;
end
-- Change the players subjob..
player:changesJob( jobId );
-- Attempt to set the players subjob level..
if (level ~= nil and level > 0 and level <= 99) then
player:setsLevel( level );
else
player:PrintToPlayer( "Invalid level given. Level must be between 1 and 99!" );
end
end | gpl-3.0 |
hanxi/cocos2d-x-v3.1 | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/DisplayManager.lua | 3 | 3590 |
--------------------------------
-- @module DisplayManager
-- @extend Ref
--------------------------------
-- @function [parent=#DisplayManager] getDisplayRenderNode
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- @function [parent=#DisplayManager] getAnchorPointInPoints
-- @param self
-- @return Vec2#Vec2 ret (return value: cc.Vec2)
--------------------------------
-- @function [parent=#DisplayManager] getDisplayRenderNodeType
-- @param self
-- @return DisplayType#DisplayType ret (return value: ccs.DisplayType)
--------------------------------
-- @function [parent=#DisplayManager] removeDisplay
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#DisplayManager] setForceChangeDisplay
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#DisplayManager] init
-- @param self
-- @param #ccs.Bone bone
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#DisplayManager] getContentSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @function [parent=#DisplayManager] getBoundingBox
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
-- overload function: addDisplay(cc.Node, int)
--
-- overload function: addDisplay(ccs.DisplayData, int)
--
-- @function [parent=#DisplayManager] addDisplay
-- @param self
-- @param #ccs.DisplayData displaydata
-- @param #int int
--------------------------------
-- overload function: containPoint(float, float)
--
-- overload function: containPoint(cc.Vec2)
--
-- @function [parent=#DisplayManager] containPoint
-- @param self
-- @param #float float
-- @param #float float
-- @return bool#bool ret (retunr value: bool)
--------------------------------
-- @function [parent=#DisplayManager] changeDisplayWithIndex
-- @param self
-- @param #int int
-- @param #bool bool
--------------------------------
-- @function [parent=#DisplayManager] changeDisplayWithName
-- @param self
-- @param #string str
-- @param #bool bool
--------------------------------
-- @function [parent=#DisplayManager] isForceChangeDisplay
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#DisplayManager] getCurrentDisplayIndex
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#DisplayManager] getAnchorPoint
-- @param self
-- @return Vec2#Vec2 ret (return value: cc.Vec2)
--------------------------------
-- @function [parent=#DisplayManager] getDecorativeDisplayList
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- @function [parent=#DisplayManager] isVisible
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#DisplayManager] setVisible
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#DisplayManager] create
-- @param self
-- @param #ccs.Bone bone
-- @return DisplayManager#DisplayManager ret (return value: ccs.DisplayManager)
--------------------------------
-- @function [parent=#DisplayManager] DisplayManager
-- @param self
return nil
| mit |
kitala1/darkstar | scripts/globals/mobskills/Optic_Induration.lua | 7 | 1334 | ---------------------------------------------
-- Optic Induration
--
-- Description: Charges up a powerful, calcifying beam directed at targets in a fan-shaped area of effect. Additional effect: Petrification & enmity reset
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes: Charges up (three times) before actually being used (except Jailer of Temperance, who doesn't need to charge it up). The petrification lasts a very long time.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:AnimationSub() == 2 or mob:AnimationSub() == 3) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PETRIFICATION;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 60);
local dmgmod = 1;
local accmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_DARK,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
mob:resetEnmity(target);
return dmg;
end;
| gpl-3.0 |
fastmailops/prosody | util/caps.lua | 5 | 2063 | -- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local base64 = require "util.encodings".base64.encode;
local sha1 = require "util.hashes".sha1;
local t_insert, t_sort, t_concat = table.insert, table.sort, table.concat;
local ipairs = ipairs;
module "caps"
function calculate_hash(disco_info)
local identities, features, extensions = {}, {}, {};
for _, tag in ipairs(disco_info) do
if tag.name == "identity" then
t_insert(identities, (tag.attr.category or "").."\0"..(tag.attr.type or "").."\0"..(tag.attr["xml:lang"] or "").."\0"..(tag.attr.name or ""));
elseif tag.name == "feature" then
t_insert(features, tag.attr.var or "");
elseif tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then
local form = {};
local FORM_TYPE;
for _, field in ipairs(tag.tags) do
if field.name == "field" and field.attr.var then
local values = {};
for _, val in ipairs(field.tags) do
val = #val.tags == 0 and val:get_text();
if val then t_insert(values, val); end
end
t_sort(values);
if field.attr.var == "FORM_TYPE" then
FORM_TYPE = values[1];
elseif #values > 0 then
t_insert(form, field.attr.var.."\0"..t_concat(values, "<"));
else
t_insert(form, field.attr.var);
end
end
end
t_sort(form);
form = t_concat(form, "<");
if FORM_TYPE then form = FORM_TYPE.."\0"..form; end
t_insert(extensions, form);
end
end
t_sort(identities);
t_sort(features);
t_sort(extensions);
if #identities > 0 then identities = t_concat(identities, "<"):gsub("%z", "/").."<"; else identities = ""; end
if #features > 0 then features = t_concat(features, "<").."<"; else features = ""; end
if #extensions > 0 then extensions = t_concat(extensions, "<"):gsub("%z", "<").."<"; else extensions = ""; end
local S = identities..features..extensions;
local ver = base64(sha1(S));
return ver, S;
end
return _M;
| mit |
paulosalvatore/maruim_server | data/modules/scripts/gamestore/gamestore.lua | 1 | 2364 | -- Parser
dofile('data/modules/scripts/gamestore/init.lua')
-- Config
GameStore.Categories = {
-- You can use default key [...] or ["..."] or name (=)
--[[ example = ]] { name = "Examples",
state = GameStore.States.STATE_NEW,
icons = {"Category_Mounts.png"},
offers = {
-- Stackable Item Example : thingId = itemId
{name = "Crystal Coin", thingId = 2160, count = 200, type = GameStore.OfferTypes.OFFER_TYPE_STACKABLE, price = 150, icons = {"Product_CC.png"}, description = "Become rich!"},
-- Normal Item Example : thingId = itemId
{name = "Sword", thingId = 2376, count = 3, type = GameStore.OfferTypes.OFFER_TYPE_ITEM, price = 150, icons = {"Product_CC.png"}, description = "Become rich!"},
-- Outfit Example : thingId = lookType
{name = "Dream Warden Outfit", thingId = {male=577,female=578}, type = GameStore.OfferTypes.OFFER_TYPE_OUTFIT, price = 250, icons = {"Product_DreamWarden.png"}},
-- Addon Example : thingId = lookType, addon = ( 1 = addon 1, 2 = addon 2, 3 = both addons)
{name = "Dream Warden Addon 1", thingId = {male=577,female=578}, addon = 1, type = GameStore.OfferTypes.OFFER_TYPE_OUTFIT_ADDON, price = 320, icons = {"Product_DreamWarden_Addon1"}},
-- Mount Example : thingId = mountId
{name = "Titanica", thingId = 7, type = GameStore.OfferTypes.OFFER_TYPE_MOUNT, price = 620, icons = {"Product_Titanica.png"}, description = "This mount looks so hot!"},
-- NameChange example
-- NameChange example
{name = "Character Name Change", type = GameStore.OfferTypes.OFFER_TYPE_NAMECHANGE, price = 500, icons = {"Product_NameChange.png"}},
-- Sexchange example
{name = "Character Sex Change", type = GameStore.OfferTypes.OFFER_TYPE_SEXCHANGE, price = 200, icons = {"Product_SexChange.png"}},
-- Promotion example
{name = "First Promotion", thingId = 1--[[ed/ms/rp/ek]], type = GameStore.OfferTypes.OFFER_TYPE_PROMOTION, price = 300, icons = {"Product_Promotion1.png"}}
}
},
}
-- For Explanation and information
-- view the readme.md file in github or via markdown viewer.
-- Non-Editable
local runningId = 1
for k, category in ipairs(GameStore.Categories) do
if category.offers then
for m, offer in ipairs(category.offers) do
offer.id = runningId
runningId = runningId + 1
if not offer.type then
offer.type = GameStore.OfferTypes.OFFER_TYPE_NONE
end
end
end
end | gpl-2.0 |
kitala1/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/mobs/Ix_ghrah.lua | 13 | 1306 | -----------------------------------
-- Area: Grand Palace of HuXzoi
-- NPC: Ix_ghrah
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/missions");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
if(mob:getMod(0x31))then mob:setMod(0x31,1000); end
if(mob:getMod(0x32))then mob:setMod(0x32,1000); end
if(mob:getMod(0x33))then mob:setMod(0x33,1000); end
if(mob:getMod(0x34))then mob:setMod(0x34,1000); end
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local changeTime = mob:getLocalVar("changeTime");
if(mob:getBattleTime() - changeTime > 60) then
mob:AnimationSub(math.random(0,3));
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
if(killer:getCurrentMission(COP) == A_FATE_DECIDED and killer:getVar("PromathiaStatus")==1)then
killer:setVar("PromathiaStatus",2);
end
end; | gpl-3.0 |
kitala1/darkstar | scripts/zones/Tavnazian_Safehold/npcs/_0q1.lua | 17 | 1896 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Sewer Entrance
-- @pos 28 -12 44 26
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(COP) == THE_LOST_CITY and player:getVar("PromathiaStatus") > 0)then
player:startEvent(0x0067);
elseif(player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus")==3)then
player:startEvent(0x0074);
elseif(player:getCurrentMission(COP) >= DISTANT_BELIEFS or hasCompletedMission(COP,THE_LAST_VERSE))then
player:startEvent(0x01f6);
else
--player:messageSpecial();
end
return 1;
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 == 0x0067)then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,THE_LOST_CITY);
player:addMission(COP,DISTANT_BELIEFS);
elseif(csid == 0x0074)then
player:setVar("PromathiaStatus",4);
elseif(csid == 0x01f6 and option == 1)then
player:setPos(260.068,0,-283.568,190,27); -- To Phomiuna Aqueducts {R}
end
end;
| gpl-3.0 |
kitala1/darkstar | scripts/globals/items/aspir_knife.lua | 15 | 1103 | -----------------------------------------
-- ID: 16509
-- Item: Aspir Knife
-- Additional effect: MP Drain
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance or target:isUndead()) then
return 0,0,0;
else
local drain = math.random(1,3);
local params = {};
params.bonusmab = 0;
params.includemab = false;
-- drain = addBonusesAbility(player, ELE_DARK, target, drain, params);
drain = drain * applyResistanceAddEffect(player,target,ELE_DARK,0);
drain = adjustForTarget(target,drain,ELE_DARK);
drain = finalMagicNonSpellAdjustments(player,target,ELE_DARK,drain);
if (drain > target:getMP()) then
drain = target:getMP();
end
target:addMP(-drain);
return SUBEFFECT_MP_DRAIN, 162, player:addMP(drain);
end
end; | gpl-3.0 |
kitala1/darkstar | scripts/zones/Windurst_Walls/npcs/Ambrosius.lua | 36 | 4204 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Ambrosius
--
-- Quest NPC for "The Postman Always KOs Twice"
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
QuestStatus = player:getQuestStatus(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE);
if (QuestStatus == QUEST_AVAILABLE) then
player:startEvent(0x0030);
elseif (QuestStatus == QUEST_ACCEPTED) then
player:startEvent(0x0031);
elseif (QuestStatus == QUEST_COMPLETED) then
player:startEvent(0x0038);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
QuestStatus = player:getQuestStatus(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE);
if (QuestStatus ~= QUEST_AVAILABLE) then
reward = 0;
if (trade:hasItemQty(584,1)) then reward = reward+1 end;
if (trade:hasItemQty(585,1)) then reward = reward+1 end;
if (trade:hasItemQty(586,1)) then reward = reward+1 end;
if (trade:hasItemQty(587,1)) then reward = reward+1 end;
if (trade:getItemCount() == reward) then
if (reward == 1) then
if (QuestStatus == QUEST_ACCEPTED) then
player:startEvent(0x0034,GIL_RATE*50);
elseif (QuestStatus == QUEST_COMPLETED) then
player:startEvent(0x0039,GIL_RATE*50);
end
elseif (reward == 2) then
if (QuestStatus == QUEST_ACCEPTED) then
player:startEvent(0x0035,GIL_RATE*150,2);
elseif (QuestStatus == QUEST_COMPLETED) then
player:startEvent(0x003a,GIL_RATE*150,2);
end
elseif (reward == 3) then
if (QuestStatus == QUEST_ACCEPTED) then
player:startEvent(0x0036,GIL_RATE*250,3);
elseif (QuestStatus == QUEST_COMPLETED) then
player:startEvent(0x003b,GIL_RATE*250,3);
end
elseif (reward == 4) then
if (QuestStatus == QUEST_ACCEPTED) then
player:startEvent(0x0037,GIL_RATE*500,4);
elseif (QuestStatus == QUEST_COMPLETED) then
player:startEvent(0x003c,GIL_RATE*500,4);
end
end
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("Update CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("Finish CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0030 and option == 0) then
player:addQuest(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE);
elseif (csid == 0x0034) then
player:tradeComplete();
player:addGil(GIL_RATE*50);
player:addFame(WINDURST,WIN_FAME*80);
player:completeQuest(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE);
elseif (csid == 0x0035) then
player:tradeComplete();
player:addGil(GIL_RATE*150);
player:addFame(WINDURST,WIN_FAME*80);
player:completeQuest(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE);
elseif (csid == 0x0036) then
player:tradeComplete();
player:addGil(GIL_RATE*250);
player:addFame(WINDURST,WIN_FAME*80);
player:completeQuest(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE);
elseif (csid == 0x0037) then
player:tradeComplete();
player:addGil(GIL_RATE*500);
player:addFame(WINDURST,WIN_FAME*80);
player:completeQuest(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE);
elseif (csid == 0x0039) then
player:tradeComplete();
player:addGil(GIL_RATE*50);
player:addFame(WINDURST,WIN_FAME*5);
elseif (csid == 0x003a) then
player:tradeComplete();
player:addGil(GIL_RATE*150);
player:addFame(WINDURST,WIN_FAME*15);
elseif (csid == 0x003b) then
player:tradeComplete();
player:addGil(GIL_RATE*250);
player:addFame(WINDURST,WIN_FAME*25);
elseif (csid == 0x003c) then
player:tradeComplete();
player:addGil(GIL_RATE*500);
player:addFame(WINDURST,WIN_FAME*50);
end
end;
| gpl-3.0 |
kitala1/darkstar | scripts/zones/West_Sarutabaruta/npcs/Naguipeillont_RK.lua | 30 | 3074 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Naguipeillont, R.K.
-- Type: Outpost Conquest Guards
-- @pos -11.322 -13.459 317.696 115
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/West_Sarutabaruta/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = SARUTABARUTA;
local csid = 0x7ffb;
-----------------------------------
-- 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 |
CTPST/resizebot | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
king98tm/mohammadking98 | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-3.0 |
shahabsaf1/uzz-bot | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
kitala1/darkstar | scripts/zones/Yughott_Grotto/npcs/Treasure_Chest.lua | 12 | 2565 | -----------------------------------
-- Area: Yughott Grotto
-- NPC: Treasure Chest
-- @zone 142
-----------------------------------
package.loaded["scripts/zones/Yughott_Grotto/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/treasure");
require("scripts/zones/Yughott_Grotto/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1024,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if((trade:hasItemQty(1024,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if(pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if(success ~= -2) then
player:tradeComplete();
if(math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if(loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1024);
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 |
kitala1/darkstar | scripts/zones/Port_Bastok/Zone.lua | 28 | 3713 | -----------------------------------
--
-- Zone: Port_Bastok (236)
--
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/zone");
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1,-112,-3,-17,-96,3,-3);--event COP
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;
-- FIRST LOGIN (START CS)
if (player:getPlaytime(false) == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 0x0001;
end
player:setPos(132,-8.5,-13,179);
player:setHomePoint();
end
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
if (prevZone == 224) then
cs = 0x0049;
player:setPos(-36.000, 7.000, -58.000, 194);
else
position = math.random(1,5) + 57;
player:setPos(position,8.5,-239,192);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
end
if (player:getCurrentMission(COP) == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus") == 0) then
cs = 0x0132;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
local regionID =region:GetRegionID();
-- printf("regionID: %u",regionID);
if (regionID == 1 and player:getCurrentMission(COP) == THE_CALL_OF_THE_WYRMKING and player:getVar("PromathiaStatus") == 0) then
player:startEvent(0x0131);
end
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x0047);
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
player:messageSpecial(ITEM_OBTAINED,536);
elseif (csid == 0x0047) then
player:setPos(0,0,0,0,224);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif (csid == 0x0131) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x0132) then
player:setVar("COP_optional_CS_chasalvigne",0);
player:setVar("COP_optional_CS_Anoki",0);
player:setVar("COP_optional_CS_Despachaire",0);
player:setVar("PromathiaStatus",1);
end
end; | gpl-3.0 |
kitala1/darkstar | scripts/zones/Waughroon_Shrine/bcnms/on_my_way.lua | 13 | 1878 | -----------------------------------
-- Area: Waughroon Shrine
-- Name: Mission Rank 7-2 (Bastok)
-- @pos -345 104 -260 144
-----------------------------------
package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Waughroon_Shrine/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if(player:hasCompletedMission(BASTOK,ON_MY_WAY)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0);
end
elseif(leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if(csid == 0x7d01) then
if((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 2)) then
player:addKeyItem(LETTER_FROM_WEREI);
player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_WEREI);
player:setVar("MissionStatus",3);
end
end
end; | gpl-3.0 |
Tigerism/tigerbot | resources/translations/en.lua | 1 | 3537 | return {
bots = "Bots",
ping = {
ping = "pinging....",
pong = "pong ``{{arg1}}ms``",
description = "shows latency information"
},
help = {
embedTitle = "Help for Tiger 2.0",
embedDescription = "Hello! I'm Tiger, a bot written in Lua with the Discordia library.\nUse the reaction buttons to filter through the command list.\n\nRemember: for most commands, if it requires a prompt, you can skip it with the ``|`` character. For example: ``tiger ban @user | reason | duration``. If a command is restricted for you, you can grant it with ``tiger perms``.\n\nFinally, most commands have what are called **flags.** A flag allows you to further customize a command. Flags start with two dashes and go at the **END** of the command. Flags may contain arguments.\nTo view detailed information on a command, use the ``--help`` flag. For example: ``tiger ban --help`` will show you information on a command. It'll also show you other flags you can use. Example: ``tiger prune 100 --bots --contains test`` will look through 100 messages and prune the ones created by bots that contain the text 'test'.\n\nOfficial links: [Discord Server](https://discord.gg/62qYz8J) | [Invite](https://discordapp.com/oauth2/authorize?&client_id=225079733799485441&scope=bot&permissions=8)\n",
description = "shows this menu",
},
reload = {
description = "reloads a module",
failed = "Module failed to reload: ``{{arg1}}``",
success = "Successfully reloaded module ``{{arg1}}``",
noname = "Please specify a module name."
},
autorole = {
name = "Autoroles",
description = "sets up an automatic role.",
firstPrompt = "Would you like to **create** an autorole, **delete** an existing one, or **list** the current autoroles?",
secondPrompt = "What condition would you like to apply to this role?\nConditions: **get**, **join**, **bot**",
choices = {
create = "create",
delete = "delete",
list = "list",
get = "get",
join = "join",
bot = "bot"
},
roleFind = "What **role** are you targeting?",
saveSuccess = "Successfully **saved** your new autorole.",
roleError = "Cannot create an autorole for a role that is higher than your highest role.",
roleDelete = "Successfully **deleted** your autorole.",
invalidRoles = "Invalid Roles",
none = "None to show.",
autorolesFor = "Autoroles for **{{arg1}}**"
},
server = {
description = "view detailed server information.",
largeServer = "Large Server",
owner = "Owner",
emojis = "Emojis",
members = "Members",
},
invite = {
title = "Invite Tiger",
botInvite = "Bot Invite",
helpInvite = "Help Server Invite",
description = "invites Tiger to your server."
},
user = {
description = "view detailed user information."
},
stats = {
description = "shows detailed information about Tiger."
},
["8ball"] = {
description = "predict the future!"
},
flipcoin = {
description = "flip a coin."
},
cat = {
description = "sends a random picture of a cat."
},
dog = {
description = "sends a random picture of a dog."
},
perms = {
description = "configure command permissions."
},
giphy = {
description = "searches giphy for a query."
}
} | mit |
mickael9/cut-and-paste | prototypes/items.lua | 1 | 3082 | data:extend{
{
-- This item is used to select a zone to cut & paste
type = "selection-tool",
name = mod.tools.cut,
icon = mod.dir .. "/graphics/icons/cut-tool.png",
flags = {"goes-to-quickbar"},
subgroup = "tool",
order = "c[automated-construction]-a[blueprint]",
stack_size = 1,
stackable = false,
selection_color = { r = 1, g = 0.5, b = 0 },
alt_selection_color = { r = 1, g = 0.5, b = 0 },
selection_mode = {"blueprint"},
alt_selection_mode = {"any-tile"},
selection_cursor_box_type = "copy",
alt_selection_cursor_box_type = "copy",
},
{
-- This item is used to select a zone to copy & paste
type = "selection-tool",
name = mod.tools.copy,
icon = mod.dir .. "/graphics/icons/copy-tool.png",
flags = {"goes-to-quickbar"},
subgroup = "tool",
order = "c[automated-construction]-a[blueprint]",
stack_size = 1,
stackable = false,
selection_color = { r = 1, g = 0.5, b = 0 },
alt_selection_color = { r = 1, g = 0.5, b = 0 },
selection_mode = {"blueprint"},
alt_selection_mode = {"any-tile"},
selection_cursor_box_type = "copy",
alt_selection_cursor_box_type = "copy",
},
{
-- This blueprint type is used to contain the user's selection
type = "blueprint",
name = mod.blueprints.copy,
icon = mod.dir .. "/graphics/icons/blueprint.png",
flags = {"goes-to-quickbar", "hidden"},
subgroup = "tool",
order = "c[automated-construction]-a[blueprint]",
stack_size = 1,
stackable = false,
selection_color = { r = 0, g = 1, b = 0 },
alt_selection_color = { r = 0, g = 1, b = 0 },
selection_mode = {"cancel-deconstruct"},
alt_selection_mode = {"cancel-deconstruct"},
selection_cursor_box_type = "not-allowed",
alt_selection_cursor_box_type = "not-allowed",
},
{
-- This blueprint type is used to contain the user's selection
type = "blueprint",
name = mod.blueprints.cut,
icon = mod.dir .. "/graphics/icons/blueprint.png",
flags = {"goes-to-quickbar", "hidden"},
subgroup = "tool",
order = "c[automated-construction]-a[blueprint]",
stack_size = 1,
stackable = false,
selection_color = { r = 0, g = 1, b = 0 },
alt_selection_color = { r = 0, g = 1, b = 0 },
selection_mode = {"cancel-deconstruct"},
alt_selection_mode = {"cancel-deconstruct"},
selection_cursor_box_type = "not-allowed",
alt_selection_cursor_box_type = "not-allowed",
},
{
-- Not a real item, just needs to exist for the placeholder item to be able to be in a blueprint.
type = "item",
name = mod.placeholder,
icon = mod.dir .. "/graphics/icons/empty.png",
flags = {"hidden"},
order = "z",
place_result = mod.placeholder,
stack_size = 1,
},
}
| mit |
Pulse-Eight/drivers | Control4/neo_Common/common/p8core.lua | 1 | 1550 | --Copyright Pulse-Eight Limited 2016
function P8INT:GET_MATRIX_URL()
local ip = Properties["Device IP Address"] or ""
return "http://" .. ip
end
function P8INT:DISCOVER()
C4:urlGet("http://www.gotomymatrix.com", {}, false,
function(ticketId, strData, responseCode, tHeaders, strError)
if responseCode == 302 then
local httpLocation = tHeaders["Location"]
httpLocation = string.gsub(httpLocation, "http://", "")
httpLocation = string.gsub(httpLocation, "/", "")
UpdateProperty("Device IP Address", httpLocation)
LogInfo("Device IP Address has been updated to: " .. httpLocation)
FirstRun()
else
LogWarn("Failed to discover your system, please visit www.gotomymatrix.com in your browser for more information")
end
end)
end
function P8INT:SET_ONLINE_STATUS(status)
if (status == "offline") then
if (DEVICE_ONLINE == 1) then
C4:SetBindingStatus(6000, "offline")
DEVICE_ONLINE = 0
end
elseif (status == "online") then
if (DEVICE_ONLINE == 0) then
C4:SetBindingStatus(6000, "online")
DEVICE_ONLINE = 1
end
end
end
function ON_PROPERTY_CHANGED.DeviceIPAddress(propertyValue)
C4:SetBindingAddress(6000, propertyValue)
FirstRun()
end
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function OnNetworkBindingChanged( idBinding, bIsBound)
if (idBinding == 6000) then
if (bIsBound == true) then
UpdateProperty("Device IP Address", C4:GetBindingAddress (6000))
FirstRun()
end
end
end | apache-2.0 |
kitala1/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Fari-Wari.lua | 34 | 1034 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Fari-Wari
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x033F);
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 |
Taracque/epgp | libs/LibDeformat-3.0/LibDeformat-3.0.lua | 1 | 9487 | --[[
Name: LibDeformat-3.0
Author(s): ckknight (ckknight@gmail.com)
Website: http://www.wowace.com/projects/libdeformat-3-0/
Description: A library to convert a post-formatted string back to its original arguments given its format string.
License: MIT
]]
local LibDeformat = LibStub:NewLibrary("LibDeformat-3.0", 1)
if not LibDeformat then
return
end
-- this function does nothing and returns nothing
local function do_nothing()
end
-- a dictionary of format to match entity
local FORMAT_SEQUENCES = {
["s"] = ".+",
["c"] = ".",
["%d*d"] = "%%-?%%d+",
["[fg]"] = "%%-?%%d+%%.?%%d*",
["%%%.%d[fg]"] = "%%-?%%d+%%.?%%d*",
}
-- a set of format sequences that are string-based, i.e. not numbers.
local STRING_BASED_SEQUENCES = {
["s"] = true,
["c"] = true,
}
local cache = setmetatable({}, {__mode='k'})
-- generate the deformat function for the pattern, or fetch from the cache.
local function get_deformat_function(pattern)
local func = cache[pattern]
if func then
return func
end
-- escape the pattern, so that string.match can use it properly
local unpattern = '^' .. pattern:gsub("([%(%)%.%*%+%-%[%]%?%^%$%%])", "%%%1") .. '$'
-- a dictionary of index-to-boolean representing whether the index is a number rather than a string.
local number_indexes = {}
-- (if the pattern is a numbered format,) a dictionary of index-to-real index.
local index_translation = nil
-- the highest found index, also the number of indexes found.
local highest_index
if not pattern:find("%%1%$") then
-- not a numbered format
local i = 0
while true do
i = i + 1
local first_index
local first_sequence
for sequence in pairs(FORMAT_SEQUENCES) do
local index = unpattern:find("%%%%" .. sequence)
if index and (not first_index or index < first_index) then
first_index = index
first_sequence = sequence
end
end
if not first_index then
break
end
unpattern = unpattern:gsub("%%%%" .. first_sequence, "(" .. FORMAT_SEQUENCES[first_sequence] .. ")", 1)
number_indexes[i] = not STRING_BASED_SEQUENCES[first_sequence]
end
highest_index = i - 1
else
-- a numbered format
local i = 0
while true do
i = i + 1
local found_sequence
for sequence in pairs(FORMAT_SEQUENCES) do
if unpattern:find("%%%%" .. i .. "%%%$" .. sequence) then
found_sequence = sequence
break
end
end
if not found_sequence then
break
end
unpattern = unpattern:gsub("%%%%" .. i .. "%%%$" .. found_sequence, "(" .. FORMAT_SEQUENCES[found_sequence] .. ")", 1)
number_indexes[i] = not STRING_BASED_SEQUENCES[found_sequence]
end
highest_index = i - 1
i = 0
index_translation = {}
pattern:gsub("%%(%d)%$", function(w)
i = i + 1
index_translation[i] = tonumber(w)
end)
end
if highest_index == 0 then
cache[pattern] = do_nothing
else
--[=[
-- resultant function looks something like this:
local unpattern = ...
return function(text)
local a1, a2 = text:match(unpattern)
if not a1 then
return nil, nil
end
return a1+0, a2
end
-- or if it were a numbered pattern,
local unpattern = ...
return function(text)
local a2, a1 = text:match(unpattern)
if not a1 then
return nil, nil
end
return a1+0, a2
end
]=]
local t = {}
t[#t+1] = [=[
return function(text)
local ]=]
for i = 1, highest_index do
if i ~= 1 then
t[#t+1] = ", "
end
t[#t+1] = "a"
if not index_translation then
t[#t+1] = i
else
t[#t+1] = index_translation[i]
end
end
t[#t+1] = [=[ = text:match(]=]
t[#t+1] = ("%q"):format(unpattern)
t[#t+1] = [=[)
if not a1 then
return ]=]
for i = 1, highest_index do
if i ~= 1 then
t[#t+1] = ", "
end
t[#t+1] = "nil"
end
t[#t+1] = "\n"
t[#t+1] = [=[
end
]=]
t[#t+1] = "return "
for i = 1, highest_index do
if i ~= 1 then
t[#t+1] = ", "
end
t[#t+1] = "a"
t[#t+1] = i
if number_indexes[i] then
t[#t+1] = "+0"
end
end
t[#t+1] = "\n"
t[#t+1] = [=[
end
]=]
t = table.concat(t, "")
-- print(t)
cache[pattern] = assert(loadstring(t))()
end
return cache[pattern]
end
--- Return the arguments of the given format string as found in the text.
-- @param text The resultant formatted text.
-- @param pattern The pattern used to create said text.
-- @return a tuple of values, either strings or numbers, based on the pattern.
-- @usage LibDeformat.Deformat("Hello, friend", "Hello, %s") == "friend"
-- @usage LibDeformat.Deformat("Hello, friend", "Hello, %1$s") == "friend"
-- @usage LibDeformat.Deformat("Cost: $100", "Cost: $%d") == 100
-- @usage LibDeformat.Deformat("Cost: $100", "Cost: $%1$d") == 100
-- @usage LibDeformat.Deformat("Alpha, Bravo", "%s, %s") => "Alpha", "Bravo"
-- @usage LibDeformat.Deformat("Alpha, Bravo", "%1$s, %2$s") => "Alpha", "Bravo"
-- @usage LibDeformat.Deformat("Alpha, Bravo", "%2$s, %1$s") => "Bravo", "Alpha"
-- @usage LibDeformat.Deformat("Hello, friend", "Cost: $%d") == nil
-- @usage LibDeformat("Hello, friend", "Hello, %s") == "friend"
function LibDeformat.Deformat(text, pattern)
if type(text) ~= "string" then
error(("Argument #1 to `Deformat' must be a string, got %s (%s)."):format(type(text), text), 2)
elseif type(pattern) ~= "string" then
error(("Argument #2 to `Deformat' must be a string, got %s (%s)."):format(type(pattern), pattern), 2)
end
return get_deformat_function(pattern)(text)
end
--[===[@debug@
function LibDeformat.Test()
local function tuple(success, ...)
if success then
return true, { n = select('#', ...), ... }
else
return false, ...
end
end
local function check(text, pattern, ...)
local success, results = tuple(pcall(LibDeformat.Deformat, text, pattern))
if not success then
return false, results
end
if select('#', ...) ~= results.n then
return false, ("Differing number of return values. Expected: %d. Actual: %d."):format(select('#', ...), results.n)
end
for i = 1, results.n do
local expected = select(i, ...)
local actual = results[i]
if type(expected) ~= type(actual) then
return false, ("Return #%d differs by type. Expected: %s (%s). Actual: %s (%s)"):format(type(expected), expected, type(actual), actual)
elseif expected ~= actual then
return false, ("Return #%d differs. Expected: %s. Actual: %s"):format(expected, actual)
end
end
return true
end
local function test(text, pattern, ...)
local success, problem = check(text, pattern, ...)
if not success then
print(("Problem with (%q, %q): %s"):format(text, pattern, problem or ""))
end
end
test("Hello, friend", "Hello, %s", "friend")
test("Hello, friend", "Hello, %1$s", "friend")
test("Cost: $100", "Cost: $%d", 100)
test("Cost: $100", "Cost: $%1$d", 100)
test("Alpha, Bravo", "%s, %s", "Alpha", "Bravo")
test("Alpha, Bravo", "%1$s, %2$s", "Alpha", "Bravo")
test("Alpha, Bravo", "%2$s, %1$s", "Bravo", "Alpha")
test("Alpha, Bravo, Charlie, Delta, Echo", "%s, %s, %s, %s, %s", "Alpha", "Bravo", "Charlie", "Delta", "Echo")
test("Alpha, Bravo, Charlie, Delta, Echo", "%1$s, %2$s, %3$s, %4$s, %5$s", "Alpha", "Bravo", "Charlie", "Delta", "Echo")
test("Alpha, Bravo, Charlie, Delta, Echo", "%5$s, %4$s, %3$s, %2$s, %1$s", "Echo", "Delta", "Charlie", "Bravo", "Alpha")
test("Alpha, Bravo, Charlie, Delta, Echo", "%2$s, %3$s, %4$s, %5$s, %1$s", "Echo", "Alpha", "Bravo", "Charlie", "Delta")
test("Alpha, Bravo, Charlie, Delta, Echo", "%3$s, %4$s, %5$s, %1$s, %2$s", "Delta", "Echo", "Alpha", "Bravo", "Charlie")
test("Alpha, Bravo, Charlie, Delta", "%s, %s, %s, %s, %s", nil, nil, nil, nil, nil)
test("Hello, friend", "Cost: $%d", nil)
print("LibDeformat-3.0: Tests completed.")
end
--@end-debug@]===]
setmetatable(LibDeformat, { __call = function(self, ...) return self.Deformat(...) end }) | bsd-3-clause |
kiarash14/be | plugins/banhammer.lua | 175 | 5896 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
if user_id == tostring(our_id) then
send_msg(chat, "I won't kick myself!", ok_cb, true)
else
chat_del_user(chat, user, ok_cb, true)
end
end
local function ban_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
if user_id == tostring(our_id) then
send_msg(chat, "I won't kick myself!", ok_cb, true)
else
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function run(msg, matches)
-- Silent ignore
if not is_sudo(msg) then
return nil
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
ban_user(user_id, chat_id)
return 'User '..user_id..' banned'
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
kick_user(matches[2], msg.to.id)
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.id..' whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.id..' removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
"!whitelist <enable>/<disable>: Enable or disable whitelist mode",
"!whitelist user <user_id>: Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat: Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id>: Remove user from whitelist",
"!whitelist delete chat: Remove chat from whitelist",
"!ban user <user_id>: Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id>: Unban user",
"!kick <user_id> Kick user from chat group"
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (%d+)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (%d+)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (%d+)$",
"^!(ban) (delete) (%d+)$",
"^!(kick) (%d+)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.