repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
nyczducky/darkstar | scripts/zones/PsoXja/TextIDs.lua | 7 | 1882 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6385; -- Obtained: <item>
GIL_OBTAINED = 6386; -- Obtained <number> gil
KEYITEM_OBTAINED = 6388; -- Obtained key item: <keyitem>
NOTHING_OUT_OF_ORDINARY = 6399; -- There is nothing out of the ordinary here.
DEVICE_IN_OPERATION = 7227; -- The device appears to be in operation...
DOOR_LOCKED = 7230; -- The door is locked.
ARCH_GLOW_BLUE = 7231; -- The arch above the door is glowing blue...
ARCH_GLOW_GREEN = 7232; -- The arch above the door is glowing green...
CANNOT_OPEN_SIDE = 7235; -- The door cannot be opened from this side.
TRAP_ACTIVATED = 7237; -- A trap connected to it has been activated!
TRAP_FAILS = 7238; -- The trap connected to it fails to activate.
DISCOVER_DISARM_FAIL = 7239; -- discovers a trap connected to the door, but fails to disarm it!
DISCOVER_DISARM_SUCCESS = 7240; -- discovers a trap connected to the door and succeeds in disarming it!
HOMEPOINT_SET = 7472; -- Home point set!
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7459; -- You unlock the chest!
CHEST_FAIL = 7460; -- Fails to open the chest.
CHEST_TRAP = 7461; -- The chest was trapped!
CHEST_WEAK = 7462; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7463; -- The chest was a mimic!
CHEST_MOOGLE = 7464; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7465; -- The chest was but an illusion...
CHEST_LOCKED = 7466; -- The chest appears to be locked.
-- Other
BROKEN_KNIFE = 7467; -- A broken knife blade can be seen among the rubble...
-- conquest Base
CONQUEST_BASE = 7068; -- Tallying conquest results...
| gpl-3.0 |
jbeich/Aquaria | files/scripts/maps/node_naija_mithalasend.lua | 6 | 1070 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
function init(me)
end
function update(me, dt)
if isFlag(FLAG_BOSS_MITHALA, 1) then
if node_isEntityIn(me, getNaija()) then
voiceOnce("Naija_MithalasEnd")
end
end
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Lufaise_Meadows/npcs/Teldo-Moroldo_WW.lua | 14 | 3342 | -----------------------------------
-- Area: Lufaise Meadows
-- NPC: Teldo-Moroldo, W.W.
-- Outpost Conquest Guards
-- @pos -542.418 -7.124 -53.521 24
-----------------------------------
package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Lufaise_Meadows/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = TAVNAZIANARCH;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
sudheesh001/RFID-DBSync | cardpeek-0.8.3/dot_cardpeek_dir/scripts/emv.lua | 1 | 23137 | --
-- This file is part of Cardpeek, the smartcard reader utility.
--
-- Copyright 2009-2013 by 'L1L1'
--
-- Cardpeek 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.
--
-- Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>.
--
-- @name EMV
-- @description Bank cards 'PIN and chip'
-- @targets 0.8
--
-- History:
-- Aug 07 2010: Corrected bug in GPO command.
-- Aug 08 2010: Corrected bug in AFL data processing
-- Mar 27 2011: Added CVM patch from Adam Laurie.
-- Jan 23 2012: Added UK Post Office Card Account in AID list from Tyson Key.
-- Mar 25 2012: Added a few AIDs
-- @update: Feb 21 2014: Better NFC compatibility by using current date in GPO.
require('lib.tlv')
require('lib.strict')
--------------------------------------------------------------------------
-- GLOBAL EMV CARD COMMANDS extending general lib.apdu
--------------------------------------------------------------------------
function build_empty_pdol_data_block(pdol)
local data = bytes.new(8);
local o_tag
local o_len
while pdol do
o_tag, pdol = asn1.split_tag(pdol)
o_len, pdol = asn1.split_tag(pdol)
if o_tag==0x9F66 and o_len==4 then
-- Terminal Transaction Qualifiers (VISA)
data = data .. "30 00 00 00"
elseif o_tag==0x9F1A and o_len==2 then
-- Terminal country code
data = data .. "0250"
elseif o_tag==0x5F2A and o_len==2 then
-- Transaction currency code
data = data .. "0978"
elseif o_tag==0x9A and o_len==3 then
-- Transaction date
data = data .. os.date("%y %m %d")
elseif o_tag==0x9F37 and o_len==4 then
-- Unpredictable number
data = data .. "DEADBEEF"
else
-- When in doubt Zeroize
while o_len > 0 do
data = data .. 0x00
o_len = o_len-1
end
end
end
return data
end
function card.get_processing_options(pdol)
local command
local pdol_data
if pdol and #pdol>0 then
pdol_data = build_empty_pdol_data_block(pdol)
command = bytes.new(8,"80 A8 00 00",#pdol_data+2,0x83,#pdol_data,pdol_data,"00")
else
command = bytes.new(8,"80 A8 00 00 02 83 00 00")
end
return card.send(command)
end
-- override card.get_data() for EMV
function card.get_data(data)
local command = bytes.new(8,"80 CA",bit.AND(bit.SHR(data,8),0xFF),bit.AND(data,0xFF),0)
return card.send(command)
end
-- ------------------------------------------------------------------------
-- EMV
-- ------------------------------------------------------------------------
TRANSACTION_TYPE = {
[0]="Purchase",
[1]="Cash"
}
function ui_parse_transaction_type(node,cc)
local tt = TRANSACTION_TYPE[cc[0]]
if tt == nil then
return tostring(cc)
end
nodes.set_attribute(node,"val",cc)
nodes.set_attribute(node,"alt",tt)
return true
end
function ui_parse_CVM(node,data)
local i
local left
local right
local leftstring
local rightstring
local subnode
local out
nodes.append(node,{ classname="item",
label="X",
size=4,
val=bytes.sub(data,0,3)})
nodes.append(node,{ classname="item",
label="Y",
size=4,
val=bytes.sub(data,4,7)})
for i= 4,(#data/2)-1 do
left = data:get(i*2)
right = data:get(i*2+1)
if left == 0 and right == 0 then
-- Amex pads the list with zeroes at the end
-- Once we reach the zeroes, we're done parsing
break
end
subnode = nodes.append(node, { classname="item",
label="CVM",
id=i-3,
size=2,
val=bytes.sub(data,i*2,i*2+1)})
if bit.AND(left,0x40) == 0x40 then
out = "Apply succeeding CV rule if this rule is unsuccessful: "
else
out = "Fail cardholder verification if this CVM is unsuccessful: "
end
if CVM_REFERENCE_BYTE1[bit.AND(left,0xBF)] == nil then
leftstring = string.format("Unknown (%02X)",left)
else
leftstring = CVM_REFERENCE_BYTE1[bit.AND(left,0xBF)]
end
if CVM_REFERENCE_BYTE2[right] == nil then
rightstring = string.format("Unknown (%02X)",right)
else
rightstring = CVM_REFERENCE_BYTE2[right]
end
out = out .. leftstring .. " - " .. rightstring
nodes.set_attribute(subnode,"alt",out)
end
nodes.set_attribute(node,"val",data)
return true
end
CVM_REFERENCE_BYTE1 = {
[0x00] = "Fail CVM processing",
[0x01] = "Plaintext PIN verification performed by ICC",
[0x02] = "Enciphered PIN verified online",
[0x03] = "Plaintext PIN verification performed by ICC and signature (paper)",
[0x04] = "Enciphered PIN verification performed by ICC",
[0x05] = "Enciphered PIN verification performed by ICC and signature (paper)",
[0x1E] = "Signature (paper)",
[0x1F] = "No CVM Required",
}
CVM_REFERENCE_BYTE2 = {
[0x00] = "Always",
[0x01] = "If unattended cash",
[0x02] = "If not attended cash and not manual cash and not purchase with cashback",
[0x03] = "If terminal supports the CVM",
[0x04] = "If manual cash",
[0x05] = "If purchase with cashback",
[0x06] = "If transaction is in the application currency and is under X value",
[0x07] = "If transaction is in the application currency and is over X value",
[0x08] = "If transaction is in the application currency and is under Y value",
[0x09] = "If transaction is in the application currency and is over Y value"
}
EMV_REFERENCE = {
['5D'] = {"Directory Definition File (DDF) Name" },
['70'] = {"Application Data File (ADF)" },
['80'] = {"Response Message Template Format 1" },
['82'] = {"Application Interchange Profile (AIP)" },
['87'] = {"Application Priority Indicator" },
['88'] = {"Short File Identifier (SFI)" },
['8C'] = {"Card Risk Management Data Object List 1 (CDOL1)" },
['8D'] = {"Card Risk Management Data Object List 2 (CDOL2)" },
['8E'] = {"Cardholder Verification Method (CVM) List", ui_parse_CVM },
['8F'] = {"Certificate Authority Public Key Index (PKI)" },
['90'] = {"Issuer PK Certificate" },
['91'] = {"Issuer Authentication Data" },
['92'] = {"Issuer PK Remainder" },
['93'] = {"Signed Static Application Data" },
['94'] = {"Application File Locator (AFL)" },
['95'] = {"Terminal Verification Results (TVR)" },
['97'] = {"Transaction Certificate Data Object List (TDOL)" },
['9A'] = {"Transaction Date", ui_parse_YYMMDD },
['9C'] = {"Transaction Type", ui_parse_transaction_type },
['A5'] = {"FCI Proprietary Template" },
['9F02'] = {"Amount, Authorized" },
['9F03'] = {"Amount, Other" },
['9F05'] = {"Application Discretionary Data" },
['9F07'] = {"Application Usage Control" },
['9F08'] = {"Application Version Number" },
['9F0B'] = {"Cardholder Name - Extended" },
['9F0D'] = {"Issuer Action Code - Default" },
['9F0E'] = {"Issuer Action Code - Denial" },
['9F0F'] = {"Issuer Action Code - Online" },
['9F10'] = {"Issuer Application Data" },
['9F11'] = {"Issuer Code Table Index" },
['9F12'] = {"Application Preferred Name" },
['9F13'] = {"Last Online ATC Register" },
['9F14'] = {"Lower Consecutive Offline Limit (Terminal Check)" },
['9F17'] = {"PIN Try Counter", ui_parse_number },
['9F19'] = {"Dynamic Data Authentication Data Object List (DDOL)" },
['9F1A'] = {"Terminal Country Code", ui_parse_country_code },
['9F1F'] = {"Track 1 Discretionary Data", ui_parse_printable },
['9F23'] = {"Upper Consecutive Offline Limit (Terminal Check)" },
['9F26'] = {"Application Cryptogram (AC)" },
['9F27'] = {"Cryptogram Information Data" },
['9F2D'] = {"ICC PIN Encipherment Public Key Certificate" },
['9F2E'] = {"ICC PIN Encipherment Public Key Exponent" },
['9F2F'] = {"ICC PIN Encipherment Public Key Remainder" },
['9F32'] = {"Issuer PK Exponent" },
['9F36'] = {"Application Transaction Counter (ATC)" },
['9F37'] = {"Unpredictable number" },
['9F38'] = {"Processing Options Data Object List (PDOL)" },
['9F42'] = {"Application Currency Code" },
['9F44'] = {"Application Currency Exponent" },
['9F45'] = {"Data Authentication Code" },
['9F46'] = {"ICC Public Key Certificate" },
['9F47'] = {"ICC Public Key Exponent" },
['9F48'] = {"ICC Public Key Remainder" },
['9F4A'] = {"Static Data Authentication Tag List" },
['9F4B'] = {"Signed Dynamic Application Data" },
['9F4C'] = {"Integrated Circuit Card (ICC) Dynamic Number" },
['9F4D'] = {"Log Entry" },
['9F4F'] = {"Log Fromat" },
['9F51'] = {"Application Currency Code" },
['9F52'] = {"Card Verification Results (CVR)" },
['9F53'] = {"Consecutive Transaction Limit (International)" },
['9F54'] = {"Cumulative Total Transaction Amount Limit" },
['9F55'] = {"Geographic Indicator" },
['9F56'] = {"Issuer Authentication Indicator" },
['9F57'] = {"Issuer Country Code" },
['9F58'] = {"Lower Consecutive Offline Limit (Card Check)" },
['9F59'] = {"Upper Consecutive Offline Limit (Card Check)" },
['9F5A'] = {"Issuer URL2" },
['9F5C'] = {"Cumulative Total Transaction Amount Upper Limit" },
['9F72'] = {"Consecutive Transaction Limit (International - Country)" },
['9F73'] = {"Currency Conversion Factor" },
['9F74'] = {"VLP Issuer Authorization Code" },
['9F75'] = {"Cumulative Total Transaction Amount Limit - Dual Currency" },
['9F76'] = {"Secondary Application Currency Code" },
['9F77'] = {"VLP Funds Limit" },
['9F78'] = {"VLP Single Transaction Limit" },
['9F79'] = {"VLP Available Funds" },
['9F7F'] = {"Card Production Life Cycle (CPLC) History File Identifiers" },
['BF0C'] = {"FCI Issuer Discretionary Data" }
}
function emv_parse(cardenv,tlv)
return tlv_parse(cardenv,tlv,EMV_REFERENCE)
end
PPSE = "#325041592E5359532E4444463031"
PSE = "#315041592E5359532E4444463031"
-- AID_LIST enhanced with information from Wikipedia
-- http://en.wikipedia.org/wiki/EMV
AID_LIST = {
"#A0000000421010", -- French CB
"#A0000000422010", -- French CB
"#A0000000031010", -- Visa credit or debit
"#A0000000032010", -- Visa electron
"#A0000000032020", -- V pay
"#A0000000032010", -- Visa electron
"#A0000000038010", -- Visa Plus
"#A0000000041010", -- Mastercard credit or debit
"#A0000000042010", --
"#A0000000043060", -- Mastercard Maestro
"#A0000000046000", -- Mastercard Cirrus
"#A00000006900", -- FR Moneo
"#A00000002501", -- American Express
"#A0000001850002", -- UK Post Office Card Account card
"#A0000001523010", -- Diners club/Discover
"#A0000002771010", -- Interac
"#A0000003241010", -- Discover
"#A0000000651010", -- JCB
}
EXTRA_DATA = { 0x9F36, 0x9F13, 0x9F17, 0x9F4D, 0x9F4F }
function emv_process_ppse(cardenv)
local sw, resp
local APP
local dirent
sw, resp = card.select(PPSE)
if sw ~= 0x9000 then
log.print(log.INFO,"No PPSE")
return false
end
-- Construct tree
APP = nodes.append(cardenv, {classname="application", label="application", id=PPSE})
emv_parse(APP,resp)
AID_LIST = {}
for dirent in nodes.find(APP,{ id="4F" }) do
aid = tostring(nodes.get_attribute(dirent,"val"))
log.print(log.INFO,"PPSE contains application #" .. aid)
table.insert(AID_LIST,"#"..aid)
end
return true
end
function emv_process_pse(cardenv)
local sw, resp
local APP
local ref
local sfi
local FILE
local rec
local REC
local RECORD
local aid
local warm_atr
local tag4F
sw, resp = card.select(PSE)
-- Could it be a french card?
if sw == 0x6E00 then
card.warm_reset()
warm_atr = card.last_atr()
nodes.append(cardenv, {classname="atr", label="ATR", id="warm", size=#warm_atr, val=warm_atr})
sw, resp = card.select(PSE)
end
-- could it be a contactless smartcard?
if sw == 0x6A82 then
return emv_process_ppse(cardenv)
end
if sw ~= 0x9000 then
log.print(log.INFO,"No PSE")
return false
end
-- Construct tree
APP = nodes.append(cardenv, {classname="application", label="application", id=PSE})
emv_parse(APP,resp)
ref = nodes.find_first(APP,{id="88"})
if (ref) then
sfi = nodes.get_attribute(ref,"val")
FILE = nodes.append(APP,{classname="file", label="file", id=sfi[0]})
rec = 1
AID_LIST = {}
repeat
sw,resp = card.read_record(sfi:get(0),rec)
if sw == 0x9000 then
RECORD = nodes.append(FILE, {classname="record", label="record", id=tostring(rec)})
emv_parse(RECORD,resp)
for tag4F in nodes.find(RECORD,{id="4F"}) do
aid = tostring(nodes.get_attribute(tag4F,"val"))
log.print(log.INFO,"PSE contains application #" .. aid)
table.insert(AID_LIST,"#"..aid)
end
rec = rec + 1
end
until sw ~= 0x9000
else
log.print(log.WARNING,"SFI indicator (tag 88) not found in PSE")
end
return true
end
function visa_process_application_logs(application, log_sfi, log_max)
local sw, resp
local LOG_FILE
local LOG_DATA
local LOG_FORMAT
local log_recno
LOG_FILE = nodes.append(application,{ classname="file",
label="file",
id=tostring(log_sfi)})
LOG_DATA = nodes.append(LOG_FILE, { classname="item",
label = "log data"})
log.print(log.INFO,string.format("Reading LOG SFI %i",log_sfi))
for log_recno =1,log_max do
sw,resp = card.read_record(log_sfi, log_recno)
if sw ~= 0x9000 then
log.print(log.WARNING,"Read log record failed")
break
else
nodes.append(LOG_DATA,{ classname = "record",
label="record",
id=log_recno,
size=#resp,
val=resp})
end
end
end
function emv_process_application_logs(application, log_sfi, log_max)
local log_format
local log_tag
local log_items = { }
local sw, resp
local tag
local tag_name
local tag_func
local len
local i
local item
local item_pos
local LOG_FILE
local LOG_DATA
local LOG_FORMAT
local REC
local ITEM
local ITEM_AMOUNT
local log_recno
local data
local currency_code, currency_name, currency_digits
LOG_FILE = nodes.append(application, { classname="file", label="log file", id=log_sfi})
LOG_FORMAT = nodes.append(LOG_FILE, { classname="block", label="log format"})
log_format = application:find_first({id = "9F4F"}):get_attribute("val")
i = 1
item = ""
nodes.set_attribute(LOG_FORMAT,"val",log_format);
while log_format
do
tag, log_format = asn1.split_tag(log_format)
len, log_format = asn1.split_length(log_format)
tag_name, tag_func = tlv_tag_info(tag,EMV_REFERENCE,0);
log_items[i]= { tag, len, tag_name, tag_func }
i = i+1
item = item .. string.format("%X[%d] ", tag, len);
end
nodes.set_attribute(LOG_FORMAT,"alt",item);
log.print(log.INFO,string.format("Reading LOG SFI %i",log_sfi))
for log_recno =1,log_max do
sw,resp = card.read_record(log_sfi,log_recno)
if sw ~= 0x9000 then
log.print(log.WARNING,"Read log record failed")
break
else
REC = nodes.append(LOG_FILE,{classname="record", label="record", id=log_recno, size=#resp})
item_pos = 0
ITEM_AMOUNT = nil
currency_digits = 0
for i=1,#log_items do
if log_items[i][3] then
ITEM = nodes.append(REC,{ classname="item",
label=log_items[i][3],
size=log_items[i][2] })
else
ITEM = nodes.append(REC,{ classname="item",
label=string.format("tag %X",log_items[i][1]),
size=log_items[i][2] })
end
data = bytes.sub(resp,item_pos,item_pos+log_items[i][2]-1)
nodes.set_attribute(ITEM,"val",data)
if log_items[i][1]==0x9F02 then
ITEM_AMOUNT=ITEM
elseif log_items[i][1]==0x5F2A then
currency_code = tonumber(tostring(data))
currency_name = iso_currency_code_name(currency_code)
currency_digits = iso_currency_code_digits(currency_code)
nodes.set_attribute(ITEM,"alt",currency_name)
elseif log_items[i][4] then
log_items[i][4](ITEM,data)
end
item_pos = item_pos + log_items[i][2]
end
if ITEM_AMOUNT then
local amount = tostring(nodes.get_attribute(ITEM_AMOUNT,"val"))
nodes.set_attribute(ITEM_AMOUNT,"alt",string.format("%.2f",amount/(10^currency_digits)))
end
end
end
end
function emv_process_application(cardenv,aid)
local sw, resp
local ref
local pdol
local AFL
local extra
local j -- counter
log.print(log.INFO,"Processing application "..aid)
-- Select AID
sw,resp = card.select(aid)
if sw ~=0x9000 then
return false
end
-- Process 'File Control Infomation' and get PDOL
local APP
local FCI
APP = nodes.append(cardenv, { classname = "application", label = "application", id=aid })
FCI = nodes.append(APP, { classname = "header", label = "answer to select", size=#resp, val=resp })
emv_parse(FCI,resp)
ref = nodes.find_first(FCI,{id="9F38"})
if (ref) then
pdol = nodes.get_attribute(ref,"val")
else
pdol = nil;
end
-- INITIATE get processing options, now that we have pdol
local GPO
if ui.question("Issue a GET PROCESSING OPTIONS command?",{"Yes","No"})==1 then
-- Get processing options
log.print(log.INFO,"Attempting GPO")
sw,resp = card.get_processing_options(pdol)
if sw ~=0x9000 then
if pdol then
-- try empty GPO just in case the card is blocking some stuff
log.print(log.WARNING,
string.format("GPO with data failed with code %X, retrying GPO without data",sw))
sw,resp = card.get_processing_options(nil)
end
end
if sw ~=0x9000 then
log.print(log.ERROR,"GPO Failed")
ui.question("GET PROCESSING OPTIONS failed, the script will continue to read the card",{"OK"})
else
GPO = nodes.append(APP,{classname="block",label="processing_options", size=#resp, val=resp})
emv_parse(GPO,resp)
end
end
-- Read extra data
--extra = nodes.append(APP,{classname="block",label="extra emv data"})
for j=1,#EXTRA_DATA do
sw,resp = card.get_data(EXTRA_DATA[j])
if sw == 0x9000 then
emv_parse(APP,resp):set_attribute("classname","block")
end
end
-- find LOG INFO
local LOG
local logformat
logformat=nil
ref = nodes.find_first(APP,{id="9F4D"})
-- I've seen this on some cards :
if ref==nil then
-- proprietary style ?
ref = nodes.find_first(APP,{id="DF60"})
logformat = "VISA"
else
logformat = "EMV"
end
if ref then
LOG = nodes.get_attribute(ref,"val")
else
sw, resp = card.get_data(0x9F4D)
if sw==0x9000 then
LOG = tostring(resp)
logformat = "EMV"
else
sw, resp = card.get_data(0xDF60)
if sw==0x9000 then
LOG = tostring(resp)
logformat = "VISA"
else
logformat = nil
LOG = nil
end
end
end
if logformat then
log.print(log.INFO,"Found "..logformat.." transaction log indicator")
else
log.print(log.INFO,"No transaction log indicator")
end
local sfi_index
local rec_index
local SFI
local REC
for sfi_index=1,31 do
SFI = nil
if (logformat==nil or LOG:get(0)~=sfi_index) then
for rec_index=1,255 do
log.print(log.INFO,string.format("Reading SFI %i, record %i",sfi_index, rec_index))
sw,resp = card.read_record(sfi_index,rec_index)
if sw ~= 0x9000 then
log.print(log.WARNING,string.format("Read record failed for SFI %i, record %i",sfi_index,rec_index))
-- Amex has files where records don't start at 1
-- The highest starting number I've seen is 4,
-- so don't treat a failure of a lower-than-five record number as "end of records in a file"
if rec_index > 5 then
break
end
else
if (SFI==nil) then
SFI = nodes.append(APP,{classname="file", label="file", id=sfi_index})
end
REC = nodes.append(SFI,{classname="record", label="record", id=rec_index})
if (emv_parse(REC,resp)==false) then
nodes.set_attribute(REC,"val",resp)
nodes.set_attribute(REC,"size",#resp)
end
end
end -- for rec_index
end -- if log exists
end -- for sfi_index
-- Read logs if they exist
if logformat=="EMV" then
emv_process_application_logs(APP,LOG:get(0),LOG:get(1))
elseif logformat=="VISA" then
visa_process_application_logs(APP,LOG:get(0),LOG:get(1))
end
return true
end
CPLC_DATA =
{
{ "IC Fabricator", 2, 0 } ,
{ "IC Type", 2, 0 },
{ "Operating System Provider Identifier", 2 },
{ "Operating System Release Date", 2 },
{ "Operating System Release Level", 2 },
{ "IC Fabrication Date", 2 },
{ "IC Serial Number", 4 },
{ "IC Batch Identifier", 2 },
{ "IC ModuleFabricator", 2 },
{ "IC ModulePackaging Date", 2 },
{ "ICC Manufacturer", 2 },
{ "IC Embedding Date", 2 },
{ "Prepersonalizer Identifier", 2 },
{ "Prepersonalization Date", 2 },
{ "Prepersonalization Equipment", 4 },
{ "Personalizer Identifier", 2 },
{ "Personalization Date", 2 },
{ "Personalization Equipment", 4 },
}
function emv_process_cplc(cardenv)
local sw, resp
local CPLC
local cplc_data
local cplc_tag
local i
local pos
local ref2
log.print(log.INFO,"Processing CPLC data")
sw,resp = card.get_data(0x9F7F)
if sw == 0x9000 then
cplc_tag, cplc_data = asn1.split(resp)
CPLC = nodes.append(cardenv,{classname="block", label="cpcl data", id="9F7F", size=#cplc_data})
nodes.set_attribute(CPLC,"val",cplc_data)
pos = 0
for i=1,#CPLC_DATA do
ref2 = nodes.append(CPLC,{classname="item", label=CPLC_DATA[i][1], id=pos});
nodes.set_attribute(ref2,"val",bytes.sub(cplc_data,pos,pos+CPLC_DATA[i][2]-1))
pos = pos + CPLC_DATA[i][2]
end
end
end
-- PROCESSING
if card.connect() then
local mycard = card.tree_startup("EMV")
emv_process_pse(mycard)
card.warm_reset()
for i=1,#AID_LIST
do
-- print(AID_LIST[i])
emv_process_application(mycard,AID_LIST[i])
card.warm_reset()
end
emv_process_cplc(mycard)
card.disconnect()
else
ui.question("No card detected in reader",{"OK"})
end
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/deepwhale.lua | 5 | 3301 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
v.n = 0
v.seen = false
local notes = { 4, 2, 3, 2, 1 }
local numNotes = 5
v.curNote = 1
v.warpLoc = 0
function init(me)
setupEntity(me)
entity_setEntityType(me, ET_NEUTRAL)
entity_initSkeletal(me, "DeepWhale")
entity_scale(me, 1.5, 1.5)
entity_setCullRadius(me, 3500)
if isFlag(FLAG_DEEPWHALE, 0) then
entity_setState(me, STATE_IDLE)
else
entity_setState(me, STATE_OPENED)
end
v.warpLoc = entity_getBoneByName(me, "WarpLoc")
loadSound("DeepWhale-Open")
entity_setInternalOffset(me, 0, -50)
entity_setInternalOffset(me, 0, 50, 4, -1, 1, 1)
end
function postInit(me)
v.n = getNaija()
entity_setTarget(me, v.n)
end
function update(me, dt)
if entity_isState(me, STATE_OPENED) then
--debugLog("opened")
local bx, by = bone_getWorldPosition(v.warpLoc)
if entity_isPositionInRange(v.n, bx, by, 200) then
loadMap("WHALE", "ENTER")
end
end
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
entity_animate(me, "idle", -1)
elseif entity_isState(me, STATE_OPEN) then
playSfx("DeepWhale-Open")
v.seen = true
entity_idle(v.n)
entity_animate(me, "open")
shakeCamera(10, 4)
entity_flipToEntity(v.n, me)
watch(1)
emote(EMOTE_NAIJAUGH)
watch(2)
emote(EMOTE_NAIJAWOW)
watch(2)
emote(EMOTE_NAIJAGIGGLE)
entity_setStateTime(me, 1)
elseif entity_isState(me, STATE_OPENED) then
entity_animate(me, "opened", -1)
if isFlag(FLAG_DEEPWHALE, 0) then
setFlag(FLAG_DEEPWHALE, 1)
end
end
end
function exitState(me)
if entity_isState(me, STATE_OPEN) then
entity_setState(me, STATE_OPENED)
end
end
function damage(me, attacker, bone, damageType, dmg)
return false
end
function animationKey(me, key)
end
function hitSurface(me)
end
function lightFlare(me)
if not v.seen then
if entity_isEntityInRange(me, v.n, 600) then
entity_idle(v.n)
v.seen = true
entity_flipToEntity(v.n, me)
watch(0.2)
emote(EMOTE_NAIJAUGH)
watch(1.4)
emote(EMOTE_NAIJALAUGH)
end
end
end
function songNote(me, note)
end
function songNoteDone(me, note)
if entity_isState(me, STATE_IDLE) then
debugLog(string.format("curNote: %d", v.curNote))
if notes[v.curNote] == note then
v.curNote = v.curNote + 1
elseif notes[1] == note then
v.curNote = 2
else
v.curNote = 1
end
if v.curNote > numNotes then
entity_setState(me, STATE_OPEN)
end
end
end
function song(me, song)
end
function activate(me)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Valkurm_Dunes/npcs/Tsunashige_IM.lua | 14 | 3324 | -----------------------------------
-- Area: Valkurm Dunes
-- NPC: Tsunashige, I.M.
-- Outpost Conquest Guards
-- @pos 139.394 -7.885 100.384 103
-----------------------------------
package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Valkurm_Dunes/TextIDs");
local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = ZULKHEIM;
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 |
SamOatesPlugins/cuberite | Server/Plugins/APIDump/Hooks/OnHopperPullingItem.lua | 44 | 1336 | return
{
HOOK_HOPPER_PULLING_ITEM =
{
CalledWhen = "A hopper is pulling an item from another block entity.",
DefaultFnName = "OnHopperPullingItem", -- also used as pagename
Desc = [[
This callback is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from another
block entity into its own internal storage. A plugin may decide to disallow the move by returning
true. Note that in such a case, the hook may be called again for the same hopper, with different
slot numbers.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
{ Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pulling the item" },
{ Name = "DstSlot", Type = "number", Notes = "The destination slot in the hopper's {{cItemGrid|internal storage}}" },
{ Name = "SrcBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = "The block entity that is losing the item" },
{ Name = "SrcSlot", Type = "number", Notes = "Slot in SrcBlockEntity from which the item will be pulled" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. If the function
returns true, no other callback is called for this event and the hopper will not pull the item.
]],
}, -- HOOK_HOPPER_PULLING_ITEM
}
| apache-2.0 |
naxiwer/Atlas | examples/tutorial-union.lua | 40 | 1614 | --[[ $%BEGINLICENSE%$
Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
res = { }
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then return end
local q = packet:sub(2)
res = { }
if q:sub(1, 6):upper() == "SELECT" then
proxy.queries:append(1, packet, { resultset_is_needed = true })
proxy.queries:append(2, packet, { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
end
end
function read_query_result(inj)
for row in inj.resultset.rows do
res[#res + 1] = row
end
if inj.id ~= 2 then
return proxy.PROXY_IGNORE_RESULT
end
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
rows = res
}
}
local fields = {}
for n = 1, #inj.resultset.fields do
fields[#fields + 1] = {
type = inj.resultset.fields[n].type,
name = inj.resultset.fields[n].name,
}
end
proxy.response.resultset.fields = fields
return proxy.PROXY_SEND_RESULT
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm10.lua | 14 | 1384 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm10 (???)
-- Involved in Quest: Hitting the Marquisate (THF AF3)
-- @pos -139.895 -5.500 154.513 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS");
if (hittingTheMarquisateHagainCS == 6) then
player:messageSpecial(PRESENCE_FROM_CEILING);
player:setVar("hittingTheMarquisateHagainCS",7);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
cliffano/swaggy-jenkins | clients/lua/generated/spec/free_style_build_spec.lua | 1 | 4356 | --[[
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.5.1-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
]]
--[[
Unit tests for openapiclient.model.free_style_build
Automatically generated by openapi-generator (https://openapi-generator.tech)
Please update as you see appropriate
]]
describe("free_style_build", function()
local openapiclient_free_style_build = require "openapiclient.model.free_style_build"
-- unit tests for the property '_class'
describe("property _class test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'Number_'
describe("property Number_ test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'url'
describe("property url test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'actions'
describe("property actions test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'building'
describe("property building test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'description'
describe("property description test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'display_name'
describe("property display_name test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'duration'
describe("property duration test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'estimated_duration'
describe("property estimated_duration test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'executor'
describe("property executor test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'full_display_name'
describe("property full_display_name test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'id'
describe("property id test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'keep_log'
describe("property keep_log test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'queue_id'
describe("property queue_id test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'result'
describe("property result test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'timestamp'
describe("property timestamp test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'built_on'
describe("property built_on test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'change_set'
describe("property change_set test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
end)
| mit |
mehrpouya81/giantbot | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
moltafet35/senatorv2 | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
ld-test/lzmq-ffi | examples/utils.lua | 16 | 1150 | local zmq = require "lzmq"
io.stdout:setvbuf"no"
function printf(...) return print(string.format(...)) end
function print_msg(title, data, err, ...)
print(title)
if data then -- data
if type(data) == 'table' then
for _, msg in ipairs(data) do
printf("[%.4d] %s", #msg, msg)
end
elseif type(data) == 'userdata' then
printf("[%.4d] %s", data:size(), data:data())
else
printf("[%.4d] %s", #data, data)
end
else --error
if type(err) == 'string' then
printf("Error: %s", err)
elseif type(err) == 'number' then
local msg = zmq.error(err):msg()
local mnemo = zmq.errors[err] or 'UNKNOWN'
printf("Error: [%s] %s (%d)", mnemo, msg, err)
elseif type(err) == 'userdata' then
printf("Error: [%s] %s (%d)", err:mnemo(), err:msg(), err:no())
else
printf("Error: %s", tostring(err))
end
end
print("-------------------------------------")
return data, err, ...
end
function print_version(zmq)
local version = zmq.version()
printf("zmq version: %d.%d.%d", version[1], version[2], version[3])
end
| mit |
francot514/CardGamePRO-Simulator | data/cards/c1080.lua | 1 | 1102 | --Battering Car
function c1080.initial_effect(c)
--Destroy target
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c1080.target)
e1:SetOperation(c1080.operation)
c:RegisterEffect(e1)
end
function c1080.filter(c)
return c:IsFaceup() or c:IsType(TYPE_UPGRADE+TYPE_BUILDING)
end
function c1080.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_SZONE) and c1080.filter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c1080.filter,tp,LOCATION_SZONE,LOCATION_SZONE,1,1,nil)
if g:GetCount()>0 and g:GetFirst():IsFaceup() then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
end
function c1080.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
if tc:IsType(TYPE_UPGRADE+TYPE_BUILDING) then Duel.Destroy(tc,REASON_EFFECT) end
end
end | gpl-2.0 |
nyczducky/darkstar | scripts/zones/Sealions_Den/mobs/Mammet-22_Zeta.lua | 23 | 4284 | -----------------------------------
-- Area: Sealions Den
-- Mob: Mammet-22_Zeta
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local MammetID = mob:getID();
-- printf("MammetID dead: %u",MammetID);
local mammet_1_1 = GetMobAction(16908289);
local mammet_1_2 = GetMobAction(16908290);
local mammet_1_3 = GetMobAction(16908291);
local mammet_1_4 = GetMobAction(16908292);
local mammet_1_5 = GetMobAction(16908293);
local mammet_2_1 = GetMobAction(16908296);
local mammet_2_2 = GetMobAction(16908297);
local mammet_2_3 = GetMobAction(16908298);
local mammet_2_4 = GetMobAction(16908299);
local mammet_2_5 = GetMobAction(16908300);
local mammet_3_1 = GetMobAction(16908303);
local mammet_3_2 = GetMobAction(16908304);
local mammet_3_3 = GetMobAction(16908305);
local mammet_3_4 = GetMobAction(16908306);
local mammet_3_5 = GetMobAction(16908307);
if (MammetID == 16908289 or MammetID == 16908290 or MammetID == 16908291 or MammetID == 16908292 or MammetID == 16908293) then
if ((mammet_1_1 == 0 or mammet_1_1 == 21 or mammet_1_1 == 22 or mammet_1_1 == 23)and
(mammet_1_2 == 0 or mammet_1_2 == 21 or mammet_1_2 == 22 or mammet_1_2 == 23)and
(mammet_1_3 == 0 or mammet_1_3 == 21 or mammet_1_3 == 22 or mammet_1_3 == 23)and
(mammet_1_4 == 0 or mammet_1_4 == 21 or mammet_1_4 == 22 or mammet_1_4 == 23)and
(mammet_1_5 == 0 or mammet_1_5 == 21 or mammet_1_5 == 22 or mammet_1_5 == 23)) then
player:startEvent(0x000b);
end
elseif (MammetID == 16908297 or MammetID == 16908298 or MammetID == 16908299 or MammetID == 16908300 or MammetID == 16908296) then
if ((mammet_2_1 == 0 or mammet_2_1 == 21 or mammet_2_1 == 22 or mammet_2_1 == 23)and
(mammet_2_2 == 0 or mammet_2_2 == 21 or mammet_2_2 == 22 or mammet_2_2 == 23)and
(mammet_2_3 == 0 or mammet_2_3 == 21 or mammet_2_3 == 22 or mammet_2_3 == 23)and
(mammet_2_4 == 0 or mammet_2_4 == 21 or mammet_2_4 == 22 or mammet_2_4 == 23)and
(mammet_2_5 == 0 or mammet_2_5 == 21 or mammet_2_5 == 22 or mammet_2_5 == 23)) then
player:startEvent(0x000b);
end
elseif (MammetID == 16908303 or MammetID == 16908304 or MammetID == 16908305 or MammetID == 16908306 or MammetID == 16908307) then
if ((mammet_3_1 == 0 or mammet_3_1 == 21 or mammet_3_1 == 22 or mammet_3_1 == 23)and
(mammet_3_2 == 0 or mammet_3_2 == 21 or mammet_3_2 == 22 or mammet_3_2 == 23)and
(mammet_3_3 == 0 or mammet_3_3 == 21 or mammet_3_3 == 22 or mammet_3_3 == 23)and
(mammet_3_4 == 0 or mammet_3_4 == 21 or mammet_3_4 == 22 or mammet_3_4 == 23)and
(mammet_3_5 == 0 or mammet_3_5 == 21 or mammet_3_5 == 22 or mammet_3_5 == 23)) then
player:startEvent(0x000b);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x000b) then
local instance = player:getVar("bcnm_instanceid")
--Players are healed in between the fights, but their TP is set to 0
player:setHP(player:getMaxHP());
player:setMP(player:getMaxMP());
player:setTP(0);
if (instance == 1) then
player:setPos(-779, -103, -80);
SpawnMob(16908294); -- omega1
elseif (instance == 2) then
player:setPos(-140, -23, -440);
SpawnMob(16908301); -- omega2
else
player:setPos(499, 56, -802);
SpawnMob(16908308); -- omega 3
end
player:addTitle(BRANDED_BY_LIGHTNING);
end
end; | gpl-3.0 |
matinbot/webamooz | plugins/stats.lua | 168 | 4001 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'creedbot' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /creedbot ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' then
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(chat_id)
else
return
end
end
if matches[2] == "creedbot" then -- Put everything you like :)
if not is_admin(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[!/]([Ss]tats)$",
"^[!/]([Ss]tatslist)$",
"^[!/]([Ss]tats) (group) (%d+)",
"^[!/]([Ss]tats) (creedbot)",-- Put everything you like :)
"^[!/]([Cc]reedbot)"-- Put everything you like :)
},
run = run
}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Northern_San_dOria/npcs/Capiria.lua | 14 | 1684 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Capiria
-- Type: Involved in Quest (Flyers for Regine)
-- @zone 231
-- @pos -127.355 0.000 130.461
--
-----------------------------------
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)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeCapiria") == 0) then
player:messageSpecial(CAPIRIA_DIALOG);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeCapiria",1);
player:messageSpecial(FLYER_ACCEPTED);
player:tradeComplete();
elseif (player:getVar("tradeCapiria") ==1) then
player:messageSpecial(FLYER_ALREADY);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CAPIRIA_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jbeich/Aquaria | files/scripts/maps/node_killentity.lua | 6 | 1106 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
function init(me)
end
function update(me)
--[[
local ent = node_getNearestEntity(me)
if ent ~=0 and entity_getEntityType(ent) ~= ET_AVATAR and node_isEntityIn(me, ent) then
entity_delete(ent)
end
]]--
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Beaucedine_Glacier/npcs/Chopapa_WW.lua | 14 | 3357 | -----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Chopapa, W.W.
-- Type: Border Conquest Guards
-- @pos -227.956 -81.475 260.442 111
-----------------------------------
package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Beaucedine_Glacier/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = FAUREGANDI;
local csid = 0x7ff6;
-----------------------------------
-- 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 |
nyczducky/darkstar | scripts/commands/addallspells.lua | 23 | 4989 | ---------------------------------------------------------------------------------------------------
-- func: addallspells
-- desc: Adds all valid spells to the given target. If no target; then to the current player.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "s"
};
local ValidSpells = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,
38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,
72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,
105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,
131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,
157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,
183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,
209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,
235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,
261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,
287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,
313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,
339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,
365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,
391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,
417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,
443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,
469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,
495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,515,517,519,521,522,524,527,
529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,547,548,549,551,554,555,557,560,561,
563,564,565,567,569,570,572,573,574,575,576,577,578,579,581,582,584,585,587,588,589,591,592,593,594,595,
596,597,598,599,603,604,605,606,608,610,611,612,613,614,615,616,617,618,620,621,622,623,626,628,629,631,
632,633,634,636,637,638,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,
660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,
686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,
712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,736,737,738,739,740,741,742,743,744,
745,746,747,748,749,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,
789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,
815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,
841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,
867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,
893,894,895
--trusts are causing client crashes when flagged in char spells packets sent outside of zone/log in
--896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,
--922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,
--948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,
--974,975,976,977,978,979,980,981,982,983,984,985,986,987,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016
};
local function AddAllSpells(player)
local save = true;
local silent = true; -- prevent packet spam
for i = 1, #ValidSpells do
if i == #ValidSpells then
silent = false;
end
player:addSpell(ValidSpells[i], silent, save);
end
end;
function onTrigger(player, target)
if (target == nil) then
AddAllSpells(player);
else
local targ = GetPlayerByName(target);
if (targ == nil) then
player:PrintToPlayer(string.format( "Player named '%s' not found!", target ));
else
AddAllSpells(targ);
end
end
end
| gpl-3.0 |
wizardbottttt/illusion | bot/seedbot.lua | 1 | 10114 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"plugins"
},
sudo_users = {105019279,152622735,173979569,158002943,tonumber(our_id)},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[[[P O W E R B O T v5 By : @POWERSUDO
Admins
@POWERSUDO [Founder]
@Blackwolf_admin [Developer]
@Somebody_i [Developer]
@POWERSUDO [Manager]
Special Thx To Iman Daneshi And Randoozle
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [GroupID] [Text]
Set a group's about text
!setrules [GroupID] [Text]
Set a group's rules
!lock [GroupID] [setting]
Lock a group's setting
!unlock [GroupID] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [GroupID]
Kick all memebers and delete group
!kill realm [RealmID]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Grt a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!br [group_id] [text]
!br 123456789 Hello !
This command will send text to [group_id]
**U can use both "/" and "!"
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
will return group logs
!banlist
will return group ban list
**U can use both "/" and "!"
*Only owner and mods can add bots in group
*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only owner can use res,setowner,promote,demote and log commands
!google : google search .
!tex : return text into img
!linkpv : return gp's link in pv (bot is reported)
!time [city] : return time of that city
!calc : calculate + - and ...
Help By : @POWERSUDO
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Xarcabard/TextIDs.lua | 1 | 1203 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6392; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6398; -- Obtained: <item>.
GIL_OBTAINED = 6399; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6401; -- Obtained key item: <keyitem>.
BEASTMEN_BANNER = 7138; -- There was a curse on the beastmen's banner!
ALREADY_OBTAINED_TELE = 7368; -- You already possess the gate crystal for this telepoint.
-- Conquest
CONQUEST = 7381; -- You've earned conquest points!
-- Other
NOTHING_OUT_OF_ORDINARY = 6412; -- There is nothing out of the ordinary here.
ONLY_SHARDS = 7714; -- Only shards of ice lie upon the ground.
BLOCKS_OF_ICE = 7715; -- You can hear blocks of ice moving from deep within the cave.
-- Dynamis dialogs
YOU_CANNOT_ENTER_DYNAMIS = 7840; -- You cannot enter Dynamis
PLAYERS_HAVE_NOT_REACHED_LEVEL = 7842; -- Players who have not reached levelare prohibited from entering Dynamis
UNUSUAL_ARRANGEMENT_OF_PEBBLES = 7853; -- There is an unusual arrangement of pebbles here.
-- conquest Base
CONQUEST_BASE = 7059; -- Tallying conquest results...
| gpl-3.0 |
guangbin79/Lua_5.1.5-iOS | xavante-2.4.0/src/codeweb/session.lua | 1 | 1188 | -----------------------------------------------------------------------------
-- Xavante sessions handler
--
-- Author: Javier Guerra
-- Copyright (c) 2005 Kepler Project
-----------------------------------------------------------------------------
local cookies = require "xavante.cookies"
local session = {}
local _sessions = {}
local _max_age = 3600 -- one hour
local _def_name = "XVTE_SESS"
local MIN_SID = 11111111
local MAX_SID = 99999999
local function new_sid ()
local sid = 0
while sid <MIN_SID or sid >MAX_SID or _sessions[sid] do
sid = math.random (MAX_SID)
end
return sid
end
function session.set_max_age (mx)
_max_age = mx
end
function session.open (req, res, name)
name = (name or _def_name) .. "_SID"
local sid = cookies.get (req, name) or new_sid ()
_sessions [sid] = _sessions [sid] or {data={}}
local sess = _sessions [sid]
sess.expires = os.time() + _max_age
cookies.set (res, name, sid, {expires=sess.expires})
return sess.data
end
function session.close (req, res, name)
name = (name or _def_name) .. "_SID"
local sid = cookies.get (req, name)
if sid then
_sessions [sid] = nil
end
cookies.delete (res, name)
end
return session
| mit |
nyczducky/darkstar | scripts/globals/items/pukatrice_egg_+1.lua | 12 | 1828 | -----------------------------------------
-- ID: 6275
-- Item: pukatrice_egg_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- HP +20
-- MP +20
-- STR +3
-- Fire resistance +21
-- Attack +21% (cap 90)
-- Ranged Attack +21% (cap 90)
-- Subtle Blow +9
-----------------------------------------
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,6275);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_MP, 20);
target:addMod(MOD_STR, 3);
target:addMod(MOD_FIRERES, 21);
target:addMod(MOD_FOOD_ATTP, 21);
target:addMod(MOD_FOOD_ATT_CAP, 90);
target:addMod(MOD_FOOD_RATTP, 21);
target:addMod(MOD_FOOD_RATT_CAP, 90);
target:addMod(MOD_SUBTLE_BLOW, 9);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_MP, 20);
target:delMod(MOD_STR, 3);
target:delMod(MOD_FIRERES, 21);
target:delMod(MOD_FOOD_ATTP, 21);
target:delMod(MOD_FOOD_ATT_CAP, 90);
target:delMod(MOD_FOOD_RATTP, 21);
target:delMod(MOD_FOOD_RATT_CAP, 90);
target:delMod(MOD_SUBTLE_BLOW, 9);
end;
| gpl-3.0 |
mehrpouya81/giantbot | plugins/anti-spam6.lua | 13 | 2433 | local NUM_MSG_MAX = 6 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 6
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, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
else
local chat = msg.to.id
local hash = 'anti-flood:enabled:'..chat
if matches[1] == 'enable' then
redis:set(hash, true)
return 'Spam Limit Is now 6'
end
if matches[1] == 'disable' then
redis:del(hash)
return 'Spam limit is Not 6 now'
end
end
end
local function pre_process (msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
local hash_enable = 'anti-flood:enabled:'..msg.to.id
local enabled = redis:get(hash_enable)
if enabled then
print('anti-flood enabled')
-- Check flood
if msg.from.type == 'user' then
-- Increase the number of messages from the user on the chat
local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
local receiver = get_receiver(msg)
local user = msg.from.id
local text = 'User '..user..' is Spaming I Will Fuck He/She'
local chat = msg.to.id
send_msg(receiver, text, ok_cb, nil)
if msg.to.type ~= 'chat' then
print("Flood in not a chat group!")
elseif user == tostring(our_id) then
print('I won\'t kick myself')
elseif is_sudo(msg) then
print('I won\'t kick an admin!')
else
-- kick user
-- TODO: Check on this plugin kicks
local bhash = 'kicked:'..msg.to.id..':'..msg.from.id
redis:set(bhash, true)
kick_user(user, chat)
end
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
return msg
end
return {
description = 'Plugin to kick flooders from group.',
usage = {},
patterns = {
'^!antiflood6 (enable)$',
'^!antiflood6 (disable)$'
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Oldton_Movalpolos/TextIDs.lua | 7 | 1146 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6385; -- Obtained: <item>.
GIL_OBTAINED = 6386; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6388; -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7565; -- You can't fish here.
-- Mining
MINING_IS_POSSIBLE_HERE = 7696; -- Mining is possible here if you have
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7743; -- You unlock the chest!
CHEST_FAIL = 7744; -- Fails to open the chest.
CHEST_TRAP = 7745; -- The chest was trapped!
CHEST_WEAK = 7746; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7747; -- The chest was a mimic!
CHEST_MOOGLE = 7748; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7749; -- The chest was but an illusion...
CHEST_LOCKED = 7750; -- The chest appears to be locked.
-- NPCs
RAKOROK_DIALOGUE = 7720; -- Nsy pipul. Gattohre! I bisynw!
-- conquest Base
CONQUEST_BASE = 7046; -- Tallying conquest results...
| gpl-3.0 |
weweadsl/thrift | lib/lua/TTransport.lua | 115 | 2800 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'Thrift'
TTransportException = TException:new {
UNKNOWN = 0,
NOT_OPEN = 1,
ALREADY_OPEN = 2,
TIMED_OUT = 3,
END_OF_FILE = 4,
INVALID_FRAME_SIZE = 5,
INVALID_TRANSFORM = 6,
INVALID_CLIENT_TYPE = 7,
errorCode = 0,
__type = 'TTransportException'
}
function TTransportException:__errorCodeToString()
if self.errorCode == self.NOT_OPEN then
return 'Transport not open'
elseif self.errorCode == self.ALREADY_OPEN then
return 'Transport already open'
elseif self.errorCode == self.TIMED_OUT then
return 'Transport timed out'
elseif self.errorCode == self.END_OF_FILE then
return 'End of file'
elseif self.errorCode == self.INVALID_FRAME_SIZE then
return 'Invalid frame size'
elseif self.errorCode == self.INVALID_TRANSFORM then
return 'Invalid transform'
elseif self.errorCode == self.INVALID_CLIENT_TYPE then
return 'Invalid client type'
else
return 'Default (unknown)'
end
end
TTransportBase = __TObject:new{
__type = 'TTransportBase'
}
function TTransportBase:isOpen() end
function TTransportBase:open() end
function TTransportBase:close() end
function TTransportBase:read(len) end
function TTransportBase:readAll(len)
local buf, have, chunk = '', 0
while have < len do
chunk = self:read(len - have)
have = have + string.len(chunk)
buf = buf .. chunk
if string.len(chunk) == 0 then
terror(TTransportException:new{
errorCode = TTransportException.END_OF_FILE
})
end
end
return buf
end
function TTransportBase:write(buf) end
function TTransportBase:flush() end
TServerTransportBase = __TObject:new{
__type = 'TServerTransportBase'
}
function TServerTransportBase:listen() end
function TServerTransportBase:accept() end
function TServerTransportBase:close() end
TTransportFactoryBase = __TObject:new{
__type = 'TTransportFactoryBase'
}
function TTransportFactoryBase:getTransport(trans)
return trans
end
| apache-2.0 |
jakianroy/NGUI_To_Be_Best | Assets/LuaFramework/ToLua/Lua/socket/mbox.lua | 51 | 2654 | local _M = {}
if module then
mbox = _M
end
function _M.split_message(message_s)
local message = {}
message_s = string.gsub(message_s, "\r\n", "\n")
string.gsub(message_s, "^(.-\n)\n", function (h) message.headers = h end)
string.gsub(message_s, "^.-\n\n(.*)", function (b) message.body = b end)
if not message.body then
string.gsub(message_s, "^\n(.*)", function (b) message.body = b end)
end
if not message.headers and not message.body then
message.headers = message_s
end
return message.headers or "", message.body or ""
end
function _M.split_headers(headers_s)
local headers = {}
headers_s = string.gsub(headers_s, "\r\n", "\n")
headers_s = string.gsub(headers_s, "\n[ ]+", " ")
string.gsub("\n" .. headers_s, "\n([^\n]+)", function (h) table.insert(headers, h) end)
return headers
end
function _M.parse_header(header_s)
header_s = string.gsub(header_s, "\n[ ]+", " ")
header_s = string.gsub(header_s, "\n+", "")
local _, __, name, value = string.find(header_s, "([^%s:]-):%s*(.*)")
return name, value
end
function _M.parse_headers(headers_s)
local headers_t = _M.split_headers(headers_s)
local headers = {}
for i = 1, #headers_t do
local name, value = _M.parse_header(headers_t[i])
if name then
name = string.lower(name)
if headers[name] then
headers[name] = headers[name] .. ", " .. value
else headers[name] = value end
end
end
return headers
end
function _M.parse_from(from)
local _, __, name, address = string.find(from, "^%s*(.-)%s*%<(.-)%>")
if not address then
_, __, address = string.find(from, "%s*(.+)%s*")
end
name = name or ""
address = address or ""
if name == "" then name = address end
name = string.gsub(name, '"', "")
return name, address
end
function _M.split_mbox(mbox_s)
local mbox = {}
mbox_s = string.gsub(mbox_s, "\r\n", "\n") .."\n\nFrom \n"
local nj, i, j = 1, 1, 1
while 1 do
i, nj = string.find(mbox_s, "\n\nFrom .-\n", j)
if not i then break end
local message = string.sub(mbox_s, j, i-1)
table.insert(mbox, message)
j = nj+1
end
return mbox
end
function _M.parse(mbox_s)
local mbox = _M.split_mbox(mbox_s)
for i = 1, #mbox do
mbox[i] = _M.parse_message(mbox[i])
end
return mbox
end
function _M.parse_message(message_s)
local message = {}
message.headers, message.body = _M.split_message(message_s)
message.headers = _M.parse_headers(message.headers)
return message
end
return _M
| gpl-3.0 |
0xwindows/Belial | rule.lua | 3 | 2332 | -----------------------------------------------------------------------------
-- Belial web waf
-- Author: 逆雪寒
-- Copyright (c) 2013 半夜三更
--
--
--
-----------------------------------------------------------------------------
--拦截规则
local regularRule =
{
--belial waf default rule。dont delete
default = {
get = "'|(and|or)\\b.+?(>|<|=|\\bin|\\blike)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)|(\\.\\.\\/)+|^\\/?[a-zA-Z]+(\\/[a-zA-Z]+)+$",
post = "base64_decode|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT.+?INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE).+?(TABLE|DATABASE)|\\.\\/|^\\/?[a-zA-Z]+(\\/[a-zA-Z]+)+$",
cookie = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)",
ngxPathInfoFix = "\\..*\\/.*php",
},
--适合俺公司的规则
ziqing = {
get = "(and|or)\\b.+?(>|<|=|\\bin|\\blike)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)|(\\.\\.\\/)+|^\\/?[a-zA-Z]+(\\/[a-zA-Z]+)+$",
post = "base64_decode|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT.+?INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE).+?(TABLE|DATABASE)|\\.\\/|^\\/?[a-zA-Z]+(\\/[a-zA-Z]+)+$",
cookie = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)",
ngxPathInfoFix = "\\..*\\/.*php",
},
}
--cc规则
-- urlRegular,ccHackAmount
local ccUrlList =
{
{"read.php\\?tid=\\d+?",120},
{"searchthread\\.php",120},
{"login\\.php",120},
{"register\\.php",120},
{"thread\\.php",120},
{"post1\\.php",60},
{"item\\/(.+?)\\.html",120}, --伪静态url
}
return {regularRule=regularRule,ccUrlList=ccUrlList} | apache-2.0 |
nyczducky/darkstar | scripts/zones/Dho_Gates/Zone.lua | 17 | 1213 | -----------------------------------
--
-- Zone: Foret de Hennetiel
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Dho_Gates/TextIDs"] = nil;
require("scripts/zones/Dho_Gates/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(62,-10,83,84);
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 |
nyczducky/darkstar | scripts/zones/Abyssea-Misareaux/npcs/qm4.lua | 14 | 1344 | -----------------------------------
-- Zone: Abyssea-Misareaux
-- NPC: qm4 (???)
-- Spawns Manohra
-- @pos ? ? ? 216
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
if (trade:hasItemQty(3088,1) and trade:getItemCount() == 1) then -- Player has all the required items.
if (GetMobAction(17662467) == ACTION_NONE) then -- Mob not already spawned from this
SpawnMob(17662467):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:tradeComplete();
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(1010, 3088); -- Inform player what items they need.
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
cornernote/minetest-skyblock | skyblock_levels/skyblock.levels.4.lua | 1 | 5343 | --[[
Skyblock for Minetest
Copyright (c) 2015 cornernote, Brett O'Donnell <cornernote@gmail.com>
Source Code: https://github.com/cornernote/minetest-skyblock
License: GPLv3
]]--
--[[
Level 4 mostly revolving around farming and dying
level 4 feats and rewards:
* craft_diamondhoe farming:seed_wheat
* use_hoe x40 farming:melon_slice
* plant_wheatseed default:cactus
* craft_flour farming:seed_cotton x10
* place_snowblock x50 dye:red x20
* dig_cactus x10 dye:white x20
* dig_geranium x5 flowers:mushroom_brown x2
* dig_tulip x5 flowers:mushroom_red x2
* dig_brownmushroom x15 farming:corn x50
* craft_ethanol default:meselamp x5
]]--
local level = 4
--
-- PUBLIC FUNCTIONS
--
skyblock.levels[level] = {}
-- feats
-- Parts of this are purely hypothetical and not implement yet
skyblock.levels[level].feats = {
{
name = "Craft a mese hoe",
hint = "farming:hoe_mese",
feat = "craft_mesehoe",
count = 1,
reward = "farming:seed_wheat 2",
craft = {"farming:hoe_mese"}
},
{
name = "Use the hoe 40 times",
hint = "farming:hoe_mese",
feat = "use_hoe",
count = 40,
reward = "farming:melon_slice",
hoeuse = {}
},
{
name = "Plant 10 wheat seeds",
hint = "farming:seed_wheat",
feat = "place_wheatseed",
count = 10,
reward = "default:cactus",
placenode = {"farming:seed_wheat"}
},
{
name = "Craft 4 lumps of flour",
hint = "farming:flour",
feat = "craft_flour",
count = 4,
reward = "farming:seed_cotton 10",
craft = {"farming:flour"},
},
{
name = "Place 50 snow blocks",
hint = "default:snowblock",
feat = "place_snowblock",
count = 50,
reward = "dye:red 20",
placenode = {"default:snowblock"},
},
{
name = "Dig 10 cacti",
hint = "default:cactus",
feat = "dig_cactus",
count = 10,
reward = "dye:white 20",
dignode = {"default:cactus"},
},
{
name = "Pick 5 Geranium flowers",
hint = "flowers:geranium",
feat = "dig_geranium",
count = 5,
reward = "flowers:mushroom_brown 2",
dignode = {"flowers:geranium"},
},
{
name = "Pick 5 orange tulips",
hint = "flowers:tulip",
feat = "dig_tulip",
count = 5,
reward = "flowers:mushroom_red 2",
dignode = {"flowers:tulip"},
},
{
name = "Dig 10 brown mushrooms",
hint = "flowers:mushroom_brown",
feat = "dig_brownmushroom",
count = 10,
reward = "farming:corn",
dignode = {"flowers:mushroom_brown"},
},
{
name = "Make ethanol!",
hint = "farming:corn",
feat = "craft_ethanol",
count = 1,
reward = "default:meselamp 5",
craft = {"farming:bottle_ethanol"},
}
}
-- init level
skyblock.levels[level].init = function(player_name)
end
-- get level information
skyblock.levels[level].get_info = function(player_name)
local info = {
level=level,
total=10,
count=0,
player_name=player_name,
infotext='',
formspec = '',
formspec_quest = '',
}
local text = 'label[0,2.7; --== Quests ==--]'
..'label[0,0.5; Time Goes On, '..player_name..'...]'
..'label[0,1.0; You may wonder, traveller, where some of your]'
..'label[0,1.5; precious items are. Be patient...]'
..'label[0,2.0; They will come to you in time...]'
info.formspec = skyblock.levels.get_inventory_formspec(level,info.player_name,true)..text
info.formspec_quest = skyblock.levels.get_inventory_formspec(level,info.player_name)..text
for k,v in ipairs(skyblock.levels[level].feats) do
info.formspec = info.formspec..skyblock.levels.get_feat_formspec(info,k,v.feat,v.count,v.name,v.hint,true)
info.formspec_quest = info.formspec_quest..skyblock.levels.get_feat_formspec(info,k,v.feat,v.count,v.name,v.hint)
end
if info.count>0 then
info.count = info.count/2 -- only count once
end
info.infotext = 'LEVEL '..info.level..' for '..info.player_name..': '..info.count..' of '..info.total
return info
end
-- Reward feats
skyblock.levels[level].reward_feat = function(player_name, feat)
return skyblock.levels.reward_feat(level, player_name, feat)
end
-- Track node placement
skyblock.levels[level].on_placenode = function(pos, newnode, placer, oldnode)
skyblock.levels.on_placenode(level, pos, newnode, placer, oldnode)
end
-- Track node digging
skyblock.levels[level].on_dignode = function(pos, oldnode, digger)
skyblock.levels.on_dignode(level, pos, oldnode, digger)
end
-- track eating feats
skyblock.levels[level].on_item_eat = function(player_name, itemstack)
skyblock.levels.on_item_eat(level, player_name, itemstack)
end
-- track crafting feats
skyblock.levels[level].on_craft = function(player_name, itemstack)
skyblock.levels.on_craft(level, player_name, itemstack)
end
-- track hoe use
skyblock.levels[level].hoe_on_use = function(player_name, pointed_thing, wieldeditem)
skyblock.levels.hoe_on_use(level, player_name, pointed_thing, wieldeditem)
end
skyblock.levels[level].bucket_on_use = function(player_name, pointed_thing) end
skyblock.levels[level].bucket_water_on_use = function(player_name, pointed_thing) end
skyblock.levels[level].bucket_lava_on_use = function(player_name, pointed_thing) end
| gpl-3.0 |
laggyluk/brick_engine | tools/logicEditor/bin/scripts/memory.lua | 1 | 1208 | --delphi memory search for given string. result is also a string for x64 bit longint 'simulation'
function memFindString(target,startOffset)
--create table
memTable = {}
--pass starting offset in first table field. starting offset also passed as string
memTable[1] = startOffset
for i=2,string.len(target) do
--trace(string.byte(target, i))
memTable[i] = string.byte(target, i-1)
end
local result = memSearchString(memTable);
--trace('mem search: ' .. result);
return result
end
--convert to hex and reverse bytes
function intToMem(num)
--hex
local num=string.format("%x",num)
--string.len(num) % 2 ~= 0))
if (string.len(num) % 2 ~= 0) then num='0'..num end
local rev = ''
for i=string.len(num),1,-2 do
rev = rev .. string.sub(num, i-1, i)
end
return rev
end
--convert hex string to string of bytes
function hexToByte(num)
local rev = ''
if (string.len(num) % 2 ~= 0) then num='0'..num end
--trace(num)
for i=1,string.len(num),2 do
rev = rev .. string.char(tonumber(string.sub(num, i, i+1), 16))
--trace(tonumber(string.sub(num, i, i+1), 16)..string.char(tonumber(string.sub(num, i, i+1), 16)))
--trace(tonumber(string.sub(num, i, i+1)))
end
return rev
end
| mit |
sevu/wesnoth | data/ai/micro_ais/cas/ca_return_guardian.lua | 7 | 1221 | local AH = wesnoth.require "ai/lua/ai_helper.lua"
local function get_guardian(cfg)
local filter = wml.get_child(cfg, "filter") or { id = cfg.id }
local guardian = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", filter }
}[1]
return guardian
end
local ca_return_guardian = {}
function ca_return_guardian:evaluation(cfg)
local guardian = get_guardian(cfg)
if guardian then
local return_loc = AH.get_named_loc_xy('return', cfg)
if (guardian.x == return_loc[1]) and (guardian.y == return_loc[2]) then
return cfg.ca_score - 200
else
return cfg.ca_score
end
end
return 0
end
function ca_return_guardian:execution(cfg)
local guardian = get_guardian(cfg)
local return_loc = AH.get_named_loc_xy('return', cfg)
-- In case the return hex is occupied:
local x, y = return_loc[1], return_loc[2]
if (guardian.x ~= x) or (guardian.y ~= y) then
x, y = wesnoth.paths.find_vacant_hex(x, y, guardian)
end
local nh = AH.next_hop(guardian, x, y)
if (not nh) then nh = { guardian.x, guardian.y } end
AH.movefull_stopunit(ai, guardian, nh)
end
return ca_return_guardian
| gpl-2.0 |
benloz10/FinalFrontier | gamemodes/finalfrontier/entities/entities/info_ff_sector/shared.lua | 1 | 3644 | -- Copyright (c) 2014 James King [metapyziks@gmail.com]
--
-- This file is part of Final Frontier.
--
-- Final Frontier is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as
-- published by the Free Software Foundation, either version 3 of
-- the License, or (at your option) any later version.
--
-- Final Frontier 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 Lesser General Public License
-- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>.
if SERVER then AddCSLuaFile("shared.lua") end
ENT.Type = "anim"
ENT.Base = "base_anim"
function ENT:SetupDataTables()
self:NetworkVar( "String", 0, "SectorName" )
end
function ENT:GetCoordinates()
return universe:GetUniversePos(self:GetPos())
end
function ENT:GetSectorName()
return self:GetSectorName()
end
function ENT:GetBoundingBox()
local cx, cy = self:GetCoordinates()
return
universe:GetWorldPos(cx + 0, cy + 0) - Vector(0, 0, 8),
universe:GetWorldPos(cx + 1, cy + 1) + Vector(0, 0, 8)
end
if SERVER then
local horzNames = {
"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta",
"iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "phi",
"rho", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega"
}
local vertNames = {}
for i = 1, 24 do vertNames[i] = tostring(i) end
local RESPAWN_DELAY = 60
ENT._lastVisit = 0
function ENT:GetPVSPos()
return self:GetPos() + Vector(0, 0, 64)
end
function ENT:SetCoordinates(x, y)
self:SetPos(universe:GetWorldPos(universe:WrapCoordinates(x + 0.5, y + 0.5)))
self:SetSectorName(horzNames[x + 1] .. "-" .. vertNames[y + 1])
end
function ENT:Purge()
for _, ent in ipairs(ents.FindInBox(self:GetBoundingBox())) do
if IsValid(ent) and ent:GetClass() == "info_ff_object"
and (not ent.GetObjectType or ent:GetObjectType() ~= objtype.SHIP) then
ent:Remove()
end
end
end
function ENT:Populate()
self:Purge()
local x, y = self:GetCoordinates()
local count, max = 0, math.ceil(math.random() * 8)
while math.random() < 0.25 and count < max do
count = count + 1
end
for i = 1, count do
local obj = ents.Create("info_ff_object")
obj:SetCoordinates(x + math.random(), y + math.random())
obj:Spawn()
if math.random() < 0.70 then
obj:AssignRoomModule(table.Random({
moduletype.LIFE_SUPPORT,
moduletype.SHIELDS,
moduletype.SYSTEM_POWER
}), nil)
elseif math.random() < 0.95 then
obj:AssignWeaponModule()
else
obj:AssignBomb()
end
end
end
function ENT:Visit()
if self._lastVisit == 0 or CurTime() - self._lastVisit >= RESPAWN_DELAY then
self:Populate()
end
self._lastVisit = CurTime()
end
function ENT:Think()
if self._lastVisit > 0 and CurTime() - self._lastVisit >= RESPAWN_DELAY then
self:Purge()
self._lastVisit = 0
end
end
elseif CLIENT then
function ENT:Draw()
return
end
end
| lgpl-3.0 |
moltafet35/senatorv2 | bot/utils.lua | 356 | 14963 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has superuser privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has admins privileges
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has moderator privileges
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end | gpl-2.0 |
vorbi123/x | bot/utils.lua | 356 | 14963 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has superuser privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has admins privileges
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has moderator privileges
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end | gpl-2.0 |
nyczducky/darkstar | scripts/globals/mobskills/Enervation.lua | 27 | 1240 | ---------------------------------------------
-- Enervation
--
-- Description: Lowers the defense and magical defense of enemies within range.
-- Type: Magical (Dark)
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 91) then
local mobSkin = mob:getModelId();
if (mobSkin == 1680) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_DEFENSE_DOWN;
local silenced = false;
local blinded = false;
silenced = MobStatusEffectMove(mob, target, EFFECT_DEFENSE_DOWN, 10, 0, 120);
blinded = MobStatusEffectMove(mob, target, EFFECT_MAGIC_DEF_DOWN, 8, 0, 120);
skill:setMsg(MSG_ENFEEB_IS);
-- display silenced first, else blind
if (silenced == MSG_ENFEEB_IS) then
typeEffect = EFFECT_DEFENSE_DOWN;
elseif (blinded == MSG_ENFEEB_IS) then
typeEffect = EFFECT_MAGIC_DEF_DOWN;
else
skill:setMsg(MSG_MISS);
end
return typeEffect;
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Tabar.lua | 17 | 1486 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Animated Tabar
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(116,1575,1000);
else
SetDropRate(116,1575,0);
end
target:showText(mob,ANIMATED_TABAR_DIALOG);
SpawnMob(17330380):updateEnmity(target);
SpawnMob(17330381):updateEnmity(target);
SpawnMob(17330382):updateEnmity(target);
SpawnMob(17330392):updateEnmity(target);
SpawnMob(17330393):updateEnmity(target);
SpawnMob(17330394):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
-----------------------------------
-- onMobDisengage
-----------------------------------
function onMobDisengage(mob)
mob:showText(mob,ANIMATED_TABAR_DIALOG+2);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:showText(mob,ANIMATED_TABAR_DIALOG+1);
DespawnMob(17330380);
DespawnMob(17330381);
DespawnMob(17330382);
DespawnMob(17330392);
DespawnMob(17330393);
DespawnMob(17330394);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Pashhow_Marshlands_[S]/npcs/Cavernous_Maw.lua | 29 | 1434 | -----------------------------------
-- Area: Sauromugue Champaign
-- NPC: Cavernous Maw
-- @pos 418 25 27 90
-- Teleports Players to Pashhow_Marshlands
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/campaign");
require("scripts/zones/Pashhow_Marshlands_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (hasMawActivated(player,4) == false) then
player:startEvent(0x0064);
else
player:startEvent(0x0065);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (option == 1) then
if (csid == 0x0064) then
player:addNationTeleport(MAW,16);
end
toMaw(player,16);
end
end; | gpl-3.0 |
weissj3/milkywayathome_client | nbody/tests/CheckpointTest.lua | 3 | 2783 | --
-- Copyright (C) 2011 Matthew Arsenault
--
-- This file is part of Milkway@Home.
--
-- Milkyway@Home 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.
--
-- Milkyway@Home 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 Milkyway@Home. If not, see <http://www.gnu.org/licenses/>.
--
--
require "NBodyTesting"
SM = require "SampleModels"
SP = require "SamplePotentials"
function randomNBodyCtx(prng)
if prng == nil then
prng = DSFMT.create()
end
return NBodyCtx.create{
timestep = prng:random(1.0e-5, 1.0e-4),
timeEvolve = prng:random(0, 10),
theta = prng:random(0, 1),
eps2 = prng:random(1.0e-9, 1.0e-3),
treeRSize = prng:randomListItem({ 4, 8, 2, 16 }),
criterion = prng:randomListItem({"NewCriterion", "SW93", "BH86", "Exact"}),
useQuad = prng:randomBool(),
allowIncest = true,
quietErrors = true
}
end
function runNSteps(st, n, ctx)
for i = 1, n do
st:step(ctx)
end
return ctx, st
end
function runInterruptedSteps(st, totalSteps, ctx, prng)
local tmpDir = os.getenv("TMP") or ""
local checkpoint = tmpDir .. os.tmpname()
for i = 1, totalSteps do
st:step(ctx)
if prng:randomBool() then
local tmp = tmpDir .. os.tmpname()
st:writeCheckpoint(ctx, checkpoint, tmp)
ctx, st = NBodyState.readCheckpoint(checkpoint)
os.remove(checkpoint)
end
end
return ctx, st
end
local nTests = 5
for i = 1, nTests do
local testSteps, st, stCopy
local ctx, m
local prng = DSFMT.create()
m = SM.randomPlummer(prng, 500)
ctx = randomNBodyCtx(prng)
ctx:addPotential(SP.randomPotential(prng))
st = NBodyState.create(ctx, m)
stClone = st:clone()
testSteps = floor(prng:random(0, 51))
ctx, st = runNSteps(st, testSteps, ctx)
ctxClone, stClone = runInterruptedSteps(stClone, testSteps, ctx, prng)
assert(ctx == ctxClone,
string.format("Checkpointed context does not match:\nctx 1 = %s\n ctx 2 = %s\n",
tostring(ctx),
tostring(ctxClone))
)
assert(st == stClone,
string.format("Checkpointed state does not match:\nstate 1 = %s\n state 2 = %s\n",
tostring(st),
tostring(stClone))
)
end
| gpl-3.0 |
abosalah22/memo | plugins/anti_spam.lua | 21 | 5248 | --An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Save stats on Redis
if msg.to.type == 'channel' then
-- User is on channel
local hash = 'channel:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
if msg.to.type == 'user' then
-- User is on chat
local hash = 'PM:'..msg.from.id
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is on or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
local chat = msg.to.id
local whitelist = "whitelist"
local is_whitelisted = redis:sismember(whitelist, user)
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
if is_whitelisted == true then
return msg
end
local receiver = get_receiver(msg)
if msg.to.type == 'user' then
local max_msg = 7 * 1
print(msgs)
if msgs >= max_msg then
print("Pass2")
send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.")
savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.")
block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private
end
end
if kicktable[user] == true then
return
end
delete_msg(msg.id, ok_cb, false)
kick_user(user, chat)
local username = msg.from.username
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", "")
if msg.to.type == 'chat' or msg.to.type == 'channel' then
if username then
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "ممنوع التكرار\n@"..username.."["..msg.from.id.."]\n")
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "ممنوع التكرار \nName:"..name_log.."["..msg.from.id.."]\n")
end
end
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
if msg.from.username ~= nil then
username = msg.from.username
else
username = "---"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
local GBan_log = 'GBan_log'
local GBan_log = data[tostring(GBan_log)]
for k,v in pairs(GBan_log) do
log_SuperGroup = v
gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)"
--send it to log group/channel
send_large_msg(log_SuperGroup, gban_text)
end
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Bastok_Mines/npcs/Wahid.lua | 14 | 1997 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Wahid
-- Start & Finishes Quest: The Siren's Tear
-- @zone 234
-- @pos 26.305 -1 -66.403
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local SirensTear = player:getQuestStatus(BASTOK,THE_SIREN_S_TEAR);
if (SirensTear ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(576,1) and trade:getItemCount() == 1) then
player:startEvent(0x0052);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local SirensTear = player:getQuestStatus(BASTOK,THE_SIREN_S_TEAR);
if (SirensTear == QUEST_AVAILABLE) then
player:startEvent(0x0051);
else
player:startEvent(0x001c);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0051) then
player:addQuest(BASTOK,THE_SIREN_S_TEAR);
elseif (csid == 0x0052) then
player:tradeComplete();
player:completeQuest(BASTOK,THE_SIREN_S_TEAR);
player:addFame(BASTOK,120);
player:addGil(150*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,150*GIL_RATE);
player:addTitle(TEARJERKER);
player:setVar("SirensTear",0);
end
end; | gpl-3.0 |
TheHipster/cwlourp | plugins/books/plugin/items/sh_book_itn.lua | 1 | 4063 | --[[
© 2013 CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
--]]
ITEM = Clockwork.item:New("book_base");
ITEM.name = "Into the Night";
ITEM.model = "models/props_lab/bindergreenlabel.mdl";
ITEM.uniqueID = "book_itn";
ITEM.description = "A tattered green journal, the front page is torn up.";
ITEM.bookInformation = [[
<font color='red' size='4'>Author unknown.</font>
Let me begin by explaining how incredibly lucky and cursed you are to have found this, if you are one of us.
"If you are truely commited to something, what can harm you?" Peter I. Keep that quote with you, and you too
will see how it will both bless and haunt you. Those words will ring in your ears any time you find yourself
in trategy or adversity. You, yourself will speak those very words without knowing so. I find myself reciting
that quote like I'm caught in a trance. Sadly, it's a double edged sword. Your now cursed to have everyone around
you die, while you go on selfishly living your life, as if those you love are mere obstacles in your grand scheme.
[A page is torn out].
And to think I trusted the woman! She left me to die, albeit in a very biblical sense. I sat on the stairs of the
souveneir stand and wept bitterly. I could hear the common dispatch alarming our community of our all too well known
anti-citizen. The Archer had left us stranded in his wake. Oh how I loathe that man!
The prattle of boots could be heard coming down the corridor staring me in the eyes, like a portal to hell, the shadows
seemed to spring out and take shape. With glaring yellow eyes, they pulsed into the "lounge" to detain a man that was
never there. The Archer had escaped again, and left so many innocent lives to be fed to the darkness. Screams, in
an octave so high would pierce the night, causing even grown men to weep. A splatter of blood was thrown to the window
like scarlet meat thrown to the butcher to be beheaded and gutted. The very thought of what was going on in that bar
made my stomach turn. Luckily for me, the demons had ignored me. Realizing how they had only momentarily stopped on their
way towards another anti-citizen hotspot, I quickly jumped up. Vaulting over the wall and clinging to the ladder in
one swift motion I climbed to a safe haven.
We were all fair game now, those hiding from inspection were murdered like dogs, and those who stayed were subject to the
same fate. Only those who broke the rules in the right ways, were spared their lives. I crept along the catwalks, another
illegal activity worthy of a punishment worse than a thousand deaths, whispering my all too familiar chant. I looked over the side
and saw the shadows withdraw from within the bar and escape back through the hellish portal carrying the spoils of a night's raid.
The only person that remained crawled out begging for death. I could barely make out how he looked, however bad it was, the
horrible moaning he made was worse. I pushed back from the railing and crawled into an appartment, barring it with whatever I could
find.
A sofa, a chair, a bookcase. Nothing would stop the permeating belch from outside. A banshee would flee in terror of such a noise.
There was no sleep to tbe had that night. Just a brief shutting of the eyes, until shaken awake by the blast of mind numbing pain
vocalized by that which was the tortured soul outside. It was enough. I acted mercifully that night, to save one man's suffering,
and another a heart ache, I ended his screams. I'm haunted every night by those screams, and they're only amplified by the water
given to us by the demons. I'll not drink water for days, until dehydrated and resusitated by a demon teasing me with my own
semi-mortality.
I eagerly tossed this journal as far as I could throw it into the night. Seeing as that's where it all began. Into the night.
[The rest of the book is in unreadable marks, indicating the insanity of the propable author, if not authors].
]];
ITEM:Register(); | unlicense |
nyczducky/darkstar | scripts/zones/Maze_of_Shakhrami/npcs/Excavation_Point.lua | 14 | 1695 | -----------------------------------
-- Area: Maze of Shakhrami
-- NPC: Excavation Point
-- Used in Quest: The Holy Crest
-- @pos 234 0.1 -110 198
-----------------------------------
package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/excavation");
require("scripts/zones/Maze_of_Shakhrami/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("TheHolyCrest_Event") == 3 and player:hasItem(1159) == false) then
if (trade:hasItemQty(605,1) and trade:getItemCount() == 1) then
if (player:getFreeSlotsCount(0) >= 1) then
player:tradeComplete();
player:addItem(1159);
player:messageSpecial(ITEM_OBTAINED, 1159); -- Wyvern Egg
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1159); -- Wyvern Egg
end
end
else
startExcavation(player,player:getZoneID(),npc,trade,0x003C);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
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 |
ArpitJalan/arch-heavy-dotfiles | luakit/noscript.lua | 1 | 4727 | --------------------------------------------------------
-- NoScript plugin for luakit --
-- (C) 2011 Mason Larobina <mason.larobina@gmail.com> --
--------------------------------------------------------
-- Get Lua environment
local os = require "os"
local tonumber = tonumber
local assert = assert
local table = table
local string = string
-- Get luakit environment
local webview = webview
local add_binds = add_binds
local lousy = require "lousy"
local sql_escape = lousy.util.sql_escape
local capi = { luakit = luakit, sqlite3 = sqlite3 }
local domain_props = domain_props
module "noscript"
-- Default blocking values
enable_scripts = false
enable_plugins = false
create_table = [[
CREATE TABLE IF NOT EXISTS by_domain (
id INTEGER PRIMARY KEY,
domain TEXT,
enable_scripts INTEGER,
enable_plugins INTEGER
);]]
db = capi.sqlite3{ filename = ":memory:" }
db:exec("PRAGMA synchronous = OFF; PRAGMA secure_delete = 1;")
db:exec(create_table)
local function btoi(bool) return bool and 1 or 0 end
local function itob(int) return tonumber(int) ~= 0 end
local function get_domain(uri)
uri = assert(lousy.uri.parse(uri), "invalid uri")
return string.lower(uri.host)
end
local function match_domain(domain)
local rows = db:exec(string.format("SELECT * FROM by_domain "
.. "WHERE domain == %s;", sql_escape(domain)))
if rows[1] then return rows[1] end
end
local function update(id, field, value)
db:exec(string.format("UPDATE by_domain SET %s = %d WHERE id == %d;",
field, btoi(value), id))
end
local function insert(domain, enable_scripts, enable_plugins)
db:exec(string.format("INSERT INTO by_domain VALUES (NULL, %s, %d, %d);",
sql_escape(domain), btoi(enable_scripts), btoi(enable_plugins)))
end
function webview.methods.toggle_scripts(view, w)
local domain = get_domain(view.uri)
if domain_props[domain] and domain_props[domain].enable_scripts ~= nil then
w:notify(string.format("Scripts on %s are %sabled in globals.lua.",
domain, domain_props[domain].enable_scripts and "en" or "dis"))
return
end
local enable_scripts = _M.enable_scripts
local row = match_domain(domain)
if row then
enable_scripts = itob(row.enable_scripts)
update(row.id, "enable_scripts", not enable_scripts)
else
insert(domain, not enable_scripts, _M.enable_plugins)
end
w:notify(string.format("%sabled scripts for domain: %s",
enable_scripts and "Dis" or "En", domain))
end
function webview.methods.toggle_plugins(view, w)
local domain = get_domain(view.uri)
local enable_plugins = _M.enable_plugins
local row = match_domain(domain)
if domain_props[domain] and domain_props[domain].enable_plugins ~= nil then
w:notify(string.format("Plugins on %s are %sabled in globals.lua.",
domain, domain_props[domain].enable_plugins and "en" or "dis"))
return
end
if row then
enable_plugins = itob(row.enable_plugins)
update(row.id, "enable_plugins", not enable_plugins)
else
insert(domain, _M.enable_scripts, not enable_plugins)
end
w:notify(string.format("%sabled plugins for domain: %s",
enable_plugins and "Dis" or "En", domain))
end
function webview.methods.toggle_remove(view, w)
local domain = get_domain(view.uri)
db:exec(string.format("DELETE FROM by_domain WHERE domain == %s;",
sql_escape(domain)))
w:notify("Removed rules for domain: " .. domain)
end
function defaults_for(domain)
local scripts, plugins = _M.enable_scripts, _M.enable_plugins
if domain_props[domain] then
if domain_props[domain].enable_scripts ~= nil then
scripts = domain_props[domain].enable_scripts
end
if domain_props[domain].enable_plugins ~= nil then
plugins = domain_props[domain].enable_plugins
end
end
return scripts, plugins
end
webview.init_funcs.noscript_load = function (view)
view:add_signal("load-status", function (v, status)
if status ~= "committed" or v.uri == "about:blank" then return end
local domain = get_domain(v.uri)
local enable_scripts, enable_plugins = defaults_for(domain)
local row = match_domain(domain)
if row then
enable_scripts = itob(row.enable_scripts)
enable_plugins = itob(row.enable_plugins)
end
view.enable_scripts = enable_scripts
view.enable_plugins = enable_plugins
end)
end
local buf = lousy.bind.buf
add_binds("normal", {
buf("^cs$", function (w) w:toggle_scripts() end),
buf("^cp$", function (w) w:toggle_plugins() end),
buf("^cr$", function (w) w:toggle_remove() end),
})
| unlicense |
nyczducky/darkstar | scripts/globals/items/piece_of_witch_nougat.lua | 12 | 1280 | -----------------------------------------
-- 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 |
rkoval/dotfiles | nvim/lua/ryankoval/stylua.lua | 1 | 2012 | local Path = require('plenary.path')
local Job = require('plenary.job')
local lspconfig_util = require('lspconfig.util')
local cached_configs = {}
local root_finder = lspconfig_util.root_pattern('.git')
local stylua_finder = function(path)
if cached_configs[path] == nil then
local file_path = Path:new(path)
local root_path = Path:new(root_finder(path))
local file_parents = file_path:parents()
local root_parents = root_path:parents()
local relative_diff = #file_parents - #root_parents
for index, dir in ipairs(file_parents) do
if index > relative_diff then
break
end
local stylua_path = Path:new({ dir, 'stylua.toml' })
if stylua_path:exists() then
cached_configs[path] = stylua_path:absolute()
break
end
stylua_path = Path:new({ dir, '.stylua.toml' })
if stylua_path:exists() then
cached_configs[path] = stylua_path:absolute()
break
end
end
end
return cached_configs[path]
end
local stylua = {}
stylua.format = function(bufnr)
bufnr = bufnr or vim.api.nvim_get_current_buf()
local filepath = Path:new(vim.api.nvim_buf_get_name(bufnr)):absolute()
local stylua_toml = stylua_finder(filepath)
if not stylua_toml then
return
end
-- stylua: ignore
local j = Job:new {
"stylua",
"--config-path", stylua_toml,
"-",
writer = vim.api.nvim_buf_get_lines(0, 0, -1, false),
}
local output = j:sync()
if j.code ~= 0 then
-- Schedule this so that it doesn't do dumb stuff like printing two things.
vim.schedule(function()
print('[stylua] Failed to process due to errors')
end)
return
end
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, output)
pcall(vim.api.nvim_buf_clear_namespace, bufnr, Luasnip_ns_id, 0, -1)
-- Handle some weird snippet problems. Not everyone will necessarily have this problem.
Luasnip_current_nodes = Luasnip_current_nodes or {}
Luasnip_current_nodes[bufnr] = nil
end
return stylua
| mit |
nyczducky/darkstar | scripts/globals/items/vulcan_claymore.lua | 42 | 1451 | -----------------------------------------
-- ID: 18379
-- Item: Vulcan Claymore
-- Additional Effect: Fire Damage
-- Enchantment: Enfire
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end;
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
local effect = EFFECT_ENFIRE;
doEnspell(target,target,nil,effect);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_HM.lua | 23 | 1634 | -----------------------------------
-- Area: LaLoff Amphitheater
-- MOB: Ark Angel HM
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:addMod(MOD_REGAIN, 50);
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local mobid = mob:getID();
for member = mobid, mobid+7 do
if (GetMobAction(member) == 16) then
GetMobByID(member):updateEnmity(target);
end
end
local hp = math.random(1,60);
mob:setLocalVar("Mijin", hp);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local battletime = mob:getBattleTime();
local mstime = mob:getLocalVar("Mighty");
local mghp = mob:getLocalVar("Mijin");
if (battletime > mstime + 150) then
mob:useMobAbility(688);
mob:setLocalVar("Mighty", battletime);
elseif (mob:getHPP() < mghp) then
mob:useMobAbility(731);
mob:setLocalVar("Mijin", 0);
end
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
| gpl-3.0 |
dtrip/awesome | tests/test-input-binding.lua | 3 | 10045 | require("awful._compat")
local runner = require( "_runner" )
local placement = require( "awful.placement" )
local gtable = require( "gears.table" )
local test_client = require( "_client" )
local akeyboard = require( "awful.keyboard" )
local amouse = require( "awful.mouse" )
local module = {
key = require( "awful.key" ),
button = require( "awful.button" )
}
local steps = {}
local second = {
key = { "a", "b", "c", "d" },
button = { 1 , 2 , 3 , 4 },
}
local function send_events(event_type, step)
root.fake_input("key_press" , "Alt_L")
root.fake_input(event_type.."_press" , second[event_type][step])
root.fake_input(event_type.."_release", second[event_type][step])
root.fake_input("key_release", "Alt_L")
end
-- Test the shared API between the keys and buttons
for _, type_name in ipairs { "key", "button" } do
local objects = {}
local pressed, released = {}, {}
table.insert(steps, function()
objects[1] = module[type_name](
{"Mod1"}, second[type_name][1], function() pressed[1] = true end, function() released[1] = true end
)
assert(objects[1].has_root_binding == false)
assert(not pressed [1])
assert(not released[1])
root["_append_"..type_name](objects[1])
-- It is async, the result need to be verified later
return true
end)
table.insert(steps, function()
assert(objects[1].has_root_binding)
-- Test "artificial" execution
objects[1]:trigger()
assert(pressed [1])
assert(released[1])
-- Test adding and removing in the same iteration
root["_remove_"..type_name](objects[1])
assert(second[type_name][2])
-- Use the multiple parameters syntax.
objects[2] = module[type_name](
{"Mod1"}, second[type_name][2], function() pressed[2] = true end, function() released[2] = true end
)
root["_append_"..type_name](objects[2])
return true
end)
table.insert(steps, function()
assert(objects[2].has_root_binding == true )
assert(objects[1].has_root_binding == false)
-- Make sure the cursor is not over the wibar
placement.centered(mouse)
assert(second[type_name][2])
send_events(type_name, 2)
return true
end)
-- Wait until the events are registered.
table.insert(steps, function()
if (not pressed[2]) or (not released[2]) then return end
-- Spawn a client.
test_client("myclient")
return true
end)
--FIXME it works when manually tested, but automated testing is too flacky
-- to enable...
if type_name == "key" then
table.insert(steps, function()
if #mouse.screen.clients ~= 1 then return end
placement.maximize(mouse.screen.clients[1])
return true
end)
local o1, o2 = nil
table.insert(steps, function()
local c = mouse.screen.clients[1]
-- This time, use the `args` syntax.
local args = {
modifiers = {"Mod1"},
on_press = function() pressed [3] = true end,
on_release = function() released[3] = true end
}
args[type_name] = second[type_name][3]
-- This time, use the `args` syntax.
o1 = module[type_name](args)
-- Test the old API.
c[type_name.."s"](c, gtable.join(o1))
return true
end)
-- This wont work until the client buttons/keys are updated, there is no
-- way to know ahead of time.
table.insert(steps, function(count)
if count < 5 then awesome.sync(); return end
send_events(type_name, 3)
return true
end)
table.insert(steps, function()
if (not pressed[3]) or (not released[3]) then return end
local c = mouse.screen.clients[1]
-- Unset the events to make sure keys can be removed.
pressed[3], released[3] = false, false
o2 = module[type_name](
{"Mod1"}, second[type_name][4], function() pressed[4] = true end, function() released[4] = true end
)
-- Test the new API
c[type_name.."s"] = {o2}
return true
end)
table.insert(steps, function(count)
if count < 5 then awesome.sync(); return end
send_events(type_name, 3)
send_events(type_name, 4)
return true
end)
table.insert(steps, function()
if (not pressed[4]) or (not released[4]) then return end
assert(not pressed [3])
assert(not released[3])
local c = mouse.screen.clients[1]
-- Make sure mixing the 2 syntaxes doesn't create a chimera state
pressed[4], released[4] = false, false
-- This *will* happen with older configs because `awful.rules` will
-- loop the properties, find the old capi list and fail to understand
-- that the content should use the legacy API.
local joined = gtable.join(o1)
assert(#joined == 4)
c[type_name.."s"] = joined
-- It should have been converted to the new format.
assert(#c[type_name.."s"] == 1)
return true
end)
table.insert(steps, function(count)
if count < 5 then awesome.sync(); return end
send_events(type_name, 3)
send_events(type_name, 4)
return true
end)
table.insert(steps, function()
if (not pressed[3]) or (not released[3]) then return end
assert(not pressed [4])
assert(not released[4])
local c = mouse.screen.clients[1]
assert(#c[type_name.."s"] == 1)
-- Test setting the object to `false` to simulate an inline Lua
-- expression gone wrong. This used to work and is rather
-- convenient, so lets not break it even if it is technically a bug.
c[type_name.."s"] = false
assert(#c[type_name.."s"] == 0)
c[type_name.."s"] = {o1}
assert(#c[type_name.."s"] == 1)
-- Test removing the objects using `nil`.
c[type_name.."s"] = nil
assert(#c[type_name.."s"] == 0)
c[type_name.."s"] = {o1}
assert(#c[type_name.."s"] == 1)
-- Test removing using `{}`
c[type_name.."s"] = {}
assert(#c[type_name.."s"] == 0)
c:kill()
return true
end)
-- Cleanup (otherwise there is a race with the root.buttons tests)
table.insert(steps, function()
if #mouse.screen.clients ~= 0 then return end
return true
end)
end
end
local exe1, exe2, exe3, exe4 = false, false, false, false
local new1, new2 = nil, nil
-- Check that you can add new default key/mousebindings at any time.
table.insert(steps, function()
assert(#mouse.screen.clients == 0)
new1 = module.key {
key = "a",
modifiers = {},
on_press = function() exe1 = true end
}
new2 = module.button {
button = 8,
modifiers = {},
on_press = function() exe2 = true end
}
akeyboard.append_client_keybinding(new1)
amouse.append_client_mousebinding(new2)
-- Spawn a client.
test_client("myclient")
return true
end)
table.insert(steps, function()
if #mouse.screen.clients == 0 then return end
client.focus = mouse.screen.clients[1]
-- That should trigger the newly added keybinding.
root.fake_input("key_press" , "a")
root.fake_input("key_release", "a")
-- Move the mouse over the client so mousebindings work.
placement.centered(mouse, {parent=client.focus})
awesome.sync()
-- Same thing for the mouse.
root.fake_input("button_press" , 8)
root.fake_input("button_release", 8)
return true
end)
table.insert(steps, function()
if (not exe1) or (not exe2) then return end
akeyboard.remove_client_keybinding(new1)
amouse.remove_client_mousebinding(new2)
exe1, exe2 = false, false
return true
end)
-- Removing is async, so wait until the next loop.
table.insert(steps, function()
root.fake_input("key_press" , "a")
root.fake_input("key_release", "a")
root.fake_input("button_press" , 8)
root.fake_input("button_release", 8)
awesome.sync()
return true
end)
-- Try adding key/mousebindings to existing clients.
table.insert(steps, function(count)
if count ~= 3 then return end
assert(not exe1)
assert(not exe2)
-- Append both types at the same time to make sure nothing overwrite
-- the list.
akeyboard.append_client_keybinding(new1)
amouse.append_client_mousebinding(new2)
new1 = module.key {
key = "b",
modifiers = {},
on_press = function() exe3 = true end
}
new2 = module.button {
button = 7,
modifiers = {},
on_press = function() exe4 = true end
}
-- Append directly on the client.
client.focus:append_keybinding(new1)
client.focus:append_mousebinding(new2)
return true
end)
-- Removing is async, so wait until the next loop.
table.insert(steps, function()
root.fake_input("key_press" , "b")
root.fake_input("key_release", "b")
root.fake_input("button_press" , 7)
root.fake_input("button_release", 7)
return true
end)
table.insert(steps, function()
if (not exe3) or (not exe4) then return end
-- Note, there is no point to try remove_keybinding, it was already called
-- (indirectly) 4 steps ago.
return true
end)
runner.run_steps(steps)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
vorbi123/x | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
omidtarh/elbot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
MRAHS/Black-Mask | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
SHIELDPOWER/Shield-power | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
duhoobo/lua-xpath | tests/refcount.lua | 1 | 1156 | package.cpath = "/home/duhoobo/prj/amateur/lua-xpath/src/?.so;" .. package.cpath
local xpath = require("xpath")
xml = [[
<html>
<head>
</head>
<body>
<name color="red">alec</name>
<name color="green">bing</name>
<sex>male</sex>
</body>
</html>]]
local sel, err = xpath.loads(xml)
if not sel then
print(err)
return nil
end
print(sel)
local list, err = sel:xpath("//body/name/@color")
if not list then
print(err)
return nil
end
for k, v in pairs(list) do
print(k, v)
end
print(sel)
print "release root `sel`"
sel = nil
print "\n--- enter 1st gc"
collectgarbage("collect")
print "--- leave 1st gc\n"
print "keep the first node, release root `sel` and the second `sel`"
sel = list[1]
print(sel)
list = nil
print "\n--- enter 2nd gc ---"
collectgarbage("collect")
print "--- leave 2nd gc ---\n"
print(sel)
sel = nil
print "release the first node"
print "\n--- enter 3rd gc ---"
collectgarbage("collect")
print "--- leave 3rd gc ---\n"
print "references are all clear"
print "\n--- enter 4th gc ---"
collectgarbage("collect")
print "--- leave 4th gc ---\n"
print "new root `sel`"
sel, err = xpath.loads(xml)
| gpl-3.0 |
hfjgjfg/uzzz | plugins/banhammer.lua | 294 | 10470 | 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
chat_del_user(chat, user, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
-- Save to redis
local hash = 'superbanned:'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
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 is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned 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 superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, msg.to.id)
if superbanned or 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 superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, chat_id)
if superbanned then
print('SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
end
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 username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if get_cmd == 'kick' then
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'superban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!')
return superban_user(member_id, chat_id)
elseif get_cmd == 'whitelist user' then
local hash = 'whitelist:user#id'..member_id
redis:set(hash, true)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted')
elseif get_cmd == 'whitelist delete user' then
local hash = 'whitelist:user#id'..member_id
redis:del(hash)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist')
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1] == 'kickme' then
kick_user(msg.from.id, msg.to.id)
end
if not is_momod(msg) then
return nil
end
local receiver = get_receiver(msg)
if matches[4] then
get_cmd = matches[1]..' '..matches[2]..' '..matches[3]
elseif matches[3] then
get_cmd = matches[1]..' '..matches[2]
else
get_cmd = matches[1]
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
if string.match(matches[3], '^%d+$') then
ban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
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] == 'superban' and is_admin(msg) then
local user_id = matches[3]
local chat_id = msg.to.id
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
superban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' globally banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'superbanned:'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
kick_user(matches[2], msg.to.id)
else
local member = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
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.print_name..' ['..msg.to.id..'] whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
if string.match(matches[4], '^%d+$') then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
else
local member = string.gsub(matches[4], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
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.print_name..' ['..msg.to.id..'] removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
user = "!kickme : Exit from group",
moderator = {
"!whitelist <enable>/<disable> : Enable or disable whitelist mode",
"!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist user <username> : 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 user <username> : 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 by id",
"!kick <username> : Kick user from chat group by username",
},
admin = {
"!superban user <user_id> : Kick user from all chat and kicks it if joins again",
"!superban user <username> : Kick user from all chat and kicks it if joins again",
"!superban delete <user_id> : Unban user",
},
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (.*)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (.*)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (.*)$",
"^!(ban) (delete) (.*)$",
"^!(superban) (user) (.*)$",
"^!(superban) (delete) (.*)$",
"^!(kick) (.*)$",
"^!(kickme)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
} | gpl-2.0 |
ffxiphoenix/darkstar | scripts/zones/Windurst_Walls/npcs/Moan-Maon.lua | 38 | 1408 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Moan-Maon
-- Type: Standard NPC
-- @pos 88.244 -6.32 148.912 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,7) == false) then
player:startEvent(0x01f1);
else
player:startEvent(0x0133);
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 == 0x01f1) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",7,true);
end
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/PsoXja/npcs/HomePoint#1.lua | 19 | 1171 | -----------------------------------
-- Area: PsoXja
-- NPC: HomePoint#1
-- @pos -58 40 14 10
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/FeiYin/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 82);
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 == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
veryrandomname/obuut | hump/camera.lua | 47 | 3388 | --[[
Copyright (c) 2010-2013 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local _PATH = (...):match('^(.*[%./])[^%.%/]+$') or ''
local cos, sin = math.cos, math.sin
local camera = {}
camera.__index = camera
local function new(x,y, zoom, rot)
x,y = x or love.graphics.getWidth()/2, y or love.graphics.getHeight()/2
zoom = zoom or 1
rot = rot or 0
return setmetatable({x = x, y = y, scale = zoom, rot = rot}, camera)
end
function camera:lookAt(x,y)
self.x, self.y = x,y
return self
end
function camera:move(x,y)
self.x, self.y = self.x + x, self.y + y
return self
end
function camera:pos()
return self.x, self.y
end
function camera:rotate(phi)
self.rot = self.rot + phi
return self
end
function camera:rotateTo(phi)
self.rot = phi
return self
end
function camera:zoom(mul)
self.scale = self.scale * mul
return self
end
function camera:zoomTo(zoom)
self.scale = zoom
return self
end
function camera:attach()
local cx,cy = love.graphics.getWidth()/(2*self.scale), love.graphics.getHeight()/(2*self.scale)
love.graphics.push()
love.graphics.scale(self.scale)
love.graphics.translate(cx, cy)
love.graphics.rotate(self.rot)
love.graphics.translate(-self.x, -self.y)
end
function camera:detach()
love.graphics.pop()
end
function camera:draw(func)
self:attach()
func()
self:detach()
end
function camera:cameraCoords(x,y)
-- x,y = ((x,y) - (self.x, self.y)):rotated(self.rot) * self.scale + center
local w,h = love.graphics.getWidth(), love.graphics.getHeight()
local c,s = cos(self.rot), sin(self.rot)
x,y = x - self.x, y - self.y
x,y = c*x - s*y, s*x + c*y
return x*self.scale + w/2, y*self.scale + h/2
end
function camera:worldCoords(x,y)
-- x,y = (((x,y) - center) / self.scale):rotated(-self.rot) + (self.x,self.y)
local w,h = love.graphics.getWidth(), love.graphics.getHeight()
local c,s = cos(-self.rot), sin(-self.rot)
x,y = (x - w/2) / self.scale, (y - h/2) / self.scale
x,y = c*x - s*y, s*x + c*y
return x+self.x, y+self.y
end
function camera:mousepos()
return self:worldCoords(love.mouse.getPosition())
end
-- the module
return setmetatable({new = new},
{__call = function(_, ...) return new(...) end})
| mit |
ffxiphoenix/darkstar | scripts/globals/items/mushroom_salad.lua | 39 | 1426 | -----------------------------------------
-- ID: 5678
-- Item: Mushroom Salad
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- MP 14% Cap 85
-- Agility 6
-- Mind 6
-- Strength -5
-- Vitality -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5678);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 14);
target:addMod(MOD_FOOD_MP_CAP, 85);
target:addMod(MOD_AGI, 6);
target:addMod(MOD_MND, 6);
target:addMod(MOD_STR, -5);
target:addMod(MOD_VIT, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 14);
target:delMod(MOD_FOOD_MP_CAP, 85);
target:delMod(MOD_AGI, 6);
target:delMod(MOD_MND, 6);
target:delMod(MOD_STR, -5);
target:delMod(MOD_VIT, -5);
end;
| gpl-3.0 |
mcseemka/vlc | share/lua/modules/simplexml.lua | 103 | 3732 | --[==========================================================================[
simplexml.lua: Lua simple xml parser wrapper
--[==========================================================================[
Copyright (C) 2010 Antoine Cellerier
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
module("simplexml",package.seeall)
--[[ Returns the xml tree structure
-- Each node is of one of the following types:
-- { name (string), attributes (key->value map), children (node array) }
-- text content (string)
--]]
local function parsexml(stream, errormsg)
if not stream then return nil, errormsg end
local xml = vlc.xml()
local reader = xml:create_reader(stream)
local tree
local parents = {}
local nodetype, nodename = reader:next_node()
while nodetype > 0 do
if nodetype == 1 then
local node = { name= nodename, attributes= {}, children= {} }
local attr, value = reader:next_attr()
while attr ~= nil do
node.attributes[attr] = value
attr, value = reader:next_attr()
end
if tree then
table.insert(tree.children, node)
table.insert(parents, tree)
end
tree = node
elseif nodetype == 2 then
if #parents > 0 then
local tmp = {}
while nodename ~= tree.name do
if #parents == 0 then
error("XML parser error/faulty logic")
end
local child = tree
tree = parents[#parents]
table.remove(parents)
table.remove(tree.children)
table.insert(tmp, 1, child)
for i, node in pairs(child.children) do
table.insert(tmp, i+1, node)
end
child.children = {}
end
for _, node in pairs(tmp) do
table.insert(tree.children, node)
end
tree = parents[#parents]
table.remove(parents)
end
elseif nodetype == 3 then
table.insert(tree.children, nodename)
end
nodetype, nodename = reader:next_node()
end
if #parents > 0 then
error("XML parser error/Missing closing tags")
end
return tree
end
function parse_url(url)
return parsexml(vlc.stream(url))
end
function parse_string(str)
return parsexml(vlc.memory_stream(str))
end
function add_name_maps(tree)
tree.children_map = {}
for _, node in pairs(tree.children) do
if type(node) == "table" then
if not tree.children_map[node.name] then
tree.children_map[node.name] = {}
end
table.insert(tree.children_map[node.name], node)
add_name_maps(node)
end
end
end
| gpl-2.0 |
keshwans/vlc | share/lua/modules/simplexml.lua | 103 | 3732 | --[==========================================================================[
simplexml.lua: Lua simple xml parser wrapper
--[==========================================================================[
Copyright (C) 2010 Antoine Cellerier
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
module("simplexml",package.seeall)
--[[ Returns the xml tree structure
-- Each node is of one of the following types:
-- { name (string), attributes (key->value map), children (node array) }
-- text content (string)
--]]
local function parsexml(stream, errormsg)
if not stream then return nil, errormsg end
local xml = vlc.xml()
local reader = xml:create_reader(stream)
local tree
local parents = {}
local nodetype, nodename = reader:next_node()
while nodetype > 0 do
if nodetype == 1 then
local node = { name= nodename, attributes= {}, children= {} }
local attr, value = reader:next_attr()
while attr ~= nil do
node.attributes[attr] = value
attr, value = reader:next_attr()
end
if tree then
table.insert(tree.children, node)
table.insert(parents, tree)
end
tree = node
elseif nodetype == 2 then
if #parents > 0 then
local tmp = {}
while nodename ~= tree.name do
if #parents == 0 then
error("XML parser error/faulty logic")
end
local child = tree
tree = parents[#parents]
table.remove(parents)
table.remove(tree.children)
table.insert(tmp, 1, child)
for i, node in pairs(child.children) do
table.insert(tmp, i+1, node)
end
child.children = {}
end
for _, node in pairs(tmp) do
table.insert(tree.children, node)
end
tree = parents[#parents]
table.remove(parents)
end
elseif nodetype == 3 then
table.insert(tree.children, nodename)
end
nodetype, nodename = reader:next_node()
end
if #parents > 0 then
error("XML parser error/Missing closing tags")
end
return tree
end
function parse_url(url)
return parsexml(vlc.stream(url))
end
function parse_string(str)
return parsexml(vlc.memory_stream(str))
end
function add_name_maps(tree)
tree.children_map = {}
for _, node in pairs(tree.children) do
if type(node) == "table" then
if not tree.children_map[node.name] then
tree.children_map[node.name] = {}
end
table.insert(tree.children_map[node.name], node)
add_name_maps(node)
end
end
end
| gpl-2.0 |
farrajota/human_pose_estimation_torch | models/test/hg-generic-ensemblev2.lua | 1 | 2250 | paths.dofile('../layers/Residual.lua')
local function hourglass(n, f, inp)
-- Upper branch
local up1 = Residual(f,f)(inp)
-- Lower branch
local pool = nn.SpatialMaxPooling(2,2,2,2)(inp)
local low1 = Residual(f,f)(pool)
local low2
if n > 1 then low2 = hourglass(n-1,f,low1)
else low2 = Residual(f,f)(low1) end
local low3 = Residual(f,f)(low2)
local up2 = nn.SpatialUpSamplingNearest(2)(low3)
-- Bring two branches together
return nn.CAddTable()({up1,up2})
end
local function lin(numIn,numOut,inp)
-- Apply 1x1 convolution, stride 1, no padding
local l = nn.SpatialConvolution(numIn,numOut,1,1,1,1,0,0)(inp)
return nn.ReLU(true)(nn.SpatialBatchNormalization(numOut)(l))
end
local function lin2(numIn,numOut,inp)
-- Apply 1x1 convolution, stride 1, no padding
local bn_relu = nn.ReLU(true)(nn.SpatialBatchNormalization(numIn)(inp))
return nn.SpatialConvolution(numIn,numOut,1,1,1,1,0,0)(bn_relu)
end
local function createModel()
local inp = nn.Identity()()
-- Initial processing of the image
local cnv1_ = nn.SpatialConvolution(3,64,7,7,2,2,3,3)(inp) -- 128
local cnv1 = nn.ReLU(true)(nn.SpatialBatchNormalization(64)(cnv1_))
local r1 = Residual(64,128)(cnv1)
local pool = nn.SpatialMaxPooling(2,2,2,2)(r1) -- 64
local r4 = Residual(128,128)(pool)
local r5 = Residual(128,opt.nFeats)(r4)
local out = {}
local inter = r5
for i = 1,opt.nStack do
local hg = hourglass(4,opt.nFeats,inter)
-- Linear layer to produce first set of predictions
local ll = lin(opt.nFeats,opt.nFeats,hg)
-- Predicted heatmaps
local tmpOut = nn.SpatialConvolution(opt.nFeats,outputDim[1][1],1,1,1,1,0,0)(ll)
table.insert(out,tmpOut)
if i < opt.nStack then inter = nn.CAddTable()({inter, hg}) end
end
local concat_outputs = nn.JoinTable(2)(out)
local ll1 = lin2(outputDim[1][1]*opt.nStack , 512, concat_outputs)
local ll2 = lin2(512, outputDim[1][1], ll1)
table.insert(out, ll2)
opt.nOutputs = opt.nStack+1
-- Final model
local model = nn.gModule({inp}, out)
return model
end
-------------------------
return createModel | mit |
ffxiphoenix/darkstar | scripts/zones/Port_Bastok/npcs/Bartolomeo.lua | 34 | 1612 | -----------------------------------
-- Area: Port Bastok
-- NPC: Bartolomeo
-- Standard Info NPC
-- Involved in Quest: Welcome to Bastok
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WelcometoBastok = player:getQuestStatus(BASTOK,WELCOME_TO_BASTOK);
if (WelcometoBastok == QUEST_ACCEPTED and player:getVar("WelcometoBastok_Event") ~= 1 and player:getEquipID(SLOT_SUB) == 12415) then -- Shell Shield
player:startEvent(0x0034);
else
player:messageSpecial(BARTHOLOMEO_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 == 0x34 and player:getQuestStatus(BASTOK,WELCOME_TO_BASTOK) == QUEST_ACCEPTED) then
player:setVar("WelcometoBastok_Event",1)
end
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Caedarva_Mire/npcs/Nasheefa.lua | 19 | 1384 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Nasheefa
-- Type: Alzadaal Undersea Ruins
-- @pos -440.998 0.107 -740.015 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then -- Silver
player:tradeComplete();
player:startEvent(0x00b7);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getXPos() < -440) then
player:startEvent(0x00be);
else
player:startEvent(0x00b6);
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 == 0x00b7) then
player:setPos(-219.977,-4,474.522,64,72); -- To Alzadaal Undersea Ruins {R}
end
end; | gpl-3.0 |
DaanVanYperen/ns2-xeno-panic | output/lua/XenoPanic/xp_PickupSpawning.lua | 1 | 4573 | if Server then
local function SpawnWeapons(self, techPoint)
local weaponTypes = {
MedPack.kMapName,
MedPack.kMapName,
GrenadeLauncherAmmo.kMapName,
FlamethrowerAmmo.kMapName,
RifleAmmo.kMapName,
RifleAmmo.kMapName,
ShotgunAmmo.kMapName,
ShotgunAmmo.kMapName,
Pistol.kMapName,
Pistol.kMapName,
Pistol.kMapName,
Pistol.kMapName,
Pistol.kMapName,
Rifle.kMapName,
Rifle.kMapName,
Rifle.kMapName,
Rifle.kMapName,
Shotgun.kMapName,
Shotgun.kMapName,
Shotgun.kMapName,
Welder.kMapName,
Welder.kMapName,
Welder.kMapName,
Flamethrower.kMapName,
GrenadeLauncher.kMapName,
LayMines.kMapName,
ClusterGrenadeThrower.kMapName,
PulseGrenadeThrower.kMapName,
GasGrenadeThrower.kMapName
}
for i = 1, #Server.itemSpawnList do
local current = Server.itemSpawnList[i]
// place some random weapons.
local spawnOrigin = current:GetOrigin() + Vector(0, .2, 0)
local randomWeapon = weaponTypes[math.random(#weaponTypes)]
newEnt = CreateEntity( randomWeapon, spawnOrigin, self:GetTeamNumber() )
if newEnt ~= nil then
-- give weapons a physics model so they can plop down.
if not newEnt.physicsModel then
newEnt.physicsModel = Shared.CreatePhysicsModel(newEnt.physicsModelIndex, true, newEnt:GetCoords(), newEnt)
end
if HasMixin(newEnt,"RifleVariant") then
end
end
end
end
/**
* Spawn hive or command station at nearest empty tech point to specified team location.
* Does nothing if can't find any.
*/
local function SpawnCommandStructure(techPoint, teamNumber)
local commandStructure = techPoint:SpawnCommandStructure(teamNumber)
assert(commandStructure ~= nil)
commandStructure:SetConstructionComplete()
// Use same align as tech point.
local techPointCoords = techPoint:GetCoords()
techPointCoords.origin = commandStructure:GetOrigin()
commandStructure:SetCoords(techPointCoords)
return commandStructure
end
function PlayingTeam:SpawnInitialStructures(techPoint)
assert(techPoint ~= nil)
// Spawn weapons for marine team.
if ( self:GetTeamNumber() == kTeam1Index ) then
SpawnWeapons(self, techPoint)
end
// Spawn hive/command station at team location.
local commandStructure = SpawnCommandStructure(techPoint, self:GetTeamNumber())
return tower, commandStructure
end
function MarineTeam:SpawnInitialStructures(techPoint)
local tower, commandStation = PlayingTeam.SpawnInitialStructures(self, techPoint)
-- Instance armslab. We need it!
local origin = commandStation:GetOrigin()
local right = commandStation:GetCoords().xAxis
local forward = commandStation:GetCoords().zAxis
local armslab = CreateEntity( ArmsLab.kMapName, origin+right*3.5+forward*1.5, kMarineTeamType)
armslab:SetConstructionComplete()
return tower, commandStation
end
end
function DropPack:OnInitialized()
ScriptActor.OnInitialized(self)
if Server then
-- XP START
-- Disable default timeout for medpacks and the like.
self.pickupRange = 1
-- XP END
self:SetAngles(Angles(0, math.random() * math.pi * 2, 0))
self:OnUpdate(0)
end
end
function Weapon:Dropped(prevOwner)
if prevOwner ~= nil then
local slot = self:GetHUDSlot()
self.prevOwnerId = prevOwner:GetId()
-- XP START
-- prevent weapons from despawning
self:SetWeaponWorldState(true,true)
-- XP END
// when dropped weapons always need a physic model
if not self.physicsModel then
self.physicsModel = Shared.CreatePhysicsModel(self.physicsModelIndex, true, self:GetCoords(), self)
end
if self.physicsModel then
local viewCoords = prevOwner:GetViewCoords()
local impulse = 0.075
if slot == 2 then
impulse = 0.0075
elseif slot == 3 then
impulse = 0.005
end
self.physicsModel:AddImpulse(self:GetOrigin(), (viewCoords.zAxis * impulse))
self.physicsModel:SetAngularVelocity(Vector(5,0,0))
end
end
end
| mit |
ffxiphoenix/darkstar | scripts/zones/Crawlers_Nest/npcs/qm10.lua | 57 | 2127 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: qm10 (??? - Exoray Mold Crumbs)
-- Involved in Quest: In Defiant Challenge
-- @pos -83.391 -8.222 79.065 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Crawlers_Nest/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB1) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(EXORAY_MOLD_CRUMB1);
player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB1);
end
if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1089, 1);
player:messageSpecial(ITEM_OBTAINED, 1089);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089);
end
end
if (player:hasItem(1089)) then
player:delKeyItem(EXORAY_MOLD_CRUMB1);
player:delKeyItem(EXORAY_MOLD_CRUMB2);
player:delKeyItem(EXORAY_MOLD_CRUMB3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
azekillDIABLO/Voxellar | mods/MISC/conjuration/tools.lua | 1 | 4738 | ---( Tools )---
---( First come the Books )---
tool_type = {
"Pickaxe",
"Axe",
"Shovel",
"Sword"
}
book_level = {
{"Lesser", 100000, 50},
{"", 18000, 75},
{"Greater", 4000, 99}
}
local function scan(inv)
for s=1,32 do
local stack = inv:get_stack("main", s)
local theName = stack:get_name()
for i=1,4 do
if theName == 'conjuration:' .. tool_type[i]:lower() then
return 0
end
end
end
return 1
end
for i=1,4 do
for _, rowc in ipairs(book_level) do
local level = rowc[1]
local level_wear = rowc[2]
local color_int = rowc[3]
local inventory_image = "(default_book.png^[colorize:#008080" .. color_int .. ")^(default_bookshelf_slot.png^[colorize:#0040FF" .. color_int .. ")"
local level_name = ""
if level == "Lesser" or level == "Greater" then
level_name = level .. " "
end
minetest.register_tool("conjuration:book_" .. tool_type[i]:lower() .. level:lower(), {
description = level_name .. "Book of Conjure " .. tool_type[i],
inventory_image = inventory_image,
tool_capabilities = {
full_punch_interval = 1.1,
},
sound = {breaks = "default_cool_lava"},
on_use = function(itemstack, player)
wear = itemstack:get_wear()
itemstack:set_wear(wear + level_wear)
local inv = player:get_inventory()
local full_slots = 1
local item_in_use = 0
local error_control = 0
for s=1,8 do
local tool_present = scan(inv)
if inv:get_stack("main", s):is_empty() == true and tool_present == 1 then
inv:set_stack("main", s, "conjuration:" .. tool_type[i]:lower())
conjuration.special_effects(player)
error_control = 1
else if error_control == 0 then
error_control = 1
minetest.sound_play("default_place_node_metal", player)
end
end
end
return itemstack
end
})
end
end
conjuration.special_effects = function(player)
minetest.sound_play("default_cool_lava", player)
local blue_screen = player:hud_add({
hud_elem_type = "image",
position = {x=0.5, y=0.5},
scale = {x=200, y=200},
text = "default_snow.png^[colorize:#0040FF99",
offset = {x=0, y=0},
})
minetest.after(0.1, function()
player:hud_remove(blue_screen)
end)
minetest.after(0.4, function()
minetest.sound_play("default_place_node_metal", player)
end)
end
---( Tools (Yea, actual tools.) )---
---( Pickaxe )---
minetest.register_tool("conjuration:pickaxe", {
description = "Bound Pickaxe",
inventory_image = "(default_tool_diamondpick.png^[brighten)^[colorize:#0040ff99",
tool_capabilities = {
full_punch_interval = 0.9,
max_drop_level=3,
groupcaps={
cracky = {times={[1]=2.0, [2]=1.0, [3]=0.50}, uses=6, maxlevel=3},
},
damage_groups = {fleshy=5},
},
sound = {breaks = "default_cool_lava"},
groups = {not_in_creative_inventory = 1},
on_drop = function(itemstack, dropper, pos)
return
end,
})
---( Shovel )---
minetest.register_tool("conjuration:shovel", {
description = "Bound Shovel",
inventory_image = "(default_tool_diamondshovel.png^[brighten)^[colorize:#0040ff99",
wield_image = "((default_tool_diamondshovel.png^[brighten)^[colorize:#0040ff99)^[transformR90",
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level=1,
groupcaps={
crumbly = {times={[1]=1.10, [2]=0.50, [3]=0.30}, uses=6, maxlevel=3},
},
damage_groups = {fleshy=4},
},
sound = {breaks = "default_cool_lava"},
groups = {not_in_creative_inventory = 1},
on_drop = function(itemstack, dropper, pos)
return
end,
})
---( Axe )---
minetest.register_tool("conjuration:axe", {
description = "Bound Axe",
inventory_image = "(default_tool_diamondaxe.png^[brighten)^[colorize:#0040ff99",
tool_capabilities = {
full_punch_interval = 0.9,
max_drop_level=1,
groupcaps={
choppy={times={[1]=2.20, [2]=1.00, [3]=0.60}, uses=6, maxlevel=3},
},
damage_groups = {fleshy=6},
},
sound = {breaks = "default_cool_lava"},
groups = {not_in_creative_inventory = 1},
on_drop = function(itemstack, dropper, pos)
return
end,
})
---( Sword )---
minetest.register_tool("conjuration:sword", {
description = "Bound Sword",
inventory_image = "(default_tool_diamondsword.png^[brighten)^[colorize:#0040ff99",
tool_capabilities = {
full_punch_interval = 0.7,
max_drop_level=1,
groupcaps={
snappy={times={[1]=1.90, [2]=0.90, [3]=0.30}, uses=6, maxlevel=3},
},
damage_groups = {fleshy=8},
},
sound = {breaks = "default_cool_lava"},
groups = {not_in_creative_inventory = 1},
on_drop = function(itemstack, dropper, pos)
return
end,
})
| lgpl-2.1 |
saadmzed/kenam | plugins/muteall.lua | 1 | 4894 | do
local function pre_process(msg)
local hash = 'muteall:'..msg.to.id
if redis:get(hash) and msg.to.type == 'channel' and not is_mod(msg) then
tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_})
end
return msg
end
local function run(msg, matches)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if matches[1] == 'mute' and matches[2] == 'all' and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
if not matches[3] then
redis:set(hash, true)
return "mute all has been enabled"
else
local hour = string.gsub(matches[3], 'h', '')
local num1 = tonumber(hour) * 3600
local minutes = string.gsub(matches[4], 'm', '')
local num2 = tonumber(minutes) * 60
local second = string.gsub(matches[5], 's', '')
local num3 = tonumber(second)
local num4 = tonumber(num1 + num2 + num3)
redis:setex(hash, num4, true)
if not lang then
return "Mute all has been enabled for \n⏺ hours : "..matches[3].."\n⏺ minutes : "..matches[4].."\n⏺ seconds : "..matches[5].."\n@BeyondTeam"
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[3].."\n⏺ دقیقه : "..matches[4].."\n⏺ ثانیه : "..matches[5].."\n@BeyondTeam"
end
end
end
if matches[1] == 'mute' and matches[2] == 'hours' and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
if not matches[3] then
redis:set(hash, true)
return "mute all has been enabled"
else
local hour = string.gsub(matches[3], 'h', '')
local num1 = tonumber(hour) * 3600
local num4 = tonumber(num1)
redis:setex(hash, num4, true)
if not lang then
return "Mute all has been enabled for \n⏺ hours : "..matches[3].."\n@BeyondTeam"
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[3].."\n@BeyondTeam"
end
end
end
if matches[1] == 'mute' and matches[2] == 'minutes' and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
if not matches[3] then
redis:set(hash, true)
return "mute all has been enabled"
else
local minutes = string.gsub(matches[3], 'm', '')
local num2 = tonumber(minutes) * 60
local num4 = tonumber(num2)
redis:setex(hash, num4, true)
if not lang then
return "Mute all has been enabled for \n⏺ minutes : "..matches[3].."\n@BeyondTeam"
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ دقیقه : "..matches[3].."\n@BeyondTeam"
end
end
end
if matches[1] == 'mute' and matches[2] == 'seconds' and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
if not matches[3] then
redis:set(hash, true)
return "mute all has been enabled"
else
local second = string.gsub(matches[3], 's', '')
local num3 = tonumber(second)
local num4 = tonumber(num3)
redis:setex(hash, num3, true)
if not lang then
return "Mute all has been enabled for \n⏺ seconds : "..matches[3].."\n@BeyondTeam"
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ ثانیه : "..matches[3].."\n@BeyondTeam"
end
end
end
if matches[1] == 'helpmute' then
if not lang then
text = [[
* اوامر كتم الصوت المؤقت:*
*!mute all* `(ساعات) (دقائق) (ثواني)`
_اوامر كتم الصوت في وقت محدد_
*!mute hours* `(العدد)`
_يمكنك الكتم لعدد من الساعات_
*!mute minute* `(العدد)`
_يمكنك الكتم لعدة دقائق_
*!mute seconds* `(العدد)`
_يمكنك الكتم ايضا لعدة ثواني_
*!unmute all*
_الغاء كتم الكل _
_يمكنك استخدام [!/#] في بداية الامر _
* مع تحياتي =>> @saad7m*
]]
elseif lang then
text = [[
* اوامر كتم الصوت المؤقت:*
*!mute all* `(ساعات) (دقائق) (ثواني)`
_اوامر كتم الصوت في وقت محدد_
*!mute hours* `(العدد)`
_يمكنك الكتم لعدد من الساعات_
*!mute minute* `(العدد)`
_يمكنك الكتم لعدة دقائق_
*!mute seconds* `(العدد)`
_يمكنك الكتم ايضا لعدة ثواني_
*!unmute all*
_الغاء كتم الكل _
_يمكنك استخدام [!/#] في بداية الامر _
* مع تحياتي =>> @saad7m*
]]
end
return text
end
if matches[1] == 'unmute' and matches[2] == 'all' and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
redis:del(hash)
if not lang then
return "mute all has been disabled"
elseif lang then
return "گروه ازاد شد و افراد می توانند دوباره پست بگذارند"
end
end
end
return {
patterns = {
"^[!/#]([Uu]nmute) (all)$",
"^[!/#]([Hh]elpmute)$",
"^[!/#]([Mm]ute) (all) (.*) (.*) (.*)$",
"^[!/#]([Mm]ute) (hours) (.*)$",
"^[!/#]([Mm]ute) (minutes) (.*)$",
"^[!/#]([Mm]ute) (seconds) (.*)$",
},
run = run,
pre_process = pre_process
}
end
--by @BeyondTeam
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Ilrusi_Atoll/npcs/Treasure_Coffer.lua | 17 | 1898 | -----------------------------------
-- Area:
-- NPC: Treasure Coffer
-- @zone illrusi atoll
-- @pos
-----------------------------------
package.loaded["scripts/zones/Ilrusi_Atoll/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Ilrusi_Atoll/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST);
local npcID = npc:getID();
local correctcofferID = GetServerVariable("correctcoffer");
print(npcID);
print(correctcofferID);
if (npcID == correctcofferID) then --correct coffer ??
player:messageSpecial( GOLDEN);
if (player:getCurrentMission(ASSAULT)==GOLDEN_SALVAGE) then
player:completeMission(ASSAULT,GOLDEN_SALVAGE);
end
GetNPCByID(17002654):setStatus(0);--spawn Ancient_Lockbox
local ID;
for ID=17002505,17002516,1 do
if (GetMobAction(ID) > 0) then DespawnMob(npcID);printf("mobdespawn: %u",ID); end--despawn mimic
end
GetNPCByID(npcID):setAnimation(89);--coffer open anim
else
SpawnMob(npcID);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Windurst_Waters/npcs/Shohrun-Tuhrun.lua | 36 | 1960 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Shohrun-Tuhrun
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SHOHRUNTUHRUN_SHOP_DIALOG);
stock = {
0x1239, 18000,1, --Haste
0x120C, 5178,2, --Scroll of Raise
0x1218, 10080,2, --Scroll of Dia II
0x121D, 8100,2, --Scroll of Banish II
0x122C, 6366,2, --Scroll of Protect II
0x1231, 15840,2, --Scroll of Shell II
0x1264, 4644,2, --Scroll of Enfire
0x1265, 3688,2, --Scroll of Enblizzard
0x1266, 2250,2, --Scroll of Enaero
0x1267, 1827,2, --Scroll of Enstone
0x1268, 1363,2, --Scroll of Enthunder
0x1269, 6366,2, --Scroll of Enwater
0x1203, 3261,3, --Scroll of Cure III
0x122E, 78200,3, --Scroll of Protect IV
0x1280, 74520,3, --Scroll of Protectra IV
0x1304, 64400,3 --Scroll of Dispel
}
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 |
ffxiphoenix/darkstar | scripts/zones/Quicksand_Caves/npcs/_5s2.lua | 17 | 1275 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -574 0 -420 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()-(-565);
local difZ = player:getZPos()-(-420);
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 |
AfuSensi/Mr.Green-MTA-Resources | resources/[gameplay]/scoreboard/dxscoreboard_http.lua | 12 | 2213 | -- Original file by jbeta
local httpColumns = {}
local httpRows = {}
local updateInterval = 1000
local lastUpdateTime = 0
function getScoreboardColumns()
-- Only update http data if someone is looking
if getTickCount() - lastUpdateTime > updateInterval then
lastUpdateTime = getTickCount()
refreshServerScoreboard()
end
return httpColumns
end
function getScoreboardRows()
return httpRows
end
local function getName( element )
local elementType = getElementType( element )
if elementType == "player" then
return getPlayerName( element )
elseif elementType == "team" then
return getTeamName( element )
end
end
local function calculateWidth()
local width = 0
for key, value in ipairs( scoreboardColumns ) do
width = width + value.width
end
return width
end
local function getRowData( element )
local rowData = { getElementType( element ), }
for key, column in ipairs( httpColumns ) do
if column.name == "name" then
table.insert( rowData, getName( element ) )
elseif column.name == "ping" then
local ping = ""
if getElementType( element ) == "player" then
ping = getPlayerPing( element )
end
table.insert( rowData, ping )
else
table.insert( rowData, getElementData( element, column.name ) or "" )
end
end
return rowData
end
function refreshServerScoreboard()
local scoreboardNewColumns = {}
for key, column in ipairs( scoreboardColumns ) do
table.insert( scoreboardNewColumns, { ["name"] = column.name, ["size"] = column.width/calculateWidth() } )
end
httpColumns = scoreboardNewColumns
local scoreboardNewRows = {}
local players = getElementsByType( "player" )
for key, player in ipairs( players ) do
if isElement( player ) and not getPlayerTeam( player ) then
table.insert( scoreboardNewRows, getRowData( player ) )
end
end
local teams = getElementsByType( "team" )
for key, team in ipairs( teams ) do
if isElement( team ) then
table.insert( scoreboardNewRows, getRowData( team ) )
local players = getPlayersInTeam( team )
for i, player in ipairs( players ) do
if isElement( player ) then
table.insert( scoreboardNewRows, getRowData( player ) )
end
end
end
end
httpRows = scoreboardNewRows
end | mit |
noooway/love2d_arkanoid_tutorial | 3-15_MoreSounds/bricks.lua | 3 | 6627 | local vector = require "vector"
local bricks = {}
bricks.image = love.graphics.newImage( "img/800x600/bricks.png" )
bricks.tile_width = 64
bricks.tile_height = 32
bricks.tileset_width = 384
bricks.tileset_height = 160
bricks.rows = 11
bricks.columns = 8
bricks.top_left_position = vector( 47, 34 )
bricks.brick_width = bricks.tile_width
bricks.brick_height = bricks.tile_height
bricks.horizontal_distance = 0
bricks.vertical_distance = 0
bricks.current_level_bricks = {}
bricks.no_more_bricks = false
local simple_break_sound = {
love.audio.newSource(
"sounds/simple_break/recordered_glass_norm.ogg",
"static"),
love.audio.newSource(
"sounds/simple_break/edgardedition_glass_hit_norm.ogg",
"static") }
local armored_hit_sound = {
love.audio.newSource(
"sounds/armored_hit/qubodupImpactMetal_short_norm.ogg",
"static"),
love.audio.newSource(
"sounds/armored_hit/cast_iron_clangs_14_short_norm.ogg",
"static"),
love.audio.newSource(
"sounds/armored_hit/cast_iron_clangs_22_short_norm.ogg",
"static") }
local armored_break_sound = {
love.audio.newSource(
"sounds/armored_break/armored_glass_break_short_norm.ogg",
"static"),
love.audio.newSource(
"sounds/armored_break/ngruber__breaking-glass_6_short_norm.ogg",
"static") }
local ball_heavyarmored_sound = {
love.audio.newSource(
"sounds/heavyarmored_hit/cast_iron_clangs_11_short_norm.ogg",
"static"),
love.audio.newSource(
"sounds/heavyarmored_hit/cast_iron_clangs_18_short_norm.ogg",
"static") }
local snd_rng = love.math.newRandomGenerator( os.time() )
function bricks.new_brick( position, width, height, bricktype, bonustype )
return( { position = position,
width = width or bricks.brick_width,
height = height or bricks.brick_height,
bricktype = bricktype,
quad = bricks.bricktype_to_quad( bricktype ),
bonustype = bonustype } )
end
function bricks.update_brick( single_brick )
end
function bricks.draw_brick( single_brick )
if single_brick.quad then
love.graphics.draw( bricks.image,
single_brick.quad,
single_brick.position.x,
single_brick.position.y )
end
end
function bricks.bricktype_to_quad( bricktype )
if bricktype == nil or bricktype <= 10 then
return nil
end
local row = math.floor( bricktype / 10 )
local col = bricktype % 10
local x_pos = bricks.tile_width * ( col - 1 )
local y_pos = bricks.tile_height * ( row - 1 )
return love.graphics.newQuad( x_pos, y_pos,
bricks.tile_width, bricks.tile_height,
bricks.tileset_width, bricks.tileset_height )
end
function bricks.construct_level( level )
bricks.no_more_bricks = false
for row_index, row in ipairs( level.bricks ) do
for col_index, bricktype in ipairs( row ) do
if bricktype ~= 0 then
local new_brick_position_x = bricks.top_left_position.x +
( col_index - 1 ) *
( bricks.brick_width + bricks.horizontal_distance )
local new_brick_position_y = bricks.top_left_position.y +
( row_index - 1 ) *
( bricks.brick_height + bricks.vertical_distance )
local new_brick_position = vector( new_brick_position_x,
new_brick_position_y )
local bonustype = level.bonuses[ row_index ][ col_index ]
local new_brick = bricks.new_brick( new_brick_position,
bricks.brick_width,
bricks.brick_height,
bricktype,
bonustype )
table.insert( bricks.current_level_bricks, new_brick )
end
end
end
end
function bricks.clear_current_level_bricks()
for i in pairs( bricks.current_level_bricks ) do
bricks.current_level_bricks[i] = nil
end
end
function bricks.update( dt )
local no_more_bricks = true
for _, brick in pairs( bricks.current_level_bricks ) do
if bricks.is_heavyarmored( brick ) then
no_more_bricks = no_more_bricks and true
else
no_more_bricks = no_more_bricks and false
end
end
bricks.no_more_bricks = no_more_bricks
end
function bricks.draw()
for _, brick in pairs( bricks.current_level_bricks ) do
bricks.draw_brick( brick )
end
end
function bricks.brick_hit_by_ball( i, brick, shift_ball, bonuses, score_display )
if bricks.is_simple( brick ) then
bonuses.generate_bonus(
vector( brick.position.x + brick.width / 2,
brick.position.y + brick.height / 2 ),
brick.bonustype )
score_display.add_score_for_simple_brick()
table.remove( bricks.current_level_bricks, i )
local snd = simple_break_sound[ snd_rng:random( #simple_break_sound ) ]
snd:play()
elseif bricks.is_armored( brick ) then
bricks.armored_to_scrathed( brick )
local snd = armored_hit_sound[ snd_rng:random( #armored_hit_sound ) ]
snd:play()
elseif bricks.is_scratched( brick ) then
bricks.scrathed_to_cracked( brick )
local snd = armored_hit_sound[ snd_rng:random( #armored_hit_sound ) ]
snd:play()
elseif bricks.is_cracked( brick ) then
bonuses.generate_bonus(
vector( brick.position.x + brick.width / 2,
brick.position.y + brick.height / 2 ),
brick.bonustype )
score_display.add_score_for_cracked_brick()
table.remove( bricks.current_level_bricks, i )
local snd = armored_break_sound[ snd_rng:random( #armored_break_sound ) ]
snd:play()
elseif bricks.is_heavyarmored( brick ) then
local snd = ball_heavyarmored_sound[ snd_rng:random( #ball_heavyarmored_sound ) ]
snd:play()
end
end
function bricks.is_simple( single_brick )
local row = math.floor( single_brick.bricktype / 10 )
return ( row == 1 )
end
function bricks.is_armored( single_brick )
local row = math.floor( single_brick.bricktype / 10 )
return ( row == 2 )
end
function bricks.is_scratched( single_brick )
local row = math.floor( single_brick.bricktype / 10 )
return ( row == 3 )
end
function bricks.is_cracked( single_brick )
local row = math.floor( single_brick.bricktype / 10 )
return ( row == 4 )
end
function bricks.is_heavyarmored( single_brick )
local row = math.floor( single_brick.bricktype / 10 )
return ( row == 5 )
end
function bricks.armored_to_scrathed( single_brick )
single_brick.bricktype = single_brick.bricktype + 10
single_brick.quad = bricks.bricktype_to_quad( single_brick.bricktype )
end
function bricks.scrathed_to_cracked( single_brick )
single_brick.bricktype = single_brick.bricktype + 10
single_brick.quad = bricks.bricktype_to_quad( single_brick.bricktype )
end
return bricks
| mit |
ffxiphoenix/darkstar | scripts/globals/items/hellsteak.lua | 35 | 1725 | -----------------------------------------
-- ID: 5609
-- Item: hellsteak
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 20
-- Strength 6
-- Intelligence -2
-- Health Regen While Healing 2
-- Attack % 19
-- Ranged ATT % 19
-- Dragon Killer 5
-- Demon Killer 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,10800,5609);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_STR, 6);
target:addMod(MOD_INT, -2);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_ATTP, 19);
target:addMod(MOD_RATTP, 19);
target:addMod(MOD_DRAGON_KILLER, 5);
target:addMod(MOD_DEMON_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_STR, 6);
target:delMod(MOD_INT, -2);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_ATTP, 19);
target:delMod(MOD_RATTP, 19);
target:delMod(MOD_DRAGON_KILLER, 5);
target:delMod(MOD_DEMON_KILLER, 5);
end;
| gpl-3.0 |
ktf/apt-rpm | contrib/guess/guess.lua | 3 | 1450 | -- This script will try to change the requested names in a few
-- ways, trying to guess an available package. It must be plugged
-- in the slot Scripts::AptGet::Install::TranslateArg
--
-- Author: Gustavo Niemeyer <niemeyer@conectiva.com>
-- Allow someone to disable this without removing the script.
if confget("APT::Get::Guess/b", "true") == "false" then
return
end
-- Don't fiddle with filenames.
if string.sub(argument, 1, 1) == "/" then
return
end
-- First, check for something with a 'lib' prefix
name = "lib"..argument
if pkgfind(name) then
translated = name
return
end
-- Now check for something with a number 0-99 suffix ...
for n = 0, 99 do
name = argument..n
if pkgfind(name) then
translated = name
return
end
-- ... and a lib prefix.
name = "lib"..argument
if pkgfind(name) then
translated = name
return
end
end
-- Now go through the package list doing the same tests with a
-- normalized case.
lower = string.lower(argument)
liblower = "lib"..lower
for i, pkg in pairs(pkglist()) do
realname = pkgname(pkg)
name = string.lower(realname)
if lower == name or liblower == name then
translated = realname
return
end
-- But instead of trying every possible number suffix,
-- extract the numbers from the real package name.
while string.gfind(string.sub(name, -1), "[%d.]")() do
name = string.sub(name, 1, -2)
if (lower == name or liblower == name) then
translated = realname
return
end
end
end
| gpl-2.0 |
DrayChou/telegram-bot | plugins/giphy.lua | 1 | 1820 | -- Idea by https://github.com/asdofindia/telegram-bot/
-- See http://api.giphy.com/
do
local BASE_URL = 'http://api.giphy.com/v1'
local API_KEY = 'dc6zaTOxFJmzC' -- public beta key
local function get_image(response)
local images = json:decode(response).data
if #images == 0 then return nil end -- No images
local i = math.random(#images)
local image = images[i] -- A random one
if image.images.downsized then
return image.images.downsized.url
end
if image.images.original then
return image.original.url
end
return nil
end
local function get_random_top()
local url = BASE_URL.."/gifs/trending?api_key="..API_KEY
local response, code = http.request(url)
if code ~= 200 then return nil end
return get_image(response)
end
local function search(text)
text = URL.escape(text)
local url = BASE_URL.."/gifs/search?q="..text.."&api_key="..API_KEY
local response, code = http.request(url)
if code ~= 200 then return nil end
return get_image(response)
end
local function run(msg, matches)
local gif_url = nil
-- If no search data, a random trending GIF will be sent
if matches[1] == "!gif" or matches[1] == "!giphy" then
gif_url = get_random_top()
else
gif_url = search(matches[1])
end
if not gif_url then
return "Error: GIF not found"
end
local receiver = get_receiver(msg)
print("GIF URL"..gif_url)
send_document_from_url(receiver, gif_url)
end
return {
description = "GIFs from telegram with Giphy API",
usage = {
"!gif (term): Search and sends GIF from Giphy. If no param, sends a trending GIF.",
"!giphy (term): Search and sends GIF from Giphy. If no param, sends a trending GIF."
},
patterns = {
"^[!|#|/]gif$",
"^[!|#|/]gif (.*)",
"^[!|#|/]giphy (.*)",
"^[!|#|/]giphy$"
},
run = run
}
end
| gpl-2.0 |
kondrak/ProDBG | units.libs.lua | 2 | 11522 | require "tundra.syntax.glob"
require "tundra.syntax.osx-bundle"
require "tundra.path"
require "tundra.util"
-----------------------------------------------------------------------------------------------------------------------
----------------------------------------------- EXTERNAL LIBS ---------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "stb",
Env = {
CCOPTS = {
{
-- "-Werror",
"-Wno-parentheses",
"-Wno-unused-variable",
"-Wno-pointer-to-int-cast",
"-Wno-int-to-pointer-cast",
"-Wno-unused-but-set-variable",
"-Wno-return-type",
"-Wno-unused-function",
"-Wno-error=strict-aliasing" ; Config = "linux-*-*" },
{ "-Wno-everything"; Config = "macosx-*-*" },
{ "/wd4244", "/wd4267", "/wd4133", "/wd4047", "/wd4204", "/wd4201", "/wd4701", "/wd4703",
"/wd4024", "/wd4100", "/wd4053", "/wd4431",
"/wd4189", "/wd4127"; Config = "win64-*-*" },
},
},
Sources = {
Glob {
Dir = "src/native/external/stb",
Extensions = { ".c", ".h" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "tinyxml2",
Env = {
CXXOPTS = {
{ "-Wno-everything"; Config = "macosx-*-*" },
{ "/wd4267", "/wd4706", "/wd4244", "/wd4701", "/wd4334", "/wd4127"; Config = "win64-*-*" },
},
},
Sources = {
Glob {
Dir = "src/native/external/tinyxml2",
Extensions = { ".cpp", ".h" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "lua",
Env = {
CPPPATH = {
"src/native/external/lua/src",
},
CCOPTS = {
{ "-Wno-everything"; Config = "macosx-*-*" },
{ "/wd4267", "/wd4706", "/wd4244", "/wd4701", "/wd4334", "/wd4127"; Config = "win64-*-*" },
},
},
Sources = {
Glob {
Dir = "src/native/external/lua/src",
Extensions = { ".c", ".h", ".hpp" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "scintilla",
Env = {
CPPPATH = {
"src/native/external/scintilla/include",
"src/native/external/scintilla/src/lexlib",
},
CXXOPTS = {
{ "-DSCI_LEXER", "-Wno-everything", "-Wno-missing-braces" ; Config = { "macosx-*-*", "macosx_test-*" } },
{ "-DGTK -DSCI_LEXER", "-Wno-everything", "-Wno-missing-braces" ; Config = { "linux-*-*" } },
{ "/DSCI_LEXER", "/wd4267", "/wd4706", "/wd4244", "/wd4701", "/wd4334", "/wd4127"; Config = "win64-*-*" },
},
},
Sources = {
Glob {
Dir = "src/native/external/scintilla/src",
Extensions = { ".cxx", ".h" },
},
Recursive = true,
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "bgfx_native",
Env = {
CPPPATH = {
{
{ "src/native/external/bx/include/compat/msvc",
"src/native/external/bgfx/3rdparty/dxsdk/include" } ; Config = "win64-*-*" },
{ "src/native/external/bx/include/compat/osx" ; Config = "macosx-*-*" },
"src/native/external/remotery/lib",
"src/native/external/bgfx/include",
"src/native/external/bx/include",
"src/native/external/bgfx/3rdparty/khronos",
},
CXXOPTS = {
{ "-Wno-variadic-macros", "-Wno-everything" ; Config = "macosx-*-*" },
{ "/Isrc/native/external/bx/include/compat/msvc",
"/EHsc"; Config = "win64-*-*" },
},
},
Sources = {
{ "src/native/external/bgfx/src/bgfx.cpp",
"src/native/external/bgfx/src/image.cpp",
"src/native/external/bgfx/src/vertexdecl.cpp",
"src/native/external/bgfx/src/debug_renderdoc.cpp",
"src/native/external/bgfx/src/topology.cpp",
"src/native/external/bgfx/src/shader_dxbc.cpp",
"src/native/external/bgfx/src/renderer_gl.cpp",
"src/native/external/bgfx/src/renderer_vk.cpp",
"src/native/external/bgfx/src/renderer_null.cpp",
"src/native/external/bgfx/src/renderer_d3d9.cpp",
"src/native/external/bgfx/src/renderer_d3d11.cpp",
"src/native/external/bgfx/src/renderer_d3d12.cpp" },
{ "src/native/external/bgfx/src/renderer_mtl.mm" ; Config = { "macosx-*-*", "macosx_test-*" } },
{ "src/native/external/bgfx/src/glcontext_wgl.cpp" ; Config = "win64-*-*" },
{ "src/native/external/bgfx/src/glcontext_glx.cpp" ; Config = "linux-*-*" },
{ "src/native/external/bgfx/src/glcontext_nsgl.mm" ; Config = { "macosx-*-*", "macosx_test-*" } },
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "imgui",
Env = {
CPPDEFS = { "IMGUI_INCLUDE_IMGUI_USER_H" },
CXXOPTS = {
{ "-Wno-everything"; Config = "macosx-*-*" },
},
CPPPATH = {
"src/native/external/scintilla/include",
"src/native/ui",
},
},
Sources = {
Glob {
Dir = "src/native/external/imgui",
Extensions = { ".cpp", ".h" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "remote_api",
Env = {
CPPPATH = { "api/include" },
CCOPTS = {
"-Wno-visibility",
"-Wno-conversion",
"-Wno-pedantic",
"-Wno-conversion",
"-Wno-covered-switch-default",
"-Wno-unreachable-code",
"-Wno-bad-function-cast",
"-Wno-missing-field-initializers",
"-Wno-float-equal",
"-Wno-conversion",
"-Wno-switch-enum",
"-Wno-format-nonliteral"; Config = "macosx-*-*"
},
},
Sources = {
Glob {
Dir = "api/src/remote",
Extensions = { ".c" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "Libs" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "remote_connection",
Env = {
CPPPATH = { "api/include" },
CCOPTS = {
"-Wno-visibility",
"-Wno-conversion",
"-Wno-pedantic",
"-Wno-conversion",
"-Wno-covered-switch-default",
"-Wno-unreachable-code",
"-Wno-bad-function-cast",
"-Wno-missing-field-initializers",
"-Wno-float-equal",
"-Wno-conversion",
"-Wno-switch-enum",
"-Wno-format-nonliteral"; Config = "macosx-*-*"
},
},
Sources = {
"api/src/remote/remote_connection.c",
},
IdeGenerationHints = { Msvc = { SolutionFolder = "Libs" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "capstone",
Env = {
CPPPATH = {
"src/native/external/capstone/include",
},
CCOPTS = {
{ "-Wno-everything"; Config = "macosx-*-*" },
{ "/wd4267", "/wd4706", "/wd4244", "/wd4701", "/wd4334", "/wd4127"; Config = "win64-*-*" },
},
CPPDEFS = {
{ "CAPSTONE_ARM64_SUPPORT", "CAPSTONE_ARM_SUPPORT", "CAPSTONE_HAS_ARM", "CAPSTONE_HAS_ARM64", "CAPSTONE_HAS_M68K", "CAPSTONE_HAS_MIPS",
"CAPSTONE_HAS_POWERPC", "CAPSTONE_HAS_SPARC", "CAPSTONE_HAS_SYSZ", "CAPSTONE_HAS_X86", "CAPSTONE_HAS_XCORE", "CAPSTONE_M68K_SUPPORT",
"CAPSTONE_MIPS_SUPPORT", "CAPSTONE_PPC_SUPPORT", "CAPSTONE_SPARC_SUPPORT", "CAPSTONE_SYSZ_SUPPORT", "CAPSTONE_USE_SYS_DYN_MEM",
"CAPSTONE_X86_SUPPORT", "CAPSTONE_XCORE_SUPPORT" },
},
},
Sources = {
Glob {
Dir = "src/native/external/capstone",
Extensions = { ".h", ".c" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "Libs" } },
}
-----------------------------------------------------------------------------------------------------------------------
----------------------------------------------- INTERNAL LIBS ---------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "ui",
Env = {
CPPDEFS = { "IMGUI_INCLUDE_IMGUI_USER_H" },
CCOPTS = {
{ "-Wno-objc-interface-ivars",
"-Wno-direct-ivar-access",
"-Wno-nullable-to-nonnull-conversion",
"-Wno-format-nonliteral"; Config = "macosx-*-*" },
},
CXXOPTS = {
{
"-Wno-gnu-anonymous-struct",
"-Wno-global-constructors",
"-Wno-switch-enum",
"-Wno-nested-anon-types",
"-Wno-float-equal",
"-Wno-cast-align",
"-Wno-everything",
"-Wno-exit-time-destructors",
"-Wno-format-nonliteral"; Config = "macosx-*-*" },
},
CPPPATH = {
"src/native/ui",
"src/native/external",
"src/native/external/imgui",
"src/native/external/bx/include",
"src/native/external/bgfx/include",
"api/include",
"src/native/external/stb",
"src/prodbg",
"third-party/include",
},
},
Sources = {
FGlob {
Dir = "src/native/ui",
Extensions = { ".c", ".cpp", ".m", ".mm", ".h", "*.inl" },
Filters = {
{ Pattern = "mac"; Config = { "macosx-*-*", "macosx_test-*" } },
{ Pattern = "windows"; Config = "win64-*-*" },
{ Pattern = "linux"; Config = "linux-*-*" },
},
Recursive = true,
},
ShadercFS { Source = "data/shaders/imgui/fs_imgui.sc" },
ShadercVS { Source = "data/shaders/imgui/vs_imgui.sc" },
ShadercFS { Source = "data/shaders/ui_pos_color/fs_pos_color.sc" },
ShadercVS { Source = "data/shaders/ui_pos_color/vs_pos_color.sc" },
ShadercFS { Source = "data/shaders/ui_pos_tex_r_color/fs_pos_tex_r_color.sc" },
ShadercVS { Source = "data/shaders/ui_pos_tex_r_color/vs_pos_tex_r_color.sc" },
-- autogenerated files
ApiGen { Source = "src/tools/api_gen/pd_ui.json", Lang="-cpp", OutName = "api/include/pd_ui_autogen.h", LangCfg="src/tools/api_gen/cpp.json" },
ApiGen { Source = "src/tools/api_gen/pd_ui.json", Lang="-rs", OutName = "api/rust/prodbg/src/ui_ffi_autogen.rs", LangCfg="src/tools/api_gen/rust.json" },
},
IdeGenerationHints = { Msvc = { SolutionFolder = "Libs" } },
}
-- vim: ts=4:sw=4:sts=4
| mit |
ffxiphoenix/darkstar | scripts/globals/spells/bluemagic/warm-up.lua | 17 | 1973 | -----------------------------------------
-- Spell: Warm-Up
-- Enhances accuracy and evasion
-- Spell cost: 59 MP
-- Monster Type: Beastmen
-- Spell Type: Magical (Earth)
-- Blue Magic Points: 4
-- Stat Bonus: VIT+1
-- Level: 68
-- Casting Time: 7 seconds
-- Recast Time: 120 seconds
-- Duration: 180 seconds
--
-- Combos: Clear Mind
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local typeEffectOne = EFFECT_ACCURACY_BOOST
local typeEffectTwo = EFFECT_EVASION_BOOST
local power = 10;
local duration = 180;
local returnEffect = typeEffectOne;
if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then
local diffMerit = caster:getMerit(MERIT_DIFFUSION);
if (diffMerit > 0) then
duration = duration + (duration/100)* diffMerit;
end;
caster:delStatusEffect(EFFECT_DIFFUSION);
end;
if (target:addStatusEffect(typeEffectOne,power,0,duration) == false and target:addStatusEffect(typeEffectTwo,power,0,duration) == false) then -- both statuses fail to apply
spell:setMsg(75);
elseif (target:addStatusEffect(typeEffectOne,power,0,duration) == false) then -- the first status fails to apply
target:addStatusEffect(typeEffectTwo,power,0,duration)
spell:setMsg(230);
returnEffect = typeEffectTwo;
else
target:addStatusEffect(typeEffectOne,power,0,duration)
target:addStatusEffect(typeEffectTwo,power,0,duration)
spell:setMsg(230);
end;
return returnEffect;
end; | gpl-3.0 |
azekillDIABLO/Voxellar | mods/NODES/xpanes/init.lua | 3 | 4717 |
local function is_pane(pos)
return minetest.get_item_group(minetest.get_node(pos).name, "pane") > 0
end
local function connects_dir(pos, name, dir)
local aside = vector.add(pos, minetest.facedir_to_dir(dir))
if is_pane(aside) then
return true
end
local connects_to = minetest.registered_nodes[name].connects_to
if not connects_to then
return false
end
local list = minetest.find_nodes_in_area(aside, aside, connects_to)
if #list > 0 then
return true
end
return false
end
local function swap(pos, node, name, param2)
if node.name == name and node.param2 == param2 then
return
end
minetest.set_node(pos, {name = name, param2 = param2})
end
local function update_pane(pos)
if not is_pane(pos) then
return
end
local node = minetest.get_node(pos)
local name = node.name
if name:sub(-5) == "_flat" then
name = name:sub(1, -6)
end
local any = node.param2
local c = {}
local count = 0
for dir = 0, 3 do
c[dir] = connects_dir(pos, name, dir)
if c[dir] then
any = dir
count = count + 1
end
end
if count == 0 then
swap(pos, node, name .. "_flat", any)
elseif count == 1 then
swap(pos, node, name .. "_flat", (any + 1) % 4)
elseif count == 2 then
if (c[0] and c[2]) or (c[1] and c[3]) then
swap(pos, node, name .. "_flat", (any + 1) % 4)
else
swap(pos, node, name, 0)
end
else
swap(pos, node, name, 0)
end
end
minetest.register_on_placenode(function(pos, node)
if minetest.get_item_group(node, "pane") then
update_pane(pos)
end
for i = 0, 3 do
local dir = minetest.facedir_to_dir(i)
update_pane(vector.add(pos, dir))
end
end)
minetest.register_on_dignode(function(pos)
for i = 0, 3 do
local dir = minetest.facedir_to_dir(i)
update_pane(vector.add(pos, dir))
end
end)
xpanes = {}
function xpanes.register_pane(name, def)
for i = 1, 15 do
minetest.register_alias("xpanes:" .. name .. "_" .. i, "xpanes:" .. name .. "_flat")
end
local flatgroups = table.copy(def.groups)
flatgroups.pane = 1
minetest.register_node(":xpanes:" .. name .. "_flat", {
description = def.description,
drawtype = "nodebox",
paramtype = "light",
is_ground_content = false,
sunlight_propagates = true,
inventory_image = def.inventory_image,
wield_image = def.wield_image,
paramtype2 = "facedir",
tiles = {def.textures[3], def.textures[3], def.textures[1]},
groups = flatgroups,
drop = "xpanes:" .. name .. "_flat",
sounds = def.sounds,
node_box = {
type = "fixed",
fixed = {{-1/2, -1/2, -1/32, 1/2, 1/2, 1/32}},
},
selection_box = {
type = "fixed",
fixed = {{-1/2, -1/2, -1/32, 1/2, 1/2, 1/32}},
},
connect_sides = { "left", "right" },
})
local groups = table.copy(def.groups)
groups.pane = 1
groups.not_in_creative_inventory = 1
minetest.register_node(":xpanes:" .. name, {
drawtype = "nodebox",
paramtype = "light",
is_ground_content = false,
sunlight_propagates = true,
description = def.description,
tiles = {def.textures[3], def.textures[3], def.textures[1]},
groups = groups,
drop = "xpanes:" .. name .. "_flat",
sounds = def.sounds,
node_box = {
type = "connected",
fixed = {{-1/32, -1/2, -1/32, 1/32, 1/2, 1/32}},
connect_front = {{-1/32, -1/2, -1/2, 1/32, 1/2, -1/32}},
connect_left = {{-1/2, -1/2, -1/32, -1/32, 1/2, 1/32}},
connect_back = {{-1/32, -1/2, 1/32, 1/32, 1/2, 1/2}},
connect_right = {{1/32, -1/2, -1/32, 1/2, 1/2, 1/32}},
},
connects_to = {"group:pane", "group:stone", "group:glass", "group:wood", "group:tree"},
})
minetest.register_craft({
output = "xpanes:" .. name .. "_flat 16",
recipe = def.recipe
})
end
xpanes.register_pane("pane", {
description = "Glass Pane",
textures = {"default_glass.png","xpanes_pane_half.png","xpanes_white.png"},
inventory_image = "default_glass.png",
wield_image = "default_glass.png",
sounds = default.node_sound_glass_defaults(),
groups = {snappy=2, cracky=3, oddly_breakable_by_hand=3},
recipe = {
{"default:glass", "default:glass", "default:glass"},
{"default:glass", "default:glass", "default:glass"}
}
})
xpanes.register_pane("bar", {
description = "Iron Bar",
textures = {"xpanes_bar.png","xpanes_bar.png","xpanes_bar_top.png"},
inventory_image = "xpanes_bar.png",
wield_image = "xpanes_bar.png",
groups = {cracky=2},
sounds = default.node_sound_metal_defaults(),
recipe = {
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"},
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"}
}
})
minetest.register_lbm({
name = "xpanes:gen2",
nodenames = {"group:pane"},
action = function(pos, node)
update_pane(pos)
for i = 0, 3 do
local dir = minetest.facedir_to_dir(i)
update_pane(vector.add(pos, dir))
end
end
})
| lgpl-2.1 |
ffxiphoenix/darkstar | scripts/zones/Kuftal_Tunnel/Zone.lua | 17 | 2256 | -----------------------------------
--
-- Zone: Kuftal_Tunnel (174)
--
-----------------------------------
package.loaded["scripts/zones/Kuftal_Tunnel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Kuftal_Tunnel/TextIDs");
require("scripts/globals/weather");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17490321,17490322,17490323,17490324};
SetGroundsTome(tomes);
-- Guivre
SetRespawnTime(17490234, 900, 10800);
UpdateTreasureSpawnPoint(17490300);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(20.37,-21.104,275.782,46);
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;
-----------------------------------
-- onZoneWeatherChange
-----------------------------------
function onZoneWeatherChange(weather)
if (weather == WEATHER_WIND or weather == WEATHER_GALES) then
GetNPCByID(17490280):setAnimation(9); -- Rock Up
else
GetNPCByID(17490280):setAnimation(8); -- Rock Down
end
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Port_Bastok/npcs/Bagnobrok.lua | 36 | 1585 | -----------------------------------
-- Area: Port Bastok
-- NPC: Bagnobrok
-- Only sells when Bastok controls Movalpolos
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
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)
RegionOwner = GetRegionOwner(MOVALPOLOS);
if (RegionOwner ~= BASTOK) then
player:showText(npc,BAGNOBROK_CLOSED_DIALOG);
else
player:showText(npc,BAGNOBROK_OPEN_DIALOG);
stock = {
0x0280, 11, --Copper Ore
0x1162, 694, --Coral Fungus
0x1117, 4032, --Danceshroom
0x0672, 6500, --Kopparnickel Ore
0x142D, 736 --Movalpolos Water
}
showShop(player,BASTOK,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/spells/cure_iii.lua | 18 | 3838 | -----------------------------------------
-- Spell: Cure III
-- Restores target's HP.
-- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local divisor = 0;
local constant = 0;
local basepower = 0;
local power = 0;
local basecure = 0;
local final = 0;
local minCure = 130;
if (USE_OLD_CURE_FORMULA == true) then
power = getCurePowerOld(caster);
rate = 1;
constant = 70;
if (power > 300) then
rate = 15.6666;
constant = 180.43;
elseif (power > 180) then
rate = 2;
constant = 115;
end
else
power = getCurePower(caster);
if (power < 125) then
divisor = 2.2
constant = 130;
basepower = 70;
elseif (power < 200) then
divisor = 75/65;
constant = 155;
basepower = 125;
elseif (power < 300) then
divisor = 2.5;
constant = 220;
basepower = 200;
elseif (power < 700) then
divisor = 5;
constant = 260;
basepower = 300;
else
divisor = 999999;
constant = 340;
basepower = 0;
end
end
if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then
if (USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCure(power,divisor,constant);
else
basecure = getBaseCure(power,divisor,constant,basepower);
end
final = getCureFinal(caster,spell,basecure,minCure,false);
if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then
local solaceStoneskin = 0;
local equippedBody = caster:getEquipID(SLOT_BODY);
if (equippedBody == 11186) then
solaceStoneskin = math.floor(final * 0.30);
elseif (equippedBody == 11086) then
solaceStoneskin = math.floor(final * 0.35);
else
solaceStoneskin = math.floor(final * 0.25);
end
target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25);
end;
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
--Applying server mods....
final = final * CURE_POWER;
local diff = (target:getMaxHP() - target:getHP());
if (final > diff) then
final = diff;
end
target:addHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
else
if (target:isUndead()) then
spell:setMsg(2);
local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5;
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0);
dmg = dmg*resist;
dmg = addBonuses(caster,spell,target,dmg);
dmg = adjustForTarget(target,dmg,spell:getElement());
dmg = finalMagicAdjustments(caster,target,spell,dmg);
final = dmg;
target:delHP(final);
target:updateEnmityFromDamage(caster,final);
elseif (caster:getObjType() == TYPE_PC) then
spell:setMsg(75);
else
-- e.g. monsters healing themselves.
if (USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCureOld(power,divisor,constant);
else
basecure = getBaseCure(power,divisor,constant,basepower);
end
final = getCureFinal(caster,spell,basecure,minCure,false);
local diff = (target:getMaxHP() - target:getHP());
if (final > diff) then
final = diff;
end
target:addHP(final);
end
end
return final;
end; | gpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/weaponskills/swift_blade.lua | 30 | 1389 | -----------------------------------
-- Swift Blade
-- Sword weapon skill
-- Skill Level: 225
-- Delivers a three-hit attack. params.accuracy varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Shadow Gorget & Soil Gorget.
-- Aligned with the Shadow Belt & Soil Belt.
-- Element: None
-- Modifiers: STR:50% ; MND:50%
-- 100%TP 200%TP 300%TP
-- 1.50 1.50 1.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 3;
params.ftp100 = 1.5; params.ftp200 = 1.5; params.ftp300 = 1.5;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.5; params.mnd_wsc = 0.5;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
ffxiphoenix/darkstar | scripts/zones/Castle_Oztroja/npcs/_47m.lua | 17 | 1571 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47m (Torch Stand)
-- Notes: Opens door _471 near password #3
-- @pos -45.230 -17.832 17.668 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 4;
local DoorA = GetNPCByID(DoorID):getAnimation();
local TorchStandA = npc:getAnimation();
local Torch2 = npc:getID();
local Torch1 = npc:getID() - 1;
if (DoorA == 9 and TorchStandA == 9) then
player:startEvent(0x000a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
local Torch2 = GetNPCByID(17396174):getID();
local Torch1 = GetNPCByID(Torch2):getID() - 1;
local DoorID = GetNPCByID(Torch2):getID() - 4;
if (option == 1) then
GetNPCByID(Torch1):openDoor(10); -- Torch Lighting
GetNPCByID(Torch2):openDoor(10); -- Torch Lighting
GetNPCByID(DoorID):openDoor(6);
end
end;
--printf("CSID: %u",csid);
--printf("RESULT: %u",option); | gpl-3.0 |
DrayChou/telegram-bot | plugins/minecraft.lua | 1 | 2623 | local usage = {
"!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565",
"!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.",
}
local ltn12 = require "ltn12"
local function mineSearch(ip, port, receiver) --25565
local responseText = ""
local api = "https://api.syfaro.net/server/status"
local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true"
local http = require("socket.http")
local respbody = {}
local body, code, headers, status = http.request{
url = api..parameters,
method = "GET",
redirect = true,
sink = ltn12.sink.table(respbody)
}
local body = table.concat(respbody)
if (status == nil) then return "ERROR: status = nil" end
if code ~=200 then return "ERROR: "..code..". Status: "..status end
local jsonData = json:decode(body)
responseText = responseText..ip..":"..port.." ->\n"
if (jsonData.motd ~= nil) then
local tempMotd = ""
tempMotd = jsonData.motd:gsub('%§.', '')
if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end
end
if (jsonData.online ~= nil) then
responseText = responseText.." Online: "..tostring(jsonData.online).."\n"
end
if (jsonData.players ~= nil) then
if (jsonData.players.max ~= nil) then
responseText = responseText.." Max Players: "..jsonData.players.max.."\n"
end
if (jsonData.players.now ~= nil) then
responseText = responseText.." Players online: "..jsonData.players.now.."\n"
end
if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then
responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n"
end
end
if (jsonData.favicon ~= nil and false) then
--send_photo(receiver, jsonData.favicon) --(decode base64 and send)
end
return responseText
end
local function parseText(chat, text)
if (text == nil or text == "!mine") then
return usage
end
ip, port = string.match(text, "^[!|#|/]mine (.-) (.*)$")
if (ip ~= nil and port ~= nil) then
return mineSearch(ip, port, chat)
end
local ip = string.match(text, "^[!|#|/]mine (.*)$")
if (ip ~= nil) then
return mineSearch(ip, "25565", chat)
end
return "ERROR: no input ip?"
end
local function run(msg, matches)
local chat_id = tostring(msg.to.id)
local result = parseText(chat_id, msg.text)
return result
end
return {
description = "Searches Minecraft server and sends info",
usage = usage,
patterns = {
"^[!|#|/]mine (.*)$"
},
run = run
} | gpl-2.0 |
dail8859/ScintilluaPlusPlus | ext/scintillua/lexers/gnuplot.lua | 5 | 3144 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Gnuplot LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'gnuplot'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- Strings.
local sq_str = l.delimited_range("'")
local dq_str = l.delimited_range('"')
local bk_str = l.delimited_range('[]', true)
local bc_str = l.delimited_range('{}', true)
local string = token(l.STRING, sq_str + dq_str + bk_str + bc_str)
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'cd', 'call', 'clear', 'exit', 'fit', 'help', 'history', 'if', 'load',
'pause', 'plot', 'using', 'with', 'index', 'every', 'smooth', 'thru', 'print',
'pwd', 'quit', 'replot', 'reread', 'reset', 'save', 'set', 'show', 'unset',
'shell', 'splot', 'system', 'test', 'unset', 'update'
})
-- Functions.
local func = token(l.FUNCTION, word_match{
'abs', 'acos', 'acosh', 'arg', 'asin', 'asinh', 'atan', 'atan2', 'atanh',
'besj0', 'besj1', 'besy0', 'besy1', 'ceil', 'cos', 'cosh', 'erf', 'erfc',
'exp', 'floor', 'gamma', 'ibeta', 'inverf', 'igamma', 'imag', 'invnorm',
'int', 'lambertw', 'lgamma', 'log', 'log10', 'norm', 'rand', 'real', 'sgn',
'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'column', 'defined', 'tm_hour',
'tm_mday', 'tm_min', 'tm_mon', 'tm_sec', 'tm_wday', 'tm_yday', 'tm_year',
'valid'
})
-- Variables.
local variable = token(l.VARIABLE, word_match{
'angles', 'arrow', 'autoscale', 'bars', 'bmargin', 'border', 'boxwidth',
'clabel', 'clip', 'cntrparam', 'colorbox', 'contour', 'datafile ',
'decimalsign', 'dgrid3d', 'dummy', 'encoding', 'fit', 'fontpath', 'format',
'functions', 'function', 'grid', 'hidden3d', 'historysize', 'isosamples',
'key', 'label', 'lmargin', 'loadpath', 'locale', 'logscale', 'mapping',
'margin', 'mouse', 'multiplot', 'mx2tics', 'mxtics', 'my2tics', 'mytics',
'mztics', 'offsets', 'origin', 'output', 'parametric', 'plot', 'pm3d',
'palette', 'pointsize', 'polar', 'print', 'rmargin', 'rrange', 'samples',
'size', 'style', 'surface', 'terminal', 'tics', 'ticslevel', 'ticscale',
'timestamp', 'timefmt', 'title', 'tmargin', 'trange', 'urange', 'variables',
'version', 'view', 'vrange', 'x2data', 'x2dtics', 'x2label', 'x2mtics',
'x2range', 'x2tics', 'x2zeroaxis', 'xdata', 'xdtics', 'xlabel', 'xmtics',
'xrange', 'xtics', 'xzeroaxis', 'y2data', 'y2dtics', 'y2label', 'y2mtics',
'y2range', 'y2tics', 'y2zeroaxis', 'ydata', 'ydtics', 'ylabel', 'ymtics',
'yrange', 'ytics', 'yzeroaxis', 'zdata', 'zdtics', 'cbdata', 'cbdtics',
'zero', 'zeroaxis', 'zlabel', 'zmtics', 'zrange', 'ztics', 'cblabel',
'cbmtics', 'cbrange', 'cbtics'
})
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Operators.
local operator = token(l.OPERATOR, S('-+~!$*%=<>&|^?:()'))
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'function', func},
{'variable', variable},
{'identifier', identifier},
{'string', string},
{'comment', comment},
{'operator', operator},
}
return M
| gpl-2.0 |
RockySeven3161/POWERNEW | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
Quenty/NevermoreEngine | src/applytagtotaggedchildren/src/Shared/ApplyTagToTaggedChildren.lua | 1 | 2609 | --[=[
Class that while constructed apply a tag to any children of the parent it is given, assuming that
class has the required tag.
This lets you bridge tag systems since CollectionService is used as an interop model between many
components in scripts.
@class ApplyTagToTaggedChildren
]=]
local require = require(script.Parent.loader).load(script)
local CollectionService = game:GetService("CollectionService")
local BaseObject = require("BaseObject")
local ApplyTagToTaggedChildren = setmetatable({}, BaseObject)
ApplyTagToTaggedChildren.ClassName = "ApplyTagToTaggedChildren"
ApplyTagToTaggedChildren.__index = ApplyTagToTaggedChildren
--[=[
Creates a new ApplyTagToTaggedChildren.
@param parent Instance
@param tag string
@param requiredTag string
@return ApplyTagToTaggedChildren
]=]
function ApplyTagToTaggedChildren.new(parent, tag, requiredTag)
local self = setmetatable(BaseObject.new(), ApplyTagToTaggedChildren)
self._parent = parent or error("No parent")
self._requiredTag = requiredTag or error("No requiredTag")
self._tag = tag or error("No tag")
assert(self._requiredTag ~= self._tag, "Bad requiredTag")
self._tagged = {}
self._maid:GiveTask(function()
for tagged, _ in pairs(self._tagged) do
CollectionService:RemoveTag(tagged, self._tag)
end
end)
self:_setup()
return self
end
function ApplyTagToTaggedChildren:_setup()
self._maid:GiveTask(self._parent.ChildAdded:Connect(function(...)
self:_handleChildAdded(...)
end))
self._maid:GiveTask(self._parent.ChildRemoved:Connect(function(...)
self:_removeTagIfTagged(...)
end))
self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(self._requiredTag)
:Connect(function(...)
self:_handleRequiredTagAddedToAnyInstance(...)
end))
self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(self._requiredTag)
:Connect(function(...)
self:_removeTagIfTagged(...)
end))
for _, child in pairs(self._parent:GetChildren()) do
self:_handleChildAdded(child)
end
end
function ApplyTagToTaggedChildren:_handleRequiredTagAddedToAnyInstance(child)
if child.Parent == self._parent then
self._tagged[child] = true
CollectionService:AddTag(child, self._tag)
end
end
function ApplyTagToTaggedChildren:_handleChildAdded(child)
if CollectionService:HasTag(child, self._requiredTag) then
self._tagged[child] = true
CollectionService:AddTag(child, self._tag)
end
end
function ApplyTagToTaggedChildren:_removeTagIfTagged(child)
if self._tagged[child] then
self._tagged[child] = nil
CollectionService:RemoveTag(child, self._tag)
end
end
return ApplyTagToTaggedChildren | mit |
AfuSensi/Mr.Green-MTA-Resources | resources/[maps]/Puma-Markers/Puma-Markers.lua | 4 | 23818 | gMe = getLocalPlayer()
gRoot = getRootElement()
screenWidth, screenHeight = guiGetScreenSize()
-- setTimer(function() StartRes() end,100,1)
function StartRes()
oldHittedCollShape = nil
MarkerTypes = {"Teleport","TeleportD","SlowDown","SpeedUp","Stop","Fire","BlowUp","Jump","Flip","Reverse","Rotate","CarsFly","CarsSwim","Gravity","Magnet","Beer","Camera","FlatTires","Freeze","GameSpeed","Color","Weather","Time","Text","AntiSC"}
isSelected = {}
isDestroyed = {}
FM = 0
SM = 0
MW = 0
TeleporterData = {}
addEventHandler ( "onClientRender", gRoot,EditorRender)
addEventHandler ( "onClientPlayerWasted", gMe, wasted )
addEventHandler ( "onClientPlayerVehicleExit", gMe, wasted )
addEvent("onClientElementSelect",true)
addEvent("onClientElementDrop",true)
addEvent("onClientElementDestroyed",true)
addEventHandler ( "onClientElementSelect", gRoot,onClientElementSelect)
addEventHandler ( "onClientElementDrop", gRoot,onClientElementDrop)
addEventHandler ( "onClientElementDestroyed", gRoot,onClientElementDestroyed)
setTimer(outputChatBox, 1000, 1, "ՠPuma-Markers (2.2) MrGreen Activated! Պ", 0,0,255)
end
addEventHandler( "onClientResourceStart", resourceRoot,StartRes)
-------------------------------- [ EDITOR ACTIONS ] --------------------------------
function onClientElementSelect()
for MT=1,#MarkerTypes do
if getElementType(getElementParent(source)) == MarkerTypes[MT] then
isSelected[getElementParent(source)] = true
elseif getElementType(source) == MarkerTypes[MT] then
isSelected[source] = true
end
end
end
function onClientElementDrop()
for MT=1,#MarkerTypes do
if getElementType(source) == MarkerTypes[MT] then
isSelected[source] = false
if MT ~= 2 then
lastSelected = source
end
if MT == 2 then
if lastSelected and getElementType(lastSelected) == "Teleport" then
setElementData(lastSelected,"destination",getElementID(source))
end
end
end
end
end
function onClientElementDestroyed()
for MT=1,#MarkerTypes do
if getElementType(source) == MarkerTypes[MT] then
isDestroyed[source] = true
end
end
end
-------------------------------- [ EDITOR RENDER ] --------------------------------
function EditorRender()
for MT=1,#MarkerTypes do
for i,p in ipairs(getElementsByType(MarkerTypes[MT])) do
-- local ax,ay,az = exports.edf:edfGetElementPosition(p)
local ax,ay,az = getElementData(p, 'posX'), getElementData(p, 'posY'), getElementData(p, 'posZ')
local px,py,pz,lx,ly,lz = getCameraMatrix (gMe)
local x1,y1 = getScreenFromWorldPosition(ax,ay,az)
local dist = getDistanceBetweenPoints3D(ax,ay,az,px,py,pz)
local size = tonumber(getElementData(p, "size"))
if not size or size == 0 then size = 1 end
if dist < 500 and dist > 6 and x1 and (not isDestroyed[p]) then
local hit, x, y, z, elementHit = processLineOfSight ( ax,ay,az,px,py,pz )
if not hit then
local Tsize = (250/dist)*size
if MT == 24 then
local text = getElementData(p, "text")
local tsize2 = getElementData(p, "tsize")
if not tsize2 or tsize2 == 0 then tsize2 = 1 end
local tfont = getElementData(p, "tfont")
local tcolor = getElementData(p, "tcolor")
local tr, tg, tb, ta = conwert(tcolor)
dxDrawText(text,(x1-Tsize)+4,(y1-Tsize),x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,(x1-Tsize)+4,(y1-Tsize)+4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,(x1-Tsize),(y1-Tsize)+4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,(x1-Tsize)-4,(y1-Tsize)+4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,(x1-Tsize)-4,(y1-Tsize),x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,(x1-Tsize)-4,(y1-Tsize)-4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,(x1-Tsize),(y1-Tsize)-4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,(x1-Tsize)+4,(y1-Tsize)-4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize*tsize2/10,tfont,"center","center")
dxDrawText(text,x1-Tsize,y1-Tsize,x1+Tsize,y1+Tsize,tocolor(tr,tg,tb,ta),Tsize*tsize2/10,tfont,"center","center")
end
local icon = getElementData(p, "icon")
local scale = getElementData(p, "iconsize")
if not scale then scale = 1 end
if icon or icon == true or icon == "true" then
if MT == 25 then
local checkpoint = getElementData(p, "checkpoint")
if not checkpoint then checkpoint = 1 end
local textcolor = getElementData(p, "iconcolor")
local tr, tg, tb, ta = conwert(textcolor)
local cptext = ""..checkpoint
dxDrawText(cptext,(x1-Tsize)+4,(y1-Tsize),x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,(x1-Tsize)+4,(y1-Tsize)+4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,(x1-Tsize),(y1-Tsize)+4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,(x1-Tsize)-4,(y1-Tsize)+4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,(x1-Tsize)-4,(y1-Tsize),x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,(x1-Tsize)-4,(y1-Tsize)-4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,(x1-Tsize),(y1-Tsize)-4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,(x1-Tsize)+4,(y1-Tsize)-4,x1+Tsize,y1+Tsize,tocolor(0,0,0,ta/2),Tsize/scale/10,"pricedown","center","center")
dxDrawText(cptext,x1-Tsize,y1-Tsize,x1+Tsize,y1+Tsize,tocolor(tr,tg,tb,ta),Tsize/scale/10,"pricedown","center","center")
else
dxDrawImage(x1-Tsize/(2/scale),y1-Tsize/(2/scale),Tsize*scale,Tsize*scale,":Puma-Markers/Icons/"..MarkerTypes[MT]..".png")
if MT == 12 or MT == 13 or MT == 15 then
local o = getElementData(p,"ON")
if not o then
dxDrawImage(x1-Tsize/(2/scale),y1-Tsize/(2/scale),Tsize*scale,Tsize*scale,":Puma-Markers/Icons/X.png")
end
end
end
end
end
end
--[[
-- if exports.edf:edfGetElementProperty (p, "type") == "ring" then
if getElementData(p, "type") == "ring" then
if isSelected[p] then
local obrep = getRepresentation(p,"object")
local rx,ry,rz = getElementRotation(obrep)
local temp = createVehicle(594,ax,ay,az,rx,ry,-rz)
setElementAlpha(temp,0)
local matrix = getElementMatrix ( temp )
destroyElement (temp)
local offX = 0 * matrix[1][1] + 50 * matrix[2][1] + 0 * matrix[3][1] + matrix[4][1]
local offY = 0 * matrix[1][2] + 50 * matrix[2][2] + 0 * matrix[3][2] + matrix[4][2]
local offZ = 0 * matrix[1][3] + 50 * matrix[2][3] + 0 * matrix[3][3] + matrix[4][3]
local marker = getRepresentation(p,"marker")
setMarkerTarget (marker, tonumber(offX), tonumber(offY), tonumber(offZ))
end
end
if MT == 1 then
local dest = getElementData(p,"destination")
if dest and dest ~= "" then
if getElementByID ( dest ) then
destmark = getElementByID ( dest )
if getElementType(destmark) == "TeleportD" then
-- local x,y,z = exports.edf:edfGetElementPosition(destmark)
local x,y,z = getElementData(destmark, 'posX'), getElementData(destmark, 'posY'), getElementData(destmark, 'posZ')
local a,b = getScreenFromWorldPosition ( x, y, z )
local c,d = getScreenFromWorldPosition ( ax, ay, az )
if a and b and c and d then
if not isDestroyed[p] and not isDestroyed[destmark] then
dxDrawLine ( a,b,c,d, tocolor ( 0, 70, 255, 230 ), 3)
end
end
end
end
end
end
--]]
end
end
end
-------------------------------- [ EDITOR TEST ] --------------------------------
addEventHandler( "onClientResourceStart", gRoot,
function ( startedRes )
if #getElementsByType('spawnpoint', source) > 0 then
AntiSCChecker = 0
addEventHandler ( "onClientColShapeHit", gRoot, ColShapeHit )
Markery={}
Teleport = {} TeleportD = {} SlowDown = {} SpeedUp = {} Stop = {} Fire = {} BlowUp = {} Jump = {} Flip = {} Reverse = {} Rotate = {} CarsFly = {} CarsSwim = {} Gravity = {} Magnet = {} Beer = {} Camera = {} FlatTires = {} Freeze = {} GameSpeed = {} Color = {} Weather = {} Time = {} Text = {} AntiSC = {}
CollShapes = {Teleport,TeleportD,SlowDown,SpeedUp,Stop,Fire,BlowUp,Jump,Flip,Reverse,Rotate,CarsFly,CarsSwim,Gravity,Magnet,Beer,Camera,FlatTires,Freeze,GameSpeed,Color,Weather,Time,Text,AntiSC}
for MT=1,#MarkerTypes do
local ScriptType = getElementsByType(MarkerTypes[MT])
for i,p in ipairs(ScriptType) do
-- if i > (#ScriptType)/2 then
local x,y,z = getElementPosition (p)
local size = getElementData(p, "size")
local type = getElementData(p,"type")
local color = getElementData(p, "color")
local r, g, b, a = conwert(color)
local power = getElementData(p,"power")
local marker = createMarker(x,y,z,type,size,r,g,b,a)
if type == "checkpoint" then
local shape = createColCircle ( x, y, size ) CollShapes[MT][i] = shape
elseif type == "ring" or type == "arrow" or type == "corona" then
local shape = createColSphere ( x, y, z, size ) CollShapes[MT][i] = shape
elseif type == "cylinder" then
local shape = createColTube ( x, y, z, size , size ) CollShapes[MT][i] = shape
end
if type == "ring" then
-- local rx,ry,rz = exports.edf:edfGetElementRotation(p)
local rx,ry,rz = getElementData(p, 'rotX'), getElementData(p, 'rotY'), getElementData(p, 'rotZ')
local temp = createVehicle(594,x,y,z,rx,ry,rz)
setElementAlpha(temp,0)
local matrix = getElementMatrix ( temp )
destroyElement (temp)
local offX = 0 * matrix[1][1] + 50 * matrix[2][1] + 0 * matrix[3][1] + matrix[4][1]
local offY = 0 * matrix[1][2] + 50 * matrix[2][2] + 0 * matrix[3][2] + matrix[4][2]
local offZ = 0 * matrix[1][3] + 50 * matrix[2][3] + 0 * matrix[3][3] + matrix[4][3]
setMarkerTarget (marker, tonumber(offX), tonumber(offY), tonumber(offZ))
end
table.insert(Markery,marker)
-- end
end
end
end
end
)
addEventHandler( "onClientResourceStop", gRoot,
function ( startedRes )
if #getElementsByType('spawnpoint', source) > 0 then
removeEventHandler ( "onClientColShapeHit", gRoot, ColShapeHit )
for i=1, #Markery do
destroyElement(Markery[i])
end
for MT=1,#MarkerTypes do
local ScriptType = getElementsByType(MarkerTypes[MT])
for i=1, #ScriptType do
if i > (#ScriptType)/2 then
destroyElement(CollShapes[MT][i])
end
end
end
end
end
)
-------------------------------- [ EDITOR TEST HIT ] --------------------------------
function ColShapeHit(player,machdimension)
if (player == gMe) then
for MT=1,#MarkerTypes do
local ScriptType = getElementsByType(MarkerTypes[MT])
for i,p in ipairs(ScriptType) do
if CollShapes[MT][i] == source then
local veh = getPedOccupiedVehicle(player)
if veh and isElement(veh) and (getVehicleOccupant(veh,0) == player) then
local x,y,z = getElementPosition(veh)
local vx,vy,vz = getElementVelocity(veh)
local rx,ry,rz = getElementRotation(veh)
----------------------------------------------------------------------------
if MT == 1 then
local dest = getElementData(p,"destination")
if dest and dest ~= "" then
if getElementByID ( dest ) then
destmark = getElementByID ( dest )
if getElementType(destmark) == "TeleportD" then
TeleporterData[i] = 1
local fade = getElementData(p,"fade")
local stop = getElementData(p,"stop")
-- local tx,ty,tz = exports.edf:edfGetElementPosition(destmark)
local tx,ty,tz = getElementData(destmark, 'posX'), getElementData(destmark, 'posY'), getElementData(destmark, 'posZ')
local vrx,vry,vrz = getVehicleTurnVelocity(veh)
setElementFrozen(veh,true)
if fade == "true" then fadeCamera ( false, 1) end
setTimer(function(veh,tx,ty,tz,fade,stop)
setElementFrozen(veh,false)
setElementPosition(veh,tx,ty,tz)
setElementFrozen(veh,true)
if fade == "true" then fadeCamera ( true, 1) end
setTimer(function(stop)
setElementFrozen(veh,false)
if stop == "false" then setElementVelocity(veh,vx,vy,vz) setVehicleTurnVelocity(veh,vrx,vry,vrz) end
end,1000,1,stop)
end,1000,1,veh,tx,ty,tz,fade,stop)
else
if TeleporterData ~= 1 then
TeleporterData[i] = 2
end
end
end
else
outputDebugString("• Puma-Markers : ( You must set a destination for "..getElementID(p).."! DoubleClick on this teleporter. )",255,255,255,true)
end
if TeleporterData[i] == 2 then
outputDebugString("• Puma-Markers : ( Can't find destination for "..getElementID(p).."! ["..dest.."] )",255,255,255,true)
end
elseif MT == 3 then
local power = getElementData(p,"power")
if tonumber(power) < 1 then power = 1 end
local power = 1/power
setElementVelocity (veh,vx*power,vy*power,vz*power)
elseif MT == 4 then
local power = getElementData(p,"power")
if tonumber(power) < 1 then power = 1 end
setElementVelocity (veh,vx*power,vy*power,vz*power)
elseif MT == 5 then
setElementVelocity (veh,0,0,0)
elseif MT == 6 then
setElementHealth (veh,249)
elseif MT == 7 then
setElementHealth (veh,0)
elseif MT == 8 then
local power = getElementData(p,"power")
setElementVelocity (veh,vx,vy,vz+(power/10))
elseif MT == 9 then
setElementRotation(veh,0,0,rz)
setVehicleTurnVelocity(veh,0,0,0)
elseif MT == 10 then
setElementVelocity(veh, -vx,-vy,-vz)
setElementRotation(veh, -rx, -ry, rz+180)
elseif MT == 11 then
setElementRotation(veh, -rx, -ry, rz+180)
elseif MT == 12 then
local o = getElementData(p,"ON")
if o == "true" and MW == 0 then
if not isWorldSpecialPropertyEnabled("aircars") then
setWorldSpecialPropertyEnabled ( "aircars" , true )
FM = 1
end
else
if isWorldSpecialPropertyEnabled("aircars") then
setWorldSpecialPropertyEnabled ( "aircars" , false )
FM = 0
end
end
elseif MT == 13 then
local o = getElementData(p,"ON")
if o == "true" and MW == 0 then
if not isWorldSpecialPropertyEnabled("hovercars") then
setWorldSpecialPropertyEnabled ( "hovercars" , true )
SM = 1
end
else
if isWorldSpecialPropertyEnabled("hovercars") then
setWorldSpecialPropertyEnabled ( "hovercars" , false )
SM = 0
end
end
elseif MT == 14 then
local power = getElementData(p,"power")
local aim = getElementData(p,"destination")
if string.lower(aim) == "up" or string.lower(aim) == "u" then
setVehicleGravityPoint( veh, x, y, z+1000, power )
elseif string.lower(aim) == "down" or string.lower(aim) == "d" then
setVehicleGravityPoint( veh, x, y, z-1000, power )
elseif string.lower(aim) == "n" or string.lower(aim) == "north" then
setVehicleGravityPoint( veh, x, y+1000, z, power )
elseif string.lower(aim) == "s" or string.lower(aim) == "south"then
setVehicleGravityPoint( veh, x, y-1000, z, power )
elseif string.lower(aim) == "e" or string.lower(aim) == "east"then
setVehicleGravityPoint( veh, x+1000, y, z, power )
elseif string.lower(aim) == "w" or string.lower(aim) == "west"then
setVehicleGravityPoint( veh, x-1000, y, z, power )
end
elseif MT == 15 then
local o = getElementData(p,"ON")
if MW == 0 and o == "true" and FM == 0 then
addEventHandler("onClientRender",gRoot,magnetWheels)
MW = 1
magnetObject = createObject(902, 200, 200, 200)
setElementCollisionsEnabled ( magnetObject, "false" )
setElementInterior(magnetObject, 25)
setElementAlpha(magnetObject,0)
elseif MW == 1 and o == "false" then
removeEventHandler("onClientRender",gRoot,magnetWheels)
setVehicleGravityPoint( veh, x, y, z-1000, 1)
MW = 0
if magnetObject then destroyElement(magnetObject) end
end
elseif MT == 16 then
local time = getElementData(p,"time")
createExplosion ( x, y, z-30, 1 ,false, 2, false )
setTimer(function() local x,y,z = getElementPosition(veh) createExplosion ( x, y, z-30, 2 ,false, 1, false ) end, 500,time*2,veh)
elseif MT == 17 then
local time = getElementData(p,"time")
local col = getElementData(p,"fadecolor")
local r,g,b,a = conwert(col)
fadeCamera ( false, 1, r,g,b)
setTimer(function() fadeCamera ( true, 1) end, time*1000,1)
elseif MT == 18 then
setVehicleWheelStates ( veh, 1, 1, 1, 1)
elseif MT == 19 then
local time = getElementData(p,"time")
setElementFrozen(veh,true)
setTimer(function() setElementFrozen(veh,false) end,time*1000,1,veh)
elseif MT == 20 then
local speed = getElementData(p,"speed")
setGameSpeed(speed)
elseif MT == 21 then
local r,g,b,a = conwert(getElementData(p,"skyup"))
local r2,g2,b2,a = conwert(getElementData(p,"skydown"))
setSkyGradient ( r, g, b, r2, g2, b2 )
local r,g,b,a = conwert(getElementData(p,"water"))
setWaterColor ( r,g,b,a )
elseif MT == 22 then
local weather = getElementData(p,"weather")
setWeather ( weather )
elseif MT == 23 then
local hr = getElementData(p,"hour")
local mn = getElementData(p,"minute")
setTime (hr,mn)
elseif MT == 25 then
local cpnr = getElementData(p,"checkpoint")
if tonumber(cpnr) > tonumber(AntiSCChecker)+1 then
blowVehicle(veh)
SCUTERtext = getElementData(p,"text")
SCr,SCg,SCb,SCa = conwert(getElementData(p,"textcolor"))
addEventHandler("onClientRender",gRoot,SCuter)
setTimer(function() removeEventHandler("onClientRender",gRoot,SCuter,text,r,g,b,a) end,10000,1)
else
AntiSCChecker = cpnr
end
end
end
end
end
end
end
end
function SCuter()
if SCScale then
SCScale = SCScale+0.002
else
SCScale = 0
end
dxDrawText(SCUTERtext,5,0,screenWidth, screenHeight-55,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,5,0,screenWidth, screenHeight-55,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,5,0,screenWidth, screenHeight-50,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,5,5,screenWidth, screenHeight-50,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,0,5,screenWidth, screenHeight-50,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,0,5,screenWidth-5, screenHeight-50,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,0,0,screenWidth-5, screenHeight-50,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,0,0,screenWidth-5, screenHeight-55,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,0,0,screenWidth, screenHeight-55,tocolor(0,0,0,128),1.5+SCScale,"pricedown","center","center")
dxDrawText(SCUTERtext,0,0,screenWidth, screenHeight-50,tocolor(SCr,SCg,SCb,SCa),1.5+SCScale,"pricedown","center","center")
end
function wasted ()
if source ~= gMe then return end
removeEventHandler("onClientRender",gRoot,magnetWheels)
MW = 0
setGameSpeed(1)
setWorldSpecialPropertyEnabled ( "aircars" , false )
setWorldSpecialPropertyEnabled ( "hovercars" , false )
end
---------------------------------------------------------------
function setVehicleGravityPoint( targetVehicle, pointX, pointY, pointZ, strength )
if isElement( targetVehicle ) and getElementType( targetVehicle ) == "vehicle" then
local vehicleX,vehicleY,vehicleZ = getElementPosition( targetVehicle )
local vectorX = vehicleX-pointX
local vectorY = vehicleY-pointY
local vectorZ = vehicleZ-pointZ
local length = ( vectorX^2 + vectorY^2 + vectorZ^2 )^0.5
local propX = vectorX^2 / length^2
local propY = vectorY^2 / length^2
local propZ = vectorZ^2 / length^2
local finalX = ( strength^2 * propX )^0.5
local finalY = ( strength^2 * propY )^0.5
local finalZ = ( strength^2 * propZ )^0.5
if vectorX > 0 then finalX = finalX * -1 end
if vectorY > 0 then finalY = finalY * -1 end
if vectorZ > 0 then finalZ = finalZ * -1 end
return setVehicleGravity( targetVehicle, finalX, finalY, finalZ )
end
return false
end
local max_grav = 0.01 -- normal gravity is 0.01
function magnetWheels()
if(getPedOccupiedVehicle(gMe) == false)then return end
local vehicle = getPedOccupiedVehicle(gMe)
attachElements(magnetObject, vehicle, 0, 0, -0.001)
local velX, velY, velZ = getElementVelocity(vehicle)
local mX, mY, mZ = getDiff(vehicle, magnetObject)
mX = mX * max_grav
mY = mY * max_grav
mZ = mZ * max_grav
setVehicleGravity(vehicle, 0, 0, 0)
setElementVelocity(vehicle, velX + mX, velY + mY, velZ + mZ)
end
function getDiff(vehicle, object)
local vehX, vehY, vehZ = getElementPosition(vehicle)
local objX, objY, objZ = getElementPosition(object)
local dist2D = math.sqrt((vehX - objX)^2 + (vehY - objY)^2)
local dist3D = math.sqrt(dist2D^2 + (vehZ - objZ)^2)
local distX = (objX - vehX) / dist3D
local distY = (objY - vehY) / dist3D
local distZ = (objZ - vehZ) / dist3D
if(distX > 1)then
distX = 1
end
if(distY > 1)then
distY = 1
end
if(distZ > 1)then
distZ = 1
end
return distX, distY, distZ
end
--[[function magnetWheels()
local veh = getPedOccupiedVehicle(gMe)
local x,y,z = getElementPosition(veh)
local underx,undery,underz = getPositionUnderTheElement(veh)
setVehicleGravity(veh,underx - x,undery - y,underz - z)
end
function getPositionUnderTheElement(element)
local matrix = getElementMatrix (element)
local offX = 0 * matrix[1][1] + 0 * matrix[2][1] - 1 * matrix[3][1] + matrix[4][1]
local offY = 0 * matrix[1][2] + 0 * matrix[2][2] - 1 * matrix[3][2] + matrix[4][2]
local offZ = 0 * matrix[1][3] + 0 * matrix[2][3] - 1 * matrix[3][3] + matrix[4][3]
return offX,offY,offZ
end]]--
function getRepresentation(element,type)
for i,elem in ipairs(getElementsByType(type,element)) do
if elem ~= exports.edf:edfGetHandle ( elem ) then
return elem
end
end
return false
end
function conwert(color)
local hexTodecim = {["0"]=0,["1"]=1,["2"]=2,["3"]=3,["4"]=4,["5"]=5,["6"]=6,["7"]=7,["8"]=8,["9"]=9,["a"]=10,["b"]=11,["c"]=12,["d"]=13,["e"]=14,["f"]=15}
local red = (hexTodecim[string.lower(string.sub(color, 2, 2))]*16) + hexTodecim[string.lower(string.sub(color, 3, 3))]
local gren = (hexTodecim[string.lower(string.sub(color, 4, 4))]*16) + hexTodecim[string.lower(string.sub(color, 5, 5))]
local blue = (hexTodecim[string.lower(string.sub(color, 6, 6))]*16) + hexTodecim[string.lower(string.sub(color, 6, 6))]
local alpha = (hexTodecim[string.lower(string.sub(color, 8, 8))]*16) + hexTodecim[string.lower(string.sub(color, 9, 9))]
return red, gren, blue, alpha
end | mit |
noooway/love2d_arkanoid_tutorial | 3-17_Packaging/lives_display.lua | 4 | 1368 | local vector = require "vector"
local lives_display = {}
lives_display.lives = 5
lives_display.lives_added_from_score = 0
local position = vector( 620, 500 )
local width = 170
local height = 65
local bungee_font = love.graphics.newFont(
"/fonts/Bungee_Inline/BungeeInline-Regular.ttf", 30 )
function lives_display.update( dt )
end
function lives_display.draw()
local oldfont = love.graphics.getFont()
love.graphics.setFont( bungee_font )
local r, g, b, a = love.graphics.getColor( )
love.graphics.setColor( 255, 255, 255, 230 )
love.graphics.printf( "Lives: " .. tostring( lives_display.lives ),
position.x,
position.y,
width,
"center" )
love.graphics.setFont( oldfont )
love.graphics.setColor( r, g, b, a )
end
function lives_display.lose_life()
lives_display.lives = lives_display.lives - 1
end
function lives_display.add_life()
lives_display.lives = lives_display.lives + 1
end
function lives_display.add_life_if_score_reached( score )
local score_milestone = (lives_display.lives_added_from_score + 1) * 3000
if score >= score_milestone then
lives_display.add_life()
lives_display.lives_added_from_score =
lives_display.lives_added_from_score + 1
end
end
function lives_display.reset()
lives_display.lives = 5
lives_display.lives_added_from_score = 0
end
return lives_display
| mit |
Phrohdoh/OpenRA | mods/d2k/maps/ordos-01b/ordos01b.lua | 4 | 5019 | --[[
Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
HarkonnenReinforcements =
{
easy =
{
{ "light_inf", "light_inf" }
},
normal =
{
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" }
},
hard =
{
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
}
HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location }
HarkonnenAttackDelay = DateTime.Seconds(30)
HarkonnenAttackWaves =
{
easy = 1,
normal = 5,
hard = 12
}
ToHarvest =
{
easy = 2500,
normal = 3000,
hard = 3500
}
OrdosReinforcements = { "light_inf", "light_inf", "light_inf", "light_inf", "raider" }
OrdosEntryPath = { OrdosWaypoint.Location, OrdosRally.Location }
Messages =
{
"Build a concrete foundation before placing your buildings.",
"Build a Wind Trap for power.",
"Build a Refinery to collect Spice.",
"Build a Silo to store additional Spice."
}
Tick = function()
if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillHarkonnen)
end
if player.Resources > SpiceToHarvest - 1 then
player.MarkCompletedObjective(GatherSpice)
end
-- player has no Wind Trap
if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then
HasPower = false
Media.DisplayMessage(Messages[2], "Mentat")
else
HasPower = true
end
-- player has no Refinery and no Silos
if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[3], "Mentat")
end
if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[4], "Mentat")
end
UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. SpiceToHarvest, player.Color)
end
WorldLoaded = function()
player = Player.GetPlayer("Ordos")
harkonnen = Player.GetPlayer("Harkonnen")
SpiceToHarvest = ToHarvest[Difficulty]
InitObjectives(player)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Ordos units.")
GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(SpiceToHarvest) .. " Solaris worth of Spice.")
KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
local checkResourceCapacity = function()
Trigger.AfterDelay(0, function()
if player.ResourceCapacity < SpiceToHarvest then
Media.DisplayMessage("We don't have enough silo space to store the required amount of Spice!", "Mentat")
Trigger.AfterDelay(DateTime.Seconds(3), function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
return true
end
end)
end
Trigger.OnRemovedFromWorld(OrdosConyard, function()
-- Mission already failed, no need to check the other conditions as well
if checkResourceCapacity() then
return
end
local refs = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "refinery" and actor.Owner == player end)
if #refs == 0 then
harkonnen.MarkCompletedObjective(KillAtreides)
else
Trigger.OnAllRemovedFromWorld(refs, function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
local silos = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "silo" and actor.Owner == player end)
Utils.Do(refs, function(actor) Trigger.OnRemovedFromWorld(actor, checkResourceCapacity) end)
Utils.Do(silos, function(actor) Trigger.OnRemovedFromWorld(actor, checkResourceCapacity) end)
end
end)
Media.DisplayMessage(Messages[1], "Mentat")
Trigger.AfterDelay(DateTime.Seconds(25), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, OrdosReinforcements, OrdosEntryPath)
end)
WavesLeft = HarkonnenAttackWaves[Difficulty]
SendReinforcements()
end
SendReinforcements = function()
local units = HarkonnenReinforcements[Difficulty]
local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay)
HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1)
if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end
Trigger.AfterDelay(delay, function()
Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt)
WavesLeft = WavesLeft - 1
if WavesLeft == 0 then
Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end)
else
SendReinforcements()
end
end)
end
| gpl-3.0 |
Ekdohibs/minetest_game | mods/vessels/init.lua | 18 | 6192 | -- Minetest 0.4 mod: vessels
-- See README.txt for licensing and other information.
local vessels_shelf_formspec =
"size[8,7;]" ..
default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"list[context;vessels;0,0.3;8,2;]" ..
"list[current_player;main;0,2.85;8,1;]" ..
"list[current_player;main;0,4.08;8,3;8]" ..
"listring[context;vessels]" ..
"listring[current_player;main]" ..
default.get_hotbar_bg(0, 2.85)
local function get_vessels_shelf_formspec(inv)
local formspec = vessels_shelf_formspec
local invlist = inv and inv:get_list("vessels")
-- Inventory slots overlay
local vx, vy = 0, 0.3
for i = 1, 16 do
if i == 9 then
vx = 0
vy = vy + 1
end
if not invlist or invlist[i]:is_empty() then
formspec = formspec ..
"image[" .. vx .. "," .. vy .. ";1,1;vessels_shelf_slot.png]"
end
vx = vx + 1
end
return formspec
end
minetest.register_node("vessels:shelf", {
description = "Vessels Shelf",
tiles = {"default_wood.png", "default_wood.png", "default_wood.png",
"default_wood.png", "vessels_shelf.png", "vessels_shelf.png"},
paramtype2 = "facedir",
is_ground_content = false,
groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3},
sounds = default.node_sound_wood_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", get_vessels_shelf_formspec(nil))
local inv = meta:get_inventory()
inv:set_size("vessels", 8 * 2)
end,
can_dig = function(pos,player)
local inv = minetest.get_meta(pos):get_inventory()
return inv:is_empty("vessels")
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
if minetest.get_item_group(stack:get_name(), "vessel") ~= 0 then
return stack:get_count()
end
return 0
end,
on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
minetest.log("action", player:get_player_name() ..
" moves stuff in vessels shelf at ".. minetest.pos_to_string(pos))
local meta = minetest.get_meta(pos)
meta:set_string("formspec", get_vessels_shelf_formspec(meta:get_inventory()))
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" moves stuff to vessels shelf at ".. minetest.pos_to_string(pos))
local meta = minetest.get_meta(pos)
meta:set_string("formspec", get_vessels_shelf_formspec(meta:get_inventory()))
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" takes stuff from vessels shelf at ".. minetest.pos_to_string(pos))
local meta = minetest.get_meta(pos)
meta:set_string("formspec", get_vessels_shelf_formspec(meta:get_inventory()))
end,
on_blast = function(pos)
local drops = {}
default.get_inventory_drops(pos, "vessels", drops)
drops[#drops + 1] = "vessels:shelf"
minetest.remove_node(pos)
return drops
end,
})
minetest.register_craft({
output = "vessels:shelf",
recipe = {
{"group:wood", "group:wood", "group:wood"},
{"group:vessel", "group:vessel", "group:vessel"},
{"group:wood", "group:wood", "group:wood"},
}
})
minetest.register_node("vessels:glass_bottle", {
description = "Glass Bottle (empty)",
drawtype = "plantlike",
tiles = {"vessels_glass_bottle.png"},
inventory_image = "vessels_glass_bottle.png",
wield_image = "vessels_glass_bottle.png",
paramtype = "light",
is_ground_content = false,
walkable = false,
selection_box = {
type = "fixed",
fixed = {-0.25, -0.5, -0.25, 0.25, 0.3, 0.25}
},
groups = {vessel = 1, dig_immediate = 3, attached_node = 1},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_craft( {
output = "vessels:glass_bottle 10",
recipe = {
{"default:glass", "", "default:glass"},
{"default:glass", "", "default:glass"},
{"", "default:glass", ""}
}
})
minetest.register_node("vessels:drinking_glass", {
description = "Drinking Glass (empty)",
drawtype = "plantlike",
tiles = {"vessels_drinking_glass.png"},
inventory_image = "vessels_drinking_glass_inv.png",
wield_image = "vessels_drinking_glass.png",
paramtype = "light",
is_ground_content = false,
walkable = false,
selection_box = {
type = "fixed",
fixed = {-0.25, -0.5, -0.25, 0.25, 0.3, 0.25}
},
groups = {vessel = 1, dig_immediate = 3, attached_node = 1},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_craft( {
output = "vessels:drinking_glass 14",
recipe = {
{"default:glass", "", "default:glass"},
{"default:glass", "", "default:glass"},
{"default:glass", "default:glass", "default:glass"}
}
})
minetest.register_node("vessels:steel_bottle", {
description = "Heavy Steel Bottle (empty)",
drawtype = "plantlike",
tiles = {"vessels_steel_bottle.png"},
inventory_image = "vessels_steel_bottle.png",
wield_image = "vessels_steel_bottle.png",
paramtype = "light",
is_ground_content = false,
walkable = false,
selection_box = {
type = "fixed",
fixed = {-0.25, -0.5, -0.25, 0.25, 0.3, 0.25}
},
groups = {vessel = 1, dig_immediate = 3, attached_node = 1},
sounds = default.node_sound_defaults(),
})
minetest.register_craft( {
output = "vessels:steel_bottle 5",
recipe = {
{"default:steel_ingot", "", "default:steel_ingot"},
{"default:steel_ingot", "", "default:steel_ingot"},
{"", "default:steel_ingot", ""}
}
})
-- Glass and steel recycling
minetest.register_craftitem("vessels:glass_fragments", {
description = "Pile of Glass Fragments",
inventory_image = "vessels_glass_fragments.png",
})
minetest.register_craft( {
type = "shapeless",
output = "vessels:glass_fragments",
recipe = {
"vessels:glass_bottle",
"vessels:glass_bottle",
},
})
minetest.register_craft( {
type = "shapeless",
output = "vessels:glass_fragments",
recipe = {
"vessels:drinking_glass",
"vessels:drinking_glass",
},
})
minetest.register_craft({
type = "cooking",
output = "default:glass",
recipe = "vessels:glass_fragments",
})
minetest.register_craft( {
type = "cooking",
output = "default:steel_ingot",
recipe = "vessels:steel_bottle",
})
minetest.register_craft({
type = "fuel",
recipe = "vessels:shelf",
burntime = 30,
})
| lgpl-2.1 |
DarkJaguar91/DJBags | src/bank/Reagent.lua | 1 | 1423 | local ADDON_NAME, ADDON = ...
local bank = {}
bank.__index = bank
function DJBagsRegisterReagentBagContainer(self, bags)
DJBagsRegisterBaseBagContainer(self, bags)
self.BaseOnShow = self.OnShow
for k, v in pairs(bank) do
self[k] = v
end
ADDON.eventManager:Add('BANKFRAME_OPENED', self)
ADDON.eventManager:Add('BANKFRAME_CLOSED', self)
ADDON.eventManager:Add('PLAYERREAGENTBANKSLOTS_CHANGED', self)
end
function bank:BANKFRAME_OPENED()
if BankFrame.selectedTab == 2 then
self:Show()
end
end
function bank:BANKFRAME_CLOSED()
self:Hide()
end
function bank:PLAYERREAGENTBANKSLOTS_CHANGED()
self:BAG_UPDATE(REAGENTBANK_CONTAINER)
end
local function BuyReagentTab()
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION)
StaticPopup_Show("CONFIRM_BUY_REAGENTBANK_TAB")
end
function bank:OnShow()
if not IsReagentBankUnlocked() then
if not self.purchaseButton then
self.purchaseButton = CreateFrame("Button", "DJBagsReagentPurchase", self, 'UIPanelButtonTemplate')
self.purchaseButton:SetPoint('TOPLEFT', 5, -5)
self.purchaseButton:SetPoint('BOTTOMRIGHT', -5, 5)
self.purchaseButton:SetText("Purchase")
self.purchaseButton:SetScript('OnClick', BuyReagentTab)
end
self.purchaseButton:Show()
self:SetSize(125, 35)
else
if (self.purchaseButton) then
self.purchaseButton:Hide()
end
self:BaseOnShow()
end
end
| mit |
vilarion/Illarion-Content | quest/groknar_311_noobia.lua | 1 | 4494 | --[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (311, 'quest.groknar_311_noobia');
local common = require("base.common")
local monsterQuests = require("monster.base.quests")
local M = {}
local GERMAN = Player.german
local ENGLISH = Player.english
-- Insert the quest title here, in both languages
local Title = {}
Title[GERMAN] = "Einführung - Kämpfen"
Title[ENGLISH] = "Tutorial - Fighting"
-- Insert an extensive description of each status here, in both languages
-- Make sure that the player knows exactly where to go and what to do
local Description = {}
Description[GERMAN] = {}
Description[ENGLISH] = {}
Description[GERMAN][1] = "Diese Station lehrt dich, wie man kämpft. Groknar, der Lehrmeister, ist ein stolzer und mächtiger Orkkrieger. Stell dich ihm vor - vorsichtig.\n\nMonster und auch andere Spielercharaktere (PvP) kannst du mit einem Rechtsklick angreifen."
Description[ENGLISH][1] = "At the next station, you will learn how to fight. Groknar, the instructor, is a proud and mighty Orc warrior. Just speak up to him - carefully.\n\nTo attack monsters and also other player characters (PvP), click on them once with the right mouse button."
Description[GERMAN][2] = "Hurr! Frischfleisch! Ich bin Groknar, der mächtigste Jäger meines Clans. Ich bring dir bei, erbärmliche Kreaturen zu erschlagen. Nimm diesen Knüppel in die Hand und erschlage drei dieser Schweine dort drüben. Du kannst mit dem Angriff auf erbärmliche Kreaturen beginnen, indem du sie einmal mit der rechten Maustaste anklickst."
Description[ENGLISH][2] = "Hurr! Fresh meat! I be Groknar, mightiest hunter of my clan. I will teach you how to smash puny creatures. Equip this club and crush three of those pigs over there. You can begin attacking puny creatures by clicking on them once with the right mouse button."
Description[GERMAN][3] = "Töte noch zwei Schweine. Klicke hierzu ein Schwein einmal mit der rechten Maustaste an."
Description[ENGLISH][3] = "Kill two pigs. Attack a pig by clicking it once with the right mouse button."
Description[GERMAN][4] = "Töte noch ein Schwein. Klicke hierzu ein Schwein einmal mit der rechten Maustaste an."
Description[ENGLISH][4] = "Kill another pig. Attack a pig by clicking it once with the right mouse button."
Description[GERMAN][5] = "Kehre zu Groknar zurück, um deine Belohnung zu erhalten."
Description[ENGLISH][5] = "Return to Groknar to claim your reward."
Description[GERMAN][6] = "Du hast die Einführung über das Kämpfen abgeschlossen."
Description[ENGLISH][6] = "You finished the tutorial on fighting."
-- Insert the position of the quest start here (probably the position of an NPC or item)
local Start = {41, 44, 100}
-- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there
local QuestTarget = {}
--QuestTarget[1] = {position(x, y, 100), position(x, y, 100)}
-- Insert the quest status which is reached at the end of the quest
local FINAL_QUEST_STATUS = 6
-- Register the monster kill parts of the quest.
monsterQuests.addQuest{
questId = 311,
location = {position = position(41, 46, 100), radius = 50},
queststatus = {from = 2, to = 5},
questTitle = {german = "Tutorial", english = "Tutorial"},
monsterName = {german = "Schweine", english = "pigs"},
npcName = "Groknar",
monsterIds = {241} -- pig
}
function M.QuestTitle(user)
return common.GetNLS(user, Title[GERMAN], Title[ENGLISH])
end
function M.QuestDescription(user, status)
local german = Description[GERMAN][status] or ""
local english = Description[ENGLISH][status] or ""
return common.GetNLS(user, german, english)
end
function M.QuestStart()
return Start
end
function M.QuestTargets(user, status)
return QuestTarget[status]
end
function M.QuestFinalStatus()
return FINAL_QUEST_STATUS
end
return M
| agpl-3.0 |
ffxiphoenix/darkstar | scripts/globals/items/plate_of_patlican_salata.lua | 35 | 1211 | -----------------------------------------
-- ID: 5582
-- Item: plate_of_patlican_salata
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Agility 4
-- Vitality -1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5582);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 4);
target:addMod(MOD_VIT, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 4);
target:delMod(MOD_VIT, -1);
end;
| gpl-3.0 |
Quenty/NevermoreEngine | src/lipsum/src/Shared/LipsumUtils.lua | 1 | 4307 | --[=[
Helpers generate test text for a variety of situations, in the standard Lorem-Ipsum utility system.
@class LipsumUtils
]=]
local require = require(script.Parent.loader).load(script)
local RandomUtils = require("RandomUtils")
local String = require("String")
local LipsumUtils = {}
local WORDS = {
"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "sed", "diam", "nonummy",
"nibh", "euismod", "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat"}
--[=[
Generates a random username.
```lua
print(LipsumUtils.username()) --> LoremIpsum23
```
@param random Random? -- Optional random
@return string
]=]
function LipsumUtils.username(random)
random = random or Random.new()
local word = RandomUtils.choice(WORDS, random)
if random:NextNumber() <= 0.5 then
word = String.uppercaseFirstLetter(word)
end
-- leet speak
if random:NextNumber() <= 0.5 then
if random:NextNumber() <= 0.75 then
word = word:gsub("o", "0")
end
if random:NextNumber() <= 0.75 then
word = word:gsub("i", "1")
end
if random:NextNumber() <= 0.75 then
word = word:gsub("l", "1")
end
end
local number = random:NextNumber()
if number <= 0.1 then
return "xXx" .. RandomUtils.choice(WORDS) .. "xXx"
elseif number <= 0.6 then
return ("%s%03d"):format(word, random:NextInteger(0, 999))
else
return word
end
end
--[=[
Generates a random word.
```lua
print(LipsumUtils.word()) --> Lipsum
```
@param random Random? -- Optional random
@return string
]=]
function LipsumUtils.word(random)
return LipsumUtils.words(1, random)
end
--[=[
Generates a random set of words space-separated.
```lua
print(LipsumUtils.words(5)) --> 5 words
```
@param numWords number
@param random Random? -- Optional random
@return string
]=]
function LipsumUtils.words(numWords, random)
local output = ""
for w = 1, numWords do
local word = RandomUtils.choice(WORDS, random)
if w == 1 then
output = output .. String.uppercaseFirstLetter(word)
else
output = output .. " " .. word
end
end
return output
end
--[=[
Generates a random sentence.
```lua
print(LipsumUtils.sentence(7)) --> Sentence with 7 words.
```
@param numWords number? -- Defaults to a random number 6 to 12.
@param random Random? -- Optional random
@return string
]=]
function LipsumUtils.sentence(numWords, random)
random = random or Random.new()
numWords = numWords or random:NextInteger(6, 12)
local output = ""
local commaIndexes = {}
if random:NextNumber() >= 0.3 and numWords >= 8 then
commaIndexes[random:NextInteger(4, 5)] = true
end
for w = 1, numWords do
local word = RandomUtils.choice(WORDS, random)
if w == 1 then
output = output .. String.uppercaseFirstLetter(word)
else
if commaIndexes[w] then
output = output .. ", " .. word
else
output = output .. " " .. word
end
end
end
output = output .. "."
return output
end
--[=[
Generates a random paragraph.
```lua
print(LipsumUtils.paragraph(4)) --> Paragraph with 4 sentences.
```
@param numSentences number
@param createSentence (() -> string)? -- Optional createSentence
@param random Random? -- Optional random
@return string
]=]
function LipsumUtils.paragraph(numSentences, createSentence, random)
random = random or Random.new()
numSentences = numSentences or random:NextInteger(5, 15)
createSentence = createSentence or function()
return LipsumUtils.sentence(nil, random)
end
local output = ""
for s=1, numSentences do
output = output .. createSentence()
if s ~= numSentences then
output = output .. " "
end
end
return output
end
--[=[
```lua
print(LipsumUtils.document(3)) --> Document with 3 paragraphs
```
@param numParagraphs number
@param createParagraph (() -> string)? -- Optional createParagraph
@param random Random? -- Optional random
@return string
]=]
function LipsumUtils.document(numParagraphs, createParagraph, random)
random = random or Random.new()
numParagraphs = numParagraphs or 5
createParagraph = createParagraph or function()
return LipsumUtils.paragraph(nil, nil, random)
end
local output = ""
for p=1, numParagraphs do
output = output .. createParagraph()
if p ~= numParagraphs then
output = output .. "\n\n"
end
end
return output
end
return LipsumUtils | mit |
ktf/apt-rpm | contrib/apt-files/apt-files.lua | 3 | 1036 | -- This script must be plugged into the APT script slot
-- Scripts::AptGet::Install::TranslateArg
--
-- Author: Gustavo Niemeyer <niemeyer@conectiva.com>
--
-- Data sample:
-- argument = "/usr/bin/python"
-- contents = "/var/lib/apt/Contents.gz"
-- translated = {}
if string.sub(argument, 1, 1) == "/" then
contents = confget("Dir::State::contents/f")
if string.sub(contents, -3) == ".gz" then
file = io.popen("zcat "..contents)
elseif string.sub(contents, -4) == ".bz2" then
file = io.popen("bzcat "..contents)
else
file = io.open(contents)
end
len = string.len(argument)
for line in file:lines() do
if string.sub(line, 1, len) == argument then
_, _, path, name = string.find(line, '(%S+)%s+(%S+)')
if path == argument then
translated = name
break
end
end
end
for line in file:lines() do
-- nothing, just don't break the pipe
end
file:close()
end
-- vim:st=4:sw=4:et
| gpl-2.0 |
ffxiphoenix/darkstar | scripts/zones/Nashmau/npcs/Pipiroon.lua | 34 | 1224 | -----------------------------------
-- Area: Nashmau
-- NPC: Pipiroon
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PIPIROON_SHOP_DIALOG);
stock = {0x43A1,1204, -- Grenade
0x43A3,6000, -- Riot Grenade
0x03A0,515, -- Bomb Ash
0x0b39,10000} -- Nashmau Waystone
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.