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 |
|---|---|---|---|---|---|
Frenzie/koreader | frontend/ui/data/keyboardlayouts/pt_keyboard.lua | 9 | 4958 | return {
min_layer = 1,
max_layer = 12,
shiftmode_keys = {[""] = true},
symbolmode_keys = {["Sym"] = true, ["ABC"] = true},
utf8mode_keys = {["🌐"] = true},
umlautmode_keys = {["Äéß"] = true},
keys = {
-- first row
{ -- 1 2 3 4 5 6 7 8 9 10 11 12
{ "Q", "q", "„", "0", "Ã", "ã", "„", "0", "Ä", "ä", "1", "ª", },
{ "W", "w", "!", "1", "Á", "á", "!", "1", "Ö", "ö", "2", "º", },
{ "E", "e", "@", "2", "É", "é", "@", "2", "Ü", "ü", "3", "¡", },
{ "R", "r", "#", "3", "Ê", "ê", "#", "3", "ß", "ß", "4", "¿", },
{ "T", "t", "+", "=", "T", "t", "+", "=", "À", "à", "5", "¼", },
{ "Y", "y", "€", "(", "Ü", "ü", "€", "(", "Â", "â", "6", "½", },
{ "U", "u", "‰", ")", "Ú", "ú", "‰", ")", "Æ", "æ", "7", "¾", },
{ "I", "i", "|", "\\", "Í", "í", "|", "\\", "Ç", "ç", "8", "©", },
{ "O", "o", "?", "/", "Õ", "õ", "?", "/", "È", "è", "9", "®", },
{ "P", "p", "~", "`", "Ó", "ó", "~", "`", "É", "é", "0", "™", },
},
-- second row
{ -- 1 2 3 4 5 6 7 8 9 10 11 12
{ "A", "a", "…", "@", "À", "à", "…", "@", "Ê", "ê", "Ş", "ş", },
{ "S", "s", "$", "4", "Â", "â", "$", "4", "Ë", "ë", "İ", "ı", },
{ "D", "d", "%", "5", "D", "d", "%", "5", "Î", "î", "Ğ", "ğ", },
{ "F", "f", "^", "6", "F", "f", "^", "6", "Ï", "ï", "Ć", "ć", },
{ "G", "g", ":", ";", "G", "g", ":", ";", "Ô", "ô", "Č", "č", },
{ "H", "h", "\"", "'", "H", "h", "\"", "'", "Œ", "œ", "Đ", "đ", },
{ "J", "j", "{", "[", "J", "j", "{", "[", "Ù", "ù", "Š", "š", },
{ "K", "k", "}", "]", "K", "k", "}", "]", "Û", "û", "Ž", "ž", },
{ "L", "l", "_", "-", "Ô", "ô", "_", "-", "Ÿ", "ÿ", "Ő", "ő", },
},
-- third row
{ -- 1 2 3 4 5 6 7 8 9 10 11 12
{ label = "",
width = 1.5
},
{ "Z", "z", "&", "7", "Z", "z", "&", "7", "Á", "á", "Ű", "ű", },
{ "X", "x", "*", "8", "x", "x", "*", "8", "É", "é", "Ø", "ø", },
{ "C", "c", "£", "9", "Ç", "ç", "£", "9", "Í", "í", "Þ", "þ", },
{ "V", "v", "<", "‚", "V", "v", "<", ",", "Ñ", "ñ", "Ý", "ý", },
{ "B", "b", ">", ".", "B", "b", ">", ".", "Ó", "ó", "†", "‡", },
{ "N", "n", "‘", "↑", "N", "n", "‘", "“", "Ú", "ú", "–", "—", },
{ "M", "m", "’", "↓", "M", "m", "’", "”", "Ç", "ç", "…", "¨", },
{ label = "",
width = 1.5,
bold = false
},
},
-- fourth row
{
{ "Sym", "Sym", "ABC", "ABC", "Sym", "Sym", "ABC", "ABC", "Sym", "Sym", "ABC", "ABC",
width = 1.5},
{ label = "🌐", },
{ "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", "Äéß", },
{ label = "space",
" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",
width = 3.0},
{ ",", ",", "“", "←", ",", ",", "Ё", "Ё", ",", ",", ",", ",", },
{ ",", ".", "”", "→", ",", ".", "ё", "ё", ",", ".", ",", ".", },
{ label = "⮠",
"\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n",
width = 1.5,
bold = true
},
},
},
}
| agpl-3.0 |
Lsty/ygopro-scripts | c64496451.lua | 3 | 6015 | --クリフォート・ディスク
function c64496451.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--splimit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e2:SetRange(LOCATION_PZONE)
e2:SetTargetRange(1,0)
e2:SetCondition(aux.nfbdncon)
e2:SetTarget(c64496451.splimit)
c:RegisterEffect(e2)
--atk up
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_PZONE)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetTargetRange(LOCATION_MZONE,0)
e3:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0xaa))
e3:SetValue(300)
c:RegisterEffect(e3)
--summon with no tribute
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(64496451,0))
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e4:SetCode(EFFECT_SUMMON_PROC)
e4:SetCondition(c64496451.ntcon)
c:RegisterEffect(e4)
--change level
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_SUMMON_COST)
e5:SetOperation(c64496451.lvop)
c:RegisterEffect(e5)
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_SINGLE)
e6:SetCode(EFFECT_SPSUMMON_COST)
e6:SetOperation(c64496451.lvop2)
c:RegisterEffect(e6)
--immune
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_SINGLE)
e7:SetCode(EFFECT_IMMUNE_EFFECT)
e7:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_UNCOPYABLE)
e7:SetRange(LOCATION_MZONE)
e7:SetCondition(c64496451.immcon)
e7:SetValue(aux.qlifilter)
c:RegisterEffect(e7)
--summon success
local e8=Effect.CreateEffect(c)
e8:SetDescription(aux.Stringid(64496451,1))
e8:SetCategory(CATEGORY_SPECIAL_SUMMON)
e8:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e8:SetCode(EVENT_SUMMON_SUCCESS)
e8:SetCondition(c64496451.spcon)
e8:SetTarget(c64496451.sptg)
e8:SetOperation(c64496451.spop)
c:RegisterEffect(e8)
--tribute check
local e9=Effect.CreateEffect(c)
e9:SetType(EFFECT_TYPE_SINGLE)
e9:SetCode(EFFECT_MATERIAL_CHECK)
e9:SetValue(c64496451.valcheck)
e9:SetLabelObject(e8)
c:RegisterEffect(e9)
end
function c64496451.splimit(e,c)
return not c:IsSetCard(0xaa)
end
function c64496451.ntcon(e,c,minc)
if c==nil then return true end
return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
end
function c64496451.lvcon(e)
return e:GetHandler():GetMaterialCount()==0
end
function c64496451.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c64496451.lvcon)
e1:SetValue(4)
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_BASE_ATTACK)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c64496451.lvcon)
e2:SetValue(1800)
e2:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e2)
end
function c64496451.lvop2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(4)
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_BASE_ATTACK)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetValue(1800)
e2:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e2)
end
function c64496451.immcon(e)
return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_NORMAL)==SUMMON_TYPE_NORMAL
end
function c64496451.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_ADVANCE and e:GetLabel()==1
end
function c64496451.spfilter(c,e,tp)
return c:IsSetCard(0xaa) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c64496451.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsExistingMatchingCard(c64496451.spfilter,tp,LOCATION_DECK,0,2,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK)
end
function c64496451.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end
local c=e:GetHandler()
local fid=c:GetFieldID()
local g=Duel.GetMatchingGroup(c64496451.spfilter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()>=2 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,2,2,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
sg:GetFirst():RegisterFlagEffect(64496451,RESET_EVENT+0x1fe0000,0,0,fid)
sg:GetNext():RegisterFlagEffect(64496451,RESET_EVENT+0x1fe0000,0,0,fid)
sg:KeepAlive()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetCountLimit(1)
e1:SetLabel(fid)
e1:SetLabelObject(sg)
e1:SetCondition(c64496451.descon)
e1:SetOperation(c64496451.desop)
Duel.RegisterEffect(e1,tp)
end
end
function c64496451.desfilter(c,fid)
return c:GetFlagEffectLabel(64496451)==fid
end
function c64496451.descon(e,tp,eg,ep,ev,re,r,rp)
local g=e:GetLabelObject()
if not g:IsExists(c64496451.desfilter,1,nil,e:GetLabel()) then
g:DeleteGroup()
e:Reset()
return false
else return true end
end
function c64496451.desop(e,tp,eg,ep,ev,re,r,rp)
local g=e:GetLabelObject()
local tg=g:Filter(c64496451.desfilter,nil,e:GetLabel())
Duel.Destroy(tg,REASON_EFFECT)
end
function c64496451.valcheck(e,c)
local g=c:GetMaterial()
if g:IsExists(Card.IsSetCard,1,nil,0xaa) then
e:GetLabelObject():SetLabel(1)
else
e:GetLabelObject():SetLabel(0)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Shield.lua | 9 | 1177 | -----------------------------------
-- Area: Dynamis - Xarcabard
-- Mob: Animated Shield
-----------------------------------
require("scripts/globals/status");
local ID = require("scripts/zones/Dynamis-Xarcabard/IDs");
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(113,1822,1000);
else
SetDropRate(113,1822,0);
end
target:showText(mob,ID.text.ANIMATED_SHIELD_DIALOG);
SpawnMob(17330290):updateEnmity(target);
SpawnMob(17330291):updateEnmity(target);
SpawnMob(17330292):updateEnmity(target);
SpawnMob(17330299):updateEnmity(target);
SpawnMob(17330300):updateEnmity(target);
SpawnMob(17330301):updateEnmity(target);
end;
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
function onMobDisengage(mob)
mob:showText(mob,ID.text.ANIMATED_SHIELD_DIALOG+2);
end;
function onMobDeath(mob, player, isKiller)
player:showText(mob,ID.text.ANIMATED_SHIELD_DIALOG+1);
DespawnMob(17330290);
DespawnMob(17330291);
DespawnMob(17330292);
DespawnMob(17330299);
DespawnMob(17330300);
DespawnMob(17330301);
end; | gpl-3.0 |
Mkalo/forgottenserver | data/chatchannels/scripts/help.lua | 49 | 3126 | local CHANNEL_HELP = 7
local muted = Condition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT)
muted:setParameter(CONDITION_PARAM_SUBID, CHANNEL_HELP)
muted:setParameter(CONDITION_PARAM_TICKS, 3600000)
function onSpeak(player, type, message)
local playerAccountType = player:getAccountType()
if player:getLevel() == 1 and playerAccountType == ACCOUNT_TYPE_NORMAL then
player:sendCancelMessage("You may not speak into channels as long as you are on level 1.")
return false
end
if player:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) then
player:sendCancelMessage("You are muted from the Help channel for using it inappropriately.")
return false
end
if playerAccountType >= ACCOUNT_TYPE_TUTOR then
if string.sub(message, 1, 6) == "!mute " then
local targetName = string.sub(message, 7)
local target = Player(targetName)
if target ~= nil then
if playerAccountType > target:getAccountType() then
if not target:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) then
target:addCondition(muted)
sendChannelMessage(CHANNEL_HELP, TALKTYPE_CHANNEL_R1, target:getName() .. " has been muted by " .. player:getName() .. " for using Help Channel inappropriately.")
else
player:sendCancelMessage("That player is already muted.")
end
else
player:sendCancelMessage("You are not authorized to mute that player.")
end
else
player:sendCancelMessage(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE)
end
return false
elseif string.sub(message, 1, 8) == "!unmute " then
local targetName = string.sub(message, 9)
local target = Player(targetName)
if target ~= nil then
if playerAccountType > target:getAccountType() then
if target:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) then
target:removeCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP)
sendChannelMessage(CHANNEL_HELP, TALKTYPE_CHANNEL_R1, target:getName() .. " has been unmuted by " .. player:getName() .. ".")
else
player:sendCancelMessage("That player is not muted.")
end
else
player:sendCancelMessage("You are not authorized to unmute that player.")
end
else
player:sendCancelMessage(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE)
end
return false
end
end
if type == TALKTYPE_CHANNEL_Y then
if playerAccountType >= ACCOUNT_TYPE_TUTOR or getPlayerFlagValue(player, PlayerFlag_TalkOrangeHelpChannel) then
type = TALKTYPE_CHANNEL_O
end
elseif type == TALKTYPE_CHANNEL_O then
if playerAccountType < ACCOUNT_TYPE_TUTOR and not getPlayerFlagValue(player, PlayerFlag_TalkOrangeHelpChannel) then
type = TALKTYPE_CHANNEL_Y
end
elseif type == TALKTYPE_CHANNEL_R1 then
if playerAccountType < ACCOUNT_TYPE_GAMEMASTER and not getPlayerFlagValue(player, PlayerFlag_CanTalkRedChannel) then
if playerAccountType >= ACCOUNT_TYPE_TUTOR or getPlayerFlagValue(player, PlayerFlag_TalkOrangeHelpChannel) then
type = TALKTYPE_CHANNEL_O
else
type = TALKTYPE_CHANNEL_Y
end
end
end
return type
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/FeiYin/npcs/Seed_Afterglow.lua | 9 | 3232 | -----------------------------------
-- Area: Fei'Yin
-- NPC: Seed Afterglow
-- !pos -94.342 -15.656 -85.889 204 Red
-- !pos -52.019 -16.525 38.848 204 Orange
-- !pos 36.000 -15.000 -35.000 204 Green
-- !pos 74.611 -16.123 134.570 204 Yellow
-- !pos -6.710 0.462 210.245 204 Cerulean
-- !pos -200.000 -15.425 120.000 204 Blue
-- !pos -168.000 0.114 130.000 204 Golden
-- !pos -130.000 0.113 8.000 204 Silver
-- !pos -50.000 0.114 32.000 204 White
-- Todo: NPC moving. In retail these move around with 3-5+ pos EACH
-----------------------------------
local ID = require("scripts/zones/FeiYin/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/npc_util")
require("scripts/globals/status")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local offset = npc:getID() - ID.npc.AFTERGRLOW_OFFSET
local ACP = player:getCurrentMission(ACP)
local currentDay = tonumber(os.date("%j"))
local needToZone = player:needToZone()
local progressMask = player:getCharVar("SEED_AFTERGLOW_MASK")
local intensity = player:getCharVar("SEED_AFTERGLOW_INTENSITY")
if (
player:hasKeyItem(dsp.ki.MARK_OF_SEED) or
player:hasKeyItem(dsp.ki.AZURE_KEY) or
player:hasKeyItem(dsp.ki.IVORY_KEY) or
CurrentDay == player:getCharVar("LastAzureKey") or
CurrentDay == player:getCharVar("LastIvoryKey") or
ACP < dsp.mission.id.acp.THOSE_WHO_LURK_IN_SHADOWS_II
) then
player:messageSpecial(ID.text.SOFTLY_SHIMMERING_LIGHT)
elseif (needToZone and not player:hasStatusEffect(dsp.effect.MARK_OF_SEED)) then
player:messageSpecial(ID.text.YOU_REACH_FOR_THE_LIGHT)
elseif (ACP >= dsp.mission.id.acp.THOSE_WHO_LURK_IN_SHADOWS_II and not player:getMaskBit(progressMask, offset)) then
player:setMaskBit(progressMask, "SEED_AFTERGLOW_MASK", offset, true)
intensity = intensity + 1
if (intensity == 9) then
player:startEvent(28)
elseif (not needToZone and not player:hasStatusEffect(dsp.effect.MARK_OF_SEED)) then
player:setCharVar("SEED_AFTERGLOW_INTENSITY", intensity)
player:messageSpecial(ID.text.YOU_REACH_OUT_TO_THE_LIGHT, 0)
player:addStatusEffectEx(dsp.effect.MARK_OF_SEED, 0, 0, 30, 1800)
player:needToZone(true)
player:messageSpecial(ID.text.THE_LIGHT_DWINDLES, 0)
else
player:setCharVar("SEED_AFTERGLOW_INTENSITY", intensity)
player:messageSpecial(ID.text.EVEN_GREATER_INTENSITY, offset)
end
else
player:messageSpecial(ID.text.SOFTLY_SHIMMERING_LIGHT)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 28 then
player:delStatusEffectSilent(dsp.effect.MARK_OF_SEED)
if option == 100 then
player:messageSpecial(ID.text.SCINTILLATING_BURST_OF_LIGHT)
npcUtil.giveKeyItem(player, dsp.ki.MARK_OF_SEED)
elseif option == 200 then
npcUtil.giveKeyItem(player, dsp.ki.AZURE_KEY)
end
end
end
| gpl-3.0 |
mortezamosavy999/zetaindex | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
AL-JOKER/AL.JOKER | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-3.0 |
ara8586/9900 | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | agpl-3.0 |
Lsty/ygopro-scripts | c42009836.lua | 5 | 1129 | --フォッシル・ダイナ パキケファロ
function c42009836.initial_effect(c)
--disable spsummon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,1)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(42009836,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_FLIP)
e2:SetTarget(c42009836.target)
e2:SetOperation(c42009836.operation)
c:RegisterEffect(e2)
end
function c42009836.filter(c)
return bit.band(c:GetSummonType(),SUMMON_TYPE_SPECIAL)~=0
end
function c42009836.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local g=Duel.GetMatchingGroup(c42009836.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c42009836.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c42009836.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Carpenters_Landing/npcs/Guilloud.lua | 9 | 1060 | -----------------------------------
-- Area: Carpenters' Landing
-- NPC: Guilloud
-- Involved with mission "The Road Forks"
-- !pos -123.770 -6.654 -469.062 2
-----------------------------------
local ID = require("scripts/zones/Carpenters_Landing/IDs")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local cop = player:getCurrentMission(COP)
local emeraldWaterStatus = player:getCharVar("EMERALD_WATERS_Status")
if cop == dsp.mission.id.cop.THE_ROAD_FORKS and emeraldWaterStatus == 4 and not GetMobByID(ID.mob.OVERGROWN_IVY):isSpawned() then
SpawnMob(ID.mob.OVERGROWN_IVY):updateClaim(player)
elseif cop == dsp.mission.id.cop.THE_ROAD_FORKS and emeraldWaterStatus == 5 then
player:startEvent(0)
else
player:startEvent(1)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 0 then
player:setCharVar("EMERALD_WATERS_Status", 6)
end
end | gpl-3.0 |
Lsty/ygopro-scripts | c23693634.lua | 9 | 1911 | --ギガンテック・ファイター
function c23693634.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--Atk up
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(c23693634.atkval)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(23693634,0))
e2:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetCode(EVENT_BATTLE_DESTROYED)
e2:SetCondition(c23693634.sumcon)
e2:SetTarget(c23693634.sumtg)
e2:SetOperation(c23693634.sumop)
c:RegisterEffect(e2)
end
function c23693634.atkval(e,c)
return Duel.GetMatchingGroupCount(Card.IsRace,c:GetControler(),LOCATION_GRAVE,LOCATION_GRAVE,nil,RACE_WARRIOR)*100
end
function c23693634.sumcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetLocation()==LOCATION_GRAVE
and bit.band(e:GetHandler():GetReason(),REASON_BATTLE)~=0
end
function c23693634.filter(c,e,tp)
return c:IsRace(RACE_WARRIOR) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c23693634.sumtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and c23693634.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c23693634.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c23693634.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c23693634.sumop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
npge/alnbox | spec/alnwindow_spec.lua | 2 | 1819 | -- alnbox, alignment viewer based on the curses library
-- Copyright (C) 2015 Boris Nagaev
-- See the LICENSE file for terms of use
local function sleep()
local duration = os.getenv('TEST_SLEEP') or 5
os.execute('sleep ' .. duration)
end
local function startCode(rt, code)
if type(code) == 'function' then
code = string.dump(code)
end
local fname = os.tmpname()
local f = io.open(fname, 'w')
f:write(code)
f:close()
local lluacov = os.getenv('LOAD_LUACOV') or ''
local cmd = 'lua %s %s; rm %s'
cmd = cmd:format(lluacov, fname, fname)
rt:forkPty(cmd)
end
describe("alnbox.alnwindow", function()
it("draws simple alignment in a curses window", function()
local rote = require 'rote'
local rt = rote.RoteTerm(24, 80)
startCode(rt, function()
local curses = require 'curses'
local initializeCurses = require 'alnbox.initializeCurses'
local stdscr = initializeCurses(curses)
local nlines = 1
local ncols = 1
local begin_y = 2
local begin_x = 5
local win = stdscr:derive(nlines, ncols,
begin_y, begin_x)
local alnwindow = require 'alnbox.alnwindow'
local aw = alnwindow(win, {rows = 1, cols = 1,
getCell = function() return 'X' end})
local navigate = require 'alnbox.navigate'
local refresh = function() win:refresh() end
local getch = function() return win:getch() end
navigate(aw, refresh, getch, nil, curses)
curses.endwin()
end)
sleep()
rt:update()
local begin_y = 2
local begin_x = 5
assert.equal('X', rt:cellChar(begin_y, begin_x))
rt:write('q')
end)
end)
| mit |
Lsty/ygopro-scripts | c75937826.lua | 3 | 2623 | --巨大戦艦 ビッグ・コアMk-II
function c75937826.initial_effect(c)
--spsummon success
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(75937826,0))
e1:SetCategory(CATEGORY_COUNTER)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetTarget(c75937826.addct)
e1:SetOperation(c75937826.addc)
c:RegisterEffect(e1)
--indes
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetValue(1)
c:RegisterEffect(e2)
--remove counter
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(75937826,1))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_DAMAGE_STEP_END)
e3:SetCondition(c75937826.rctcon)
e3:SetOperation(c75937826.rctop)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(75937826,2))
e4:SetCategory(CATEGORY_DESTROY)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_DAMAGE_STEP_END)
e4:SetCondition(c75937826.descon)
e4:SetTarget(c75937826.destg)
e4:SetOperation(c75937826.desop)
c:RegisterEffect(e4)
--summon with no tribute
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(75937826,3))
e5:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_SUMMON_PROC)
e5:SetCondition(c75937826.ntcon)
c:RegisterEffect(e5)
end
function c75937826.addct(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,3,0,0x1f)
end
function c75937826.addc(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
e:GetHandler():AddCounter(0x1f,3)
end
end
function c75937826.rctcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetCounter(0x1f)~=0
end
function c75937826.rctop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
c:RemoveCounter(tp,0x1f,1,REASON_EFFECT)
end
end
function c75937826.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetCounter(0x1f)==0
end
function c75937826.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c75937826.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
Duel.Destroy(c,REASON_EFFECT)
end
end
function c75937826.ntcon(e,c,minc)
if c==nil then return true end
return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.GetFieldGroupCount(c:GetControler(),LOCATION_MZONE,0)==0
end
| gpl-2.0 |
Lsty/ygopro-scripts | c31766317.lua | 5 | 2505 | --ヘル・エンプレス・デーモン
function c31766317.initial_effect(c)
--destroy replace
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DESTROY_REPLACE)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c31766317.destg)
e1:SetValue(1)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(31766317,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c31766317.spcon)
e2:SetTarget(c31766317.sptg)
e2:SetOperation(c31766317.spop)
c:RegisterEffect(e2)
end
function c31766317.rfilter(c)
return c:IsRace(RACE_FIEND) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsAbleToRemove()
end
function c31766317.destg(e,tp,eg,ep,ev,re,r,rp,chk)
local dc=eg:GetFirst()
if chk==0 then return eg:GetCount()==1 and dc~=e:GetHandler() and dc:IsFaceup() and dc:IsLocation(LOCATION_MZONE)
and dc:IsRace(RACE_FIEND) and dc:IsAttribute(ATTRIBUTE_DARK)
and Duel.IsExistingMatchingCard(c31766317.rfilter,tp,LOCATION_GRAVE,0,1,nil) end
if Duel.SelectYesNo(tp,aux.Stringid(31766317,0)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c31766317.rfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
return true
else return false end
end
function c31766317.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY) and bit.band(e:GetHandler():GetPreviousLocation(),LOCATION_ONFIELD)~=0
end
function c31766317.filter(c,e,tp)
return c:IsRace(RACE_FIEND) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsLevelAbove(6)
and c:GetCode()~=31766317 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c31766317.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c31766317.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c31766317.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c31766317.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c31766317.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/pathfind.lua | 14 | 3143 | ------------------------------------
--
-- NPC PATH WALKING
--
------------------------------------
dsp = dsp or {}
dsp.path =
{
flag =
{
NONE = 0,
RUN = 1,
WALLHACK = 2,
REVERSE = 4,
},
-- returns the point at the given index
get = function(points, index)
local pos = {}
if index < 0 then
index = (#points + index - 2) / 3
end
pos[1] = points[index*3-2]
pos[2] = points[index*3-1]
pos[3] = points[index*3]
return pos
end,
-- returns number of points in given path
length = function(points)
return #points / 3
end,
-- returns first point in given path
first = function(points)
return dsp.path.get(points, 1)
end,
-- are two points the same?
equal = function(point1, point2)
return point1[1] == point2[1] and point1[2] == point2[2] and point1[3] == point2[3]
end,
-- returns last point in given path
last = function(points)
local length = dsp.path.length(points)
return dsp.path.get(points, length)
end,
-- returns random point from given path
random = function(points)
local length = dsp.path.length(points)
return dsp.path.get(points, math.random(length))
end,
-- returns the start path without the first element
fromStart = function(points, start)
start = start or 1
local t2 = {}
local maxLength = 50
local length = dsp.path.length(points)
local count = 1
local pos = start + 1
local index = 1
while pos <= length and count <= maxLength do
local pt = dsp.path.get(points, pos)
t2[index] = pt[1]
t2[index+1] = pt[2]
t2[index+2] = pt[3]
pos = pos + 1
count = count + 1
index = index + 3
end
return t2
end,
-- reverses the array and removes the first element
fromEnd = function(points, start)
start = start or 1
local t2 = {}
local length = dsp.path.length(points)
start = length - start
local index = 1
for i = start, 1, -1 do
local pt = dsp.path.get(points, i)
t2[index] = pt[1]
t2[index+1] = pt[2]
t2[index+2] = pt[3]
index = index + 3
if i > 50 then
break
end
end
return t2
end,
-- continusly run the path
patrol = function(npc, points, flags)
if npc:atPoint(dsp.path.first(points)) or npc:atPoint(dsp.path.last(points)) then
npc:pathThrough(dsp.path.fromStart(points), flags)
else
local length = dsp.path.length(points)
local currentLength = 0
local i = 51
while(i <= length) do
if npc:atPoint(dsp.path.get(points, i)) then
npc:pathThrough(dsp.path.fromStart(points, i), flags)
break
end
i = i + 50
end
end
end
} | gpl-3.0 |
MalRD/darkstar | scripts/globals/items/dark_bass.lua | 11 | 1047 | -----------------------------------------
-- ID: 4428
-- Item: dark_bass
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:getRace() ~= dsp.race.MITHRA) then
result = dsp.msg.basic.CANNOT_EAT
end
if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then
result = 0
end
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,300,4428)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.DEX, 2)
target:addMod(dsp.mod.MND, -4)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 2)
target:delMod(dsp.mod.MND, -4)
end
| gpl-3.0 |
Frenzie/koreader | spec/unit/device_spec.lua | 1 | 16123 | describe("device module", function()
-- luacheck: push ignore
local mock_fb, mock_input
local iopen = io.open
local ipopen = io.popen
local osgetenv = os.getenv
local ffi, C
setup(function()
mock_fb = {
new = function()
return {
getRawSize = function() return {w = 600, h = 800} end,
getWidth = function() return 600 end,
getDPI = function() return 72 end,
setViewport = function() end,
getRotationMode = function() return 0 end,
getScreenMode = function() return "portrait" end,
setRotationMode = function() end,
scaleByDPI = function(this, dp) return math.ceil(dp * this:getDPI() / 160) end,
}
end
}
require("commonrequire")
package.unloadAll()
ffi = require("ffi")
C = ffi.C
require("ffi/linux_input_h")
require("document/canvascontext"):init(require("device"))
end)
before_each(function()
package.loaded['ffi/framebuffer_mxcfb'] = mock_fb
mock_input = require('device/input')
stub(mock_input, "open")
stub(os, "getenv")
stub(os, "execute")
end)
after_each(function()
mock_input.open:revert()
os.getenv:revert()
os.execute:revert()
os.getenv = osgetenv
io.open = iopen
io.popen = ipopen
end)
describe("kobo", function()
local time
local NickelConf
setup(function()
time = require("ui/time")
NickelConf = require("device/kobo/nickel_conf")
end)
before_each(function()
stub(NickelConf.frontLightLevel, "get")
NickelConf.frontLightLevel.get.returns(0)
stub(NickelConf.frontLightState, "get")
end)
after_each(function()
NickelConf.frontLightLevel.get:revert()
NickelConf.frontLightState.get:revert()
end)
it("should initialize properly on Kobo dahlia", function()
os.getenv.returns("dahlia")
local kobo_dev = require("device/kobo/device")
kobo_dev:init()
assert.is.same("Kobo_dahlia", kobo_dev.model)
end)
it("should setup eventAdjustHooks properly for input on trilogy C", function()
os.getenv.invokes(function(key)
if key == "PRODUCT" then
return "trilogy"
elseif key == "MODEL_NUMBER" then
return "320"
else
return osgetenv(key)
end
end)
package.loaded['device/kobo/device'] = nil
local kobo_dev = require("device/kobo/device")
kobo_dev:init()
local Screen = kobo_dev.screen
assert.is.same("Kobo_trilogy_C", kobo_dev.model)
assert.falsy(kobo_dev:needsTouchScreenProbe())
local x, y = Screen:getWidth()-5, 10
-- mirror x, then switch_xy
local ev_x = {
type = C.EV_ABS,
code = C.ABS_X,
value = y,
time = time:realtime(),
}
local ev_y = {
type = C.EV_ABS,
code = C.ABS_Y,
value = Screen:getWidth() - 1 - x,
time = time:realtime(),
}
kobo_dev.input:eventAdjustHook(ev_x)
kobo_dev.input:eventAdjustHook(ev_y)
assert.is.same(x, ev_y.value)
assert.is.same(C.ABS_X, ev_y.code)
assert.is.same(y, ev_x.value)
assert.is.same(C.ABS_Y, ev_x.code)
-- reset eventAdjustHook
kobo_dev.input.eventAdjustHook = function() end
end)
it("should setup eventAdjustHooks properly for trilogy with non-epoch ev time", function()
-- This has no more value since #6798 as ev time can now stay
-- non-epoch. Adjustments are made on first event handled, and
-- have only effects when handling long-press (so, the long-press
-- for dict lookup tests with test this).
-- We just check here it still works with non-epoch ev time, as previous test
os.getenv.invokes(function(key)
if key == "PRODUCT" then
return "trilogy"
elseif key == "MODEL_NUMBER" then
return "320"
else
return osgetenv(key)
end
end)
package.loaded['device/kobo/device'] = nil
local kobo_dev = require("device/kobo/device")
kobo_dev:init()
local Screen = kobo_dev.screen
assert.is.same("Kobo_trilogy_C", kobo_dev.model)
assert.falsy(kobo_dev:needsTouchScreenProbe())
local x, y = Screen:getWidth()-5, 10
local ev_x = {
type = C.EV_ABS,
code = C.ABS_X,
value = y,
time = {sec = 1000}
}
local ev_y = {
type = C.EV_ABS,
code = C.ABS_Y,
value = Screen:getWidth() - 1 - x,
time = {sec = 1000}
}
kobo_dev.input:eventAdjustHook(ev_x)
kobo_dev.input:eventAdjustHook(ev_y)
assert.is.same(x, ev_y.value)
assert.is.same(C.ABS_X, ev_y.code)
assert.is.same(y, ev_x.value)
assert.is.same(C.ABS_Y, ev_x.code)
-- reset eventAdjustHook
kobo_dev.input.eventAdjustHook = function() end
end)
end)
describe("kindle", function()
it("should initialize voyage without error", function()
io.open = function(filename, mode)
if filename == "/proc/usid" then
return {
read = function() return "B013XX" end,
close = function() end
}
else
return iopen(filename, mode)
end
end
local kindle_dev = require('device/kindle/device')
assert.is.same(kindle_dev.model, "KindleVoyage")
kindle_dev:init()
assert.is.same(kindle_dev.input.event_map[104], "LPgBack")
assert.is.same(kindle_dev.input.event_map[109], "LPgFwd")
assert.is.same(kindle_dev.powerd.fl_min, 0)
-- NOTE: fl_max + 1 since #5989
assert.is.same(kindle_dev.powerd.fl_max, 25)
end)
it("should toggle frontlight", function()
io.open = function(filename, mode)
if filename == "/proc/usid" then
return {
read = function() return "B013XX" end,
close = function() end
}
elseif filename == "/sys/class/backlight/max77696-bl/brightness" then
return {
read = function() return 12 end,
close = function() end
}
else
return iopen(filename, mode)
end
end
local kindle_dev = require("device/kindle/device")
kindle_dev:init()
assert.is.same(kindle_dev.powerd.fl_intensity, 12)
kindle_dev.powerd:setIntensity(5)
assert.is.same(kindle_dev.powerd.fl_intensity, 5)
kindle_dev.powerd:toggleFrontlight()
assert.stub(os.execute).was_called_with(
"printf '%s' 0 > /sys/class/backlight/max77696-bl/brightness")
-- Here be shenanigans: we don't override powerd's fl_intensity when we turn the light off,
-- so that we can properly turn it back on at the previous intensity ;)
assert.is.same(kindle_dev.powerd.fl_intensity, 5)
-- But if we were to cat /sys/class/backlight/max77696-bl/brightness, it should now be 0.
kindle_dev.powerd:toggleFrontlight()
assert.is.same(kindle_dev.powerd.fl_intensity, 5)
-- And /sys/class/backlight/max77696-bl/brightness is now !0
-- (exact value is HW-dependent, each model has a different curve, we let lipc do the work for us).
end)
it("oasis should interpret orientation event", function()
package.unload('device/kindle/device')
io.open = function(filename, mode)
if filename == "/proc/usid" then
return {
read = function()
return "G0B0GCXXX"
end,
close = function() end
}
else
return iopen(filename, mode)
end
end
mock_ffi_input = require('ffi/input')
stub(mock_ffi_input, "waitForEvent")
mock_ffi_input.waitForEvent.returns(true, {
{
type = C.EV_ABS,
time = {
usec = 450565,
sec = 1471081881
},
code = 24, -- C.ABS_PRESSURE -> ABS_OASIS_ORIENTATION
value = 16
}
})
local UIManager = require("ui/uimanager")
stub(UIManager, "onRotation")
local kindle_dev = require('device/kindle/device')
assert.is.same("KindleOasis", kindle_dev.model)
kindle_dev:init()
kindle_dev:lockGSensor(true)
kindle_dev.input:waitEvent()
assert.stub(UIManager.onRotation).was_called()
mock_ffi_input.waitForEvent:revert()
UIManager.onRotation:revert()
end)
end)
describe("Flush book Settings for", function()
it("Kobo", function()
os.getenv.invokes(function(key)
if key == "PRODUCT" then
return "trilogy"
else
return osgetenv(key)
end
end)
local sample_pdf = "spec/front/unit/data/tall.pdf"
local ReaderUI = require("apps/reader/readerui")
local device_to_test = require("device/kobo/device")
local Device = require("device")
Device.setEventHandlers = device_to_test.setEventHandlers
local UIManager = require("ui/uimanager")
stub(Device, "suspend")
stub(Device.powerd, "beforeSuspend")
stub(Device, "isKobo")
Device.isKobo.returns(true)
UIManager:init()
ReaderUI:doShowReader(sample_pdf)
local readerui = ReaderUI._getRunningInstance()
stub(readerui, "onFlushSettings")
UIManager.event_handlers.PowerPress()
UIManager.event_handlers.PowerRelease()
assert.stub(readerui.onFlushSettings).was_called()
Device.suspend:revert()
Device.powerd.beforeSuspend:revert()
Device.isKobo:revert()
readerui.onFlushSettings:revert()
Device.screen_saver_mode = false
readerui:onClose()
end)
it("Cervantes", function()
io.popen = function(filename, mode)
if filename:find("/usr/bin/ntxinfo") then
return {
read = function()
return 68 -- Cervantes4
end,
close = function() end
}
else
return ipopen(filename, mode)
end
end
local sample_pdf = "spec/front/unit/data/tall.pdf"
local ReaderUI = require("apps/reader/readerui")
local Device = require("device")
local device_to_test = require("device/cervantes/device")
Device.setEventHandlers = device_to_test.setEventHandlers
local UIManager = require("ui/uimanager")
stub(Device, "suspend")
stub(Device.powerd, "beforeSuspend")
stub(Device, "isCervantes")
Device.isCervantes.returns(true)
UIManager:init()
ReaderUI:doShowReader(sample_pdf)
local readerui = ReaderUI._getRunningInstance()
stub(readerui, "onFlushSettings")
UIManager.event_handlers.PowerPress()
UIManager.event_handlers.PowerRelease()
assert.stub(readerui.onFlushSettings).was_called()
Device.suspend:revert()
Device.powerd.beforeSuspend:revert()
Device.isCervantes:revert()
Device.screen_saver_mode = false
readerui.onFlushSettings:revert()
readerui:onClose()
end)
it("SDL", function()
local sample_pdf = "spec/front/unit/data/tall.pdf"
local ReaderUI = require("apps/reader/readerui")
local Device = require("device")
local device_to_test = require("device/sdl/device")
Device.setEventHandlers = device_to_test.setEventHandlers
local UIManager = require("ui/uimanager")
stub(Device, "suspend")
stub(Device.powerd, "beforeSuspend")
stub(Device, "isSDL")
Device.isSDL.returns(true)
UIManager:init()
ReaderUI:doShowReader(sample_pdf)
local readerui = ReaderUI._getRunningInstance()
stub(readerui, "onFlushSettings")
UIManager.event_handlers.PowerPress()
UIManager.event_handlers.PowerRelease()
assert.stub(readerui.onFlushSettings).was_called()
Device.suspend:revert()
Device.powerd.beforeSuspend:revert()
Device.isSDL:revert()
Device.screen_saver_mode = false
readerui.onFlushSettings:revert()
readerui:onClose()
end)
it("Remarkable", function()
io.open = function(filename, mode)
if filename == "/usr/bin/xochitl" then
return {
read = function()
return true
end,
close = function() end
}
elseif filename == "/sys/devices/soc0/machine" then
return {
read = function()
return "reMarkable", "generic"
end,
close = function() end
}
else
return iopen(filename, mode)
end
end
local sample_pdf = "spec/front/unit/data/tall.pdf"
local ReaderUI = require("apps/reader/readerui")
local Device = require("device")
local device_to_test = require("device/remarkable/device")
Device.setEventHandlers = device_to_test.setEventHandlers
local UIManager = require("ui/uimanager")
stub(Device, "suspend")
stub(Device.powerd, "beforeSuspend")
stub(Device, "isRemarkable")
Device.isRemarkable.returns(true)
UIManager:init()
ReaderUI:doShowReader(sample_pdf)
local readerui = ReaderUI._getRunningInstance()
stub(readerui, "onFlushSettings")
UIManager.event_handlers.PowerPress()
UIManager.event_handlers.PowerRelease()
assert.stub(readerui.onFlushSettings).was_called()
Device.suspend:revert()
Device.powerd.beforeSuspend:revert()
Device.isRemarkable:revert()
Device.screen_saver_mode = false
readerui.onFlushSettings:revert()
readerui:onClose()
end)
end)
-- luacheck: pop
end)
| agpl-3.0 |
mrbangi/ww_WW_ww | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
CommandPost/CommandPost-App | extensions/network/network_reachability.lua | 4 | 4367 | --- === hs.network.reachability ===
---
--- This sub-module can be used to determine the reachability of a target host. A remote host is considered reachable when a data packet, sent by an application into the network stack, can leave the local device. Reachability does not guarantee that the data packet will actually be received by the host.
---
--- It is important to remember that this module works by determining if the computer has a route for network traffic bound to a specific destination. An active internet connection provides a default route for any network that the host is not a member of, so care must be used when testing for specific VPN or local networks to avoid false positives. Some examples follow:
---
--- This is a simple watcher which will be invoked whenever the computer's active internet connection changes state:
--- ~~~
--- hs.network.reachability.internet():setCallback(function(self, flags)
--- if (flags & hs.network.reachability.flags.reachable) > 0 then
--- -- a default route exists, so an active internet connection is present
--- else
--- -- no default route exists, so no active internet connection is present
--- end
--- end):start()
--- ~~~
---
--- Note that when an active internet connection is up (reachable), any specific network test that does not include an address pair will be reachable, since internet reachability is defined as having a default route for all non-local networks.
---
--- A specific test for determining if an OpenVPN network is available. This example requires knowing what the local computer's IP address on the VPN network is (OpenVPN does not set the `isDirect` flag) and has been tested with Tunnelblick.
--- ~~~
--- hs.network.reachability.forAddress("10.x.y.z"):setCallback(function(self, flags)
--- -- note that because having an internet connection at all will show the remote network
--- -- as "reachable", we instead look at whether or not our specific address is "local" instead
--- if (flags & hs.network.reachability.flags.isLocalAddress) > 0 then
--- -- VPN tunnel is up
--- else
--- -- VPN tunnel is down
--- end
--- end):start()
--- ~~~
local USERDATA_TAG = "hs.network.reachability"
local module = require("hs.libnetworkreachability")
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
module.flags = ls.makeConstantsTable(module.flags)
module.specialAddresses = ls.makeConstantsTable({
IN_LINKLOCALNETNUM = 0xA9FE0000, -- 169.254.0.0
INADDR_ANY = 0x00000000, -- 0.0.0.0
})
--- hs.network.reachability.internet() -> reachabilityObject
--- Constructor
--- Creates a reachability object for testing internet access
---
--- Parameters:
--- * None
---
--- Returns:
--- * a reachability object
---
--- Notes:
--- * This is equivalent to `hs.network.reachability.forAddress("0.0.0.0")`
--- * This constructor assumes that a default route for IPv4 traffic is sufficient to determine internet access. If you are on an IPv6 only network which does not also provide IPv4 route mapping, you should probably use something along the lines of `hs.network.reachability.forAddress("::")` instead.
module.internet = function()
return module.forAddress(module.specialAddresses.INADDR_ANY)
end
--- hs.network.reachability.linkLocal() -> reachabilityObject
--- Constructor
--- Creates a reachability object for testing IPv4 link local networking
---
--- Parameters:
--- * None
---
--- Returns:
--- * a reachability object
---
--- Notes:
--- * This is equivalent to `hs.network.reachability.forAddress("169.254.0.0")`
--- * You can use this to determine if any interface has an IPv4 link local address (i.e. zero conf or local only networking) by checking the "isDirect" flag:
--- * `hs.network.reachability.linklocal():status() & hs.network.reachability.flags.isDirect`
--- * If the internet is reachable, then this network will also be reachable by default -- use the isDirect flag to ensure that the route is local.
module.linklocal = function()
return module.forAddress(module.specialAddresses.IN_LINKLOCALNETNUM)
end
-- Return Module Object --------------------------------------------------
return module
| mit |
MalRD/darkstar | scripts/zones/Mount_Zhayolm/mobs/Claret.lua | 11 | 1298 | -----------------------------------
-- Area: Mount Zhayolm
-- ZNM: Claret
-- !pos 501 -9 53
-- Spawned with Pectin: !additem 2591
-- Wiki: http://ffxiclopedia.wikia.com/wiki/Claret
-----------------------------------
mixins = {require("scripts/mixins/rage")}
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(dsp.mobMod.IDLE_DESPAWN, 300)
end
function onMobSpawn(mob)
mob:setLocalVar("[rage]timer", 3600) -- 60 minutes
mob:addMod(dsp.mod.REGEN, math.floor(mob:getMaxHP()*.004))
mob:addMod(dsp.mod.BINDRES, 40)
mob:addMod(dsp.mod.MOVE, 15)
mob:SetAutoAttackEnabled(false)
end
function onMobFight(mob, target)
if mob:checkDistance(target) < 3 then
if not target:hasStatusEffect(dsp.effect.POISON) then
target:addStatusEffect(dsp.effect.POISON, 100, 3, math.random(3, 6) * 3) -- Poison for 3-6 ticks.
else
if target:getStatusEffect(dsp.effect.POISON):getPower() < 100 then
target:delStatusEffect(dsp.effect.POISON)
target:addStatusEffect(dsp.effect.POISON, 100, 3, math.random(3, 6) * 3) -- Poison for 3-6 ticks.
end
end
end
end
function onMobDeath(mob, player, isKiller)
end | gpl-3.0 |
MalRD/darkstar | scripts/globals/items/viking_herring.lua | 11 | 1267 | -----------------------------------------
-- ID: 5183
-- Item: viking_herring
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 4
-- Mind -3
-- Attack % 12 (cap 75)
-- Ranged ATT % 12 (cap 75)
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,3600,5183)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, 4)
target:addMod(dsp.mod.MND, -3)
target:addMod(dsp.mod.FOOD_ATTP, 12)
target:addMod(dsp.mod.FOOD_ATT_CAP, 75)
target:addMod(dsp.mod.FOOD_RATTP, 12)
target:addMod(dsp.mod.FOOD_RATT_CAP, 75)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 4)
target:delMod(dsp.mod.MND, -3)
target:delMod(dsp.mod.FOOD_ATTP, 12)
target:delMod(dsp.mod.FOOD_ATT_CAP, 75)
target:delMod(dsp.mod.FOOD_RATTP, 12)
target:delMod(dsp.mod.FOOD_RATT_CAP, 75)
end
| gpl-3.0 |
CommandPost/CommandPost-App | extensions/menubar/menubar.lua | 4 | 1541 | --- === hs.menubar ===
---
--- Create and manage menubar icons
local menubar = require "hs.libmenubar"
local imagemod = require("hs.image")
local geometry = require "hs.geometry"
local screen = require "hs.screen"
require("hs.styledtext")
-- protects tables of constants
menubar.imagePositions = ls.makeConstantsTable(menubar.imagePositions)
-- This is the wrapper for hs.menubar:setIcon(). It is documented in internal.m
local menubarObject = hs.getObjectMetatable("hs.menubar")
menubarObject.setIcon = function(object, imagePath, template)
local tmpImage = nil
if type(imagePath) == "userdata" then
tmpImage = imagePath
elseif type(imagePath) == "string" then
if string.sub(imagePath, 1, 6) == "ASCII:" then
tmpImage = imagemod.imageFromASCII(string.sub(imagePath, 7, -1))
else
tmpImage = imagemod.imageFromPath(imagePath)
end
end
return object:_setIcon(tmpImage, template)
end
--- hs.menubar:frame() -> hs.geometry rect
--- Method
--- Returns the menubar item frame
---
--- Parameters:
--- * None
---
--- Returns:
--- * an hs.geometry rect describing the menubar item's frame or nil if the menubar item is not currently in the menubar.
---
--- Notes:
--- * This will return a frame even if no icon or title is set
function menubarObject:frame()
local sf = screen.mainScreen():fullFrame()
local f = self:_frame()
if f then
f.y = sf.h - f.y - f.h
return geometry(f)
else
return nil
end
end
return menubar
| mit |
Frenzie/koreader | frontend/ui/widget/screenshoter.lua | 4 | 4437 | local BD = require("ui/bidi")
local ConfirmBox = require("ui/widget/confirmbox")
local MultiConfirmBox = require("ui/widget/multiconfirmbox")
local DataStorage = require("datastorage")
local GestureRange = require("ui/gesturerange")
local InputContainer = require("ui/widget/container/inputcontainer")
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local T = require("ffi/util").template
local _ = require("gettext")
local Screenshoter = InputContainer:extend{
prefix = 'Screenshot',
}
function Screenshoter:init()
local diagonal = math.sqrt(Screen:getWidth()^2 + Screen:getHeight()^2)
self.ges_events = {
TapDiagonal = {
GestureRange:new{
ges = "two_finger_tap",
scale = {diagonal - Screen:scaleBySize(200), diagonal},
rate = 1.0,
}
},
SwipeDiagonal = {
GestureRange:new{
ges = "swipe",
scale = {diagonal - Screen:scaleBySize(200), diagonal},
rate = 1.0,
}
},
}
end
function Screenshoter:onScreenshot(filename, when_done_func)
local screenshots_dir = G_reader_settings:readSetting("screenshot_dir") or DataStorage:getDataDir() .. "/screenshots/"
self.screenshot_fn_fmt = screenshots_dir .. self.prefix .. "_%Y-%m-%d_%H%M%S.png"
local screenshot_name = filename or os.date(self.screenshot_fn_fmt)
Screen:shot(screenshot_name)
local confirm_box
confirm_box = ConfirmBox:new{
text = T( _("Screenshot saved to:\n%1"), BD.filepath(screenshot_name)),
keep_dialog_open = true,
flush_events_on_show = true, -- may be invoked with 2-fingers tap, accidental additional events can happen
cancel_text = _("Close"),
cancel_callback = function()
if when_done_func then when_done_func() end
end,
ok_text = _("Set as screensaver"),
ok_callback = function()
G_reader_settings:saveSetting("screensaver_type", "image_file")
G_reader_settings:saveSetting("screensaver_image", screenshot_name)
UIManager:close(confirm_box)
if when_done_func then when_done_func() end
end,
other_buttons_first = true,
other_buttons = {{
{
text = _("Delete"),
callback = function()
local __ = os.remove(screenshot_name)
UIManager:close(confirm_box)
if when_done_func then when_done_func() end
end,
},
{
text = _("View"),
callback = function()
local image_viewer = require("ui/widget/imageviewer"):new{
file = screenshot_name,
modal = true,
with_title_bar = false,
buttons_visible = true,
}
UIManager:show(image_viewer)
end,
},
}},
}
UIManager:show(confirm_box)
-- trigger full refresh
UIManager:setDirty(nil, "full")
return true
end
function Screenshoter:chooseFolder()
local screenshot_dir_default = DataStorage:getFullDataDir() .. "/screenshots/"
local screenshot_dir = G_reader_settings:readSetting("screenshot_dir") or screenshot_dir_default
local confirm_box = MultiConfirmBox:new{
text = T(_("Screenshot folder is set to:\n%1\n\nChoose a new folder for screenshots?"), screenshot_dir),
choice1_text = _("Use default"),
choice1_callback = function()
G_reader_settings:saveSetting("screenshot_dir", screenshot_dir_default)
end,
choice2_text = _("Choose folder"),
choice2_callback = function()
local path_chooser = require("ui/widget/pathchooser"):new{
select_file = false,
show_files = false,
path = screenshot_dir,
onConfirm = function(new_path)
G_reader_settings:saveSetting("screenshot_dir", new_path .. "/")
end
}
UIManager:show(path_chooser)
end,
}
UIManager:show(confirm_box)
end
function Screenshoter:onTapDiagonal()
return self:onScreenshot()
end
function Screenshoter:onSwipeDiagonal()
return self:onScreenshot()
end
return Screenshoter
| agpl-3.0 |
todotodoo/skia | tools/lua/classify_rrect_clips.lua | 160 | 3346 |
function sk_scrape_startcanvas(c, fileName) end
function sk_scrape_endcanvas(c, fileName) end
function classify_rrect(rrect)
if (rrect:type() == "simple") then
local x, y = rrect:radii(0)
if (x == y) then
return "simple_circle"
else
return "simple_oval"
end
elseif (rrect:type() == "complex") then
local numNotSquare = 0
local rx, ry
local same = true;
local first_not_square_corner
local last_not_square_corner
for i = 1, 4 do
local x, y = rrect:radii(i-1)
if (x ~= 0 and y ~= 0) then
if (numNotSquare == 0) then
rx = x
ry = y
first_not_square_corner = i
else
last_not_square_corner = i
if (rx ~= x or ry ~=y) then
same = false
end
end
numNotSquare = numNotSquare + 1
end
end
local numSquare = 4 - numNotSquare
if (numSquare > 0 and same) then
local corners = "corners"
if (numSquare == 2) then
if ((last_not_square_corner - 1 == first_not_square_corner) or
(1 == first_not_square_corner and 4 == last_not_square_corner )) then
corners = "adjacent_" .. corners
else
corners = "opposite_" .. corners
end
elseif (1 == numSquare) then
corners = "corner"
end
if (rx == ry) then
return "circles_with_" .. numSquare .. "_square_" .. corners
else
return "ovals_with_" .. numSquare .. "_square_" .. corners
end
end
return "complex_unclassified"
elseif (rrect:type() == "rect") then
return "rect"
elseif (rrect:type() == "oval") then
local x, y = rrect:radii(0)
if (x == y) then
return "circle"
else
return "oval"
end
elseif (rrect:type() == "empty") then
return "empty"
else
return "unknown"
end
end
function print_classes(class_table)
function sort_classes(a, b)
return a.count > b.count
end
array = {}
for k, v in pairs(class_table) do
if (type(v) == "number") then
array[#array + 1] = {class = k, count = v};
end
end
table.sort(array, sort_classes)
local i
for i = 1, #array do
io.write(array[i].class, ": ", array[i].count, " (", array[i].count/class_table["total"] * 100, "%)\n");
end
end
function sk_scrape_accumulate(t)
if (t.verb == "clipRRect") then
local rrect = t.rrect
table["total"] = (table["total"] or 0) + 1
local class = classify_rrect(rrect)
table[class] = (table[class] or 0) + 1
end
end
function sk_scrape_summarize()
print_classes(table)
--[[ To use the web scraper comment out the above call to print_classes, run the code below,
and in the aggregator pass agg_table to print_classes.
for k, v in pairs(table) do
if (type(v) == "number") then
local t = "agg_table[\"" .. k .. "\"]"
io.write(t, " = (", t, " or 0) + ", table[k], "\n" );
end
end
--]]
end
| bsd-3-clause |
mickelfeng/ABTestingGateway | admin/runtime/del.lua | 22 | 2550 | local runtimeModule = require('abtesting.adapter.runtime')
local redisModule = require('abtesting.utils.redis')
local systemConf = require('abtesting.utils.init')
local handler = require('abtesting.error.handler').handler
local utils = require('abtesting.utils.utils')
local ERRORINFO = require('abtesting.error.errcode').info
local cjson = require('cjson.safe')
local redisConf = systemConf.redisConf
local prefixConf = systemConf.prefixConf
local runtimeLib = prefixConf.runtimeInfoPrefix
local policyLib = prefixConf.policyLibPrefix
local domain_name = prefixConf.domainname
local divtypes = systemConf.divtypes
local doresp = utils.doresp
local dolog = utils.dolog
local domainName = domain_name or ngx.var.arg_domainname
if not domainName then
local request_body = ngx.var.request_body
local postData = cjson.decode(request_body)
if not request_body then
-- ERRORCODE.PARAMETER_NONE
local info = ERRORINFO.PARAMETER_NONE
local desc = 'request_body or post data'
local response = doresp(info, desc)
dolog(info, desc)
ngx.say(response)
return
end
if not postData then
-- ERRORCODE.PARAMETER_ERROR
local info = ERRORINFO.PARAMETER_ERROR
local desc = 'postData is not a json string'
local response = doresp(info, desc)
dolog(info, desc)
ngx.say(response)
return
end
if not domainName then
domainName = postData.domainname
if not domainName then
local info = ERRORINFO.PARAMETER_NONE
local desc = "domainName"
local response = doresp(info, desc)
dolog(info, desc)
ngx.say(response)
return
end
end
end
local red = redisModule:new(redisConf)
local ok, err = red:connectdb()
if not ok then
local errinfo = ERRORINFO.REDIS_CONNECT_ERROR
local response = doresp(errinfo, err)
dolog(errinfo, err)
ngx.say(response)
return
end
local pfunc = function()
local runtimeMod = runtimeModule:new(red.redis, runtimeLib)
runtimeMod:del(domainName)
end
local status, info = xpcall(pfunc, handler)
if not status then
local errinfo = info[1]
local errstack = info[2]
local err, desc = errinfo[1], errinfo[2]
local response = doresp(err, desc)
dolog(err, desc, nil, errstack)
ngx.say(response)
return
end
local response = doresp(ERRORINFO.SUCCESS)
ngx.say(response)
| mit |
Lsty/ygopro-scripts | c96345188.lua | 3 | 2671 | --RR-ミミクリー・レイニアス
function c96345188.initial_effect(c)
--level
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c96345188.lvcon)
e1:SetTarget(c96345188.lvtg)
e1:SetOperation(c96345188.lvop)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,96345188)
e2:SetCondition(c96345188.thcon)
e2:SetCost(c96345188.thcost)
e2:SetTarget(c96345188.thtg)
e2:SetOperation(c96345188.thop)
c:RegisterEffect(e2)
if not c96345188.global_check then
c96345188.global_check=true
local ge1=Effect.CreateEffect(c)
ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge1:SetCode(EVENT_SUMMON_SUCCESS)
ge1:SetOperation(aux.sumreg)
ge1:SetLabel(96345188)
Duel.RegisterEffect(ge1,0)
local ge2=ge1:Clone()
ge2:SetCode(EVENT_SPSUMMON_SUCCESS)
ge2:SetLabel(96345188)
Duel.RegisterEffect(ge2,0)
end
end
function c96345188.lvcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(96345188)>0
end
function c96345188.filter(c)
return c:IsFaceup() and c:GetLevel()>0 and c:IsSetCard(0xba)
end
function c96345188.lvtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c96345188.filter,tp,LOCATION_MZONE,0,1,nil) end
end
function c96345188.lvop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c96345188.filter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
function c96345188.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetTurnID()==Duel.GetTurnCount()
end
function c96345188.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c96345188.thfilter(c)
return c:IsSetCard(0xba) and not c:IsCode(96345188) and c:IsAbleToHand()
end
function c96345188.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c96345188.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c96345188.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c96345188.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
qaheri/AASv2 | plugins/Lock_Emoji.lua | 43 | 2047 | local function run(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['emoji'] == 'yes' then
if not is_momod(msg) then
delete_msg(msg.id, ok_cb, true)
end
end
end
return {patterns = {
"😞(.+)",
"😞",
"😐(.+)",
"😐",
"🙁(.+)",
"🙁",
"🌝(.+)",
"🌝",
"🤖(.+)",
"🤖",
"😲(.+)",
"😲",
"💋(.+)",
"💋",
"🙄(.+)",
"🙄",
"🤗(.+)",
"🤗",
"😱(.+)",
"😱",
"🤐(.+)",
"🤐",
"💩(.+)",
"💩",
"🌹(.+)",
"🌹",
"🖐(.+)",
"🖐",
"❤️(.+)",
"❤️",
"💗(.+)",
"💗",
"🤔(.+)",
"🤔",
"😖(.+)",
"😖",
"☹️(.+)",
"☹️",
"😔(.+)",
"😔",
"👾(.+)",
"👾",
"🚀(.+)",
"🚀",
"🌎🌍(.+)",
"🌍",
"🍦",
"😸(.+)",
"😺",
"😯(.+)",
"😯",
"🤒(.+)",
"🤒",
"😷(.+)",
"😷",
"🙀(.+)",
"🙀",
"🎪(.+)",
"🌚",
"🌚(.+)",
"😂",
"😂(.+)",
"😳",
"😳(.+)",
"😛",
"😛(.+)",
"😢",
"😢(.+)",
"😓",
"😓(.+)",
"😾",
"😾(.+)",
"👊🏻",
"👊🏻(.+)",
"✊🏻",
"✊🏻(.+)",
"👿",
"👿(.+)",
"👅",
"👅(.+)",
"🖕🏿",
"🖕🏿(.+)",
"😲",
"😲(.+)",
"👹",
"👹(.+)",
"😴",
"😴(.+)",
"☂",
"☂(.+)",
"🗣",
"🗣(.+)",
"⛄️",
"⛄️(.+)",
"😻",
"😻(.+)",
"😀(.+)",
"😀",
"😬(.+)",
"😬",
"😁(.+)",
"😁",
"😂(.+)",
"😂",
"😃(.+)",
"😃",
"😄(.+)",
"😄",
"😅",
"😆(.+)",
"😆",
"😇(.+)",
"😇",
"😉(.+)",
"😉",
"😊(.+)",
"😊",
"🙂(.+)",
"🙂",
"🙃(.+)",
"🙃",
"☺️(.+)",
"☺️",
"😋(.+)",
"😋",
"😌",
"😍(.+)",
"😍",
"😘(.+)",
"😘",
"😗(.+)",
"😗",
"😙(.+)",
"😙",
"😚(.+)",
"😚",
"😜(.+)",
"😜",
"😝(.+)",
"😝",
"🤑(.+)",
"🤑",
"🤓(.+)",
"🤓",
"😎(.+)",
"😎",
"🤗(.+)",
"🤗",
"😏(.+)",
"😏",
"😶(.+)",
"😶",
"😺(.+)",
"😺",
"😹",
"😼",
"😿",
"🌝",
"🌚",
"🌶",
"🖐🏼",
},run = run}
| gpl-2.0 |
Lsty/ygopro-scripts | c15871676.lua | 5 | 1132 | --セイクリッド・ダバラン
function c15871676.initial_effect(c)
--summon success
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(15871676,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetTarget(c15871676.sptg)
e2:SetOperation(c15871676.spop)
c:RegisterEffect(e2)
end
function c15871676.filter(c,e,tp)
return c:IsSetCard(0x53) and c:GetLevel()==3 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c15871676.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c15871676.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c15871676.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c15871676.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
ml-lab/NAMAS | summary/nnlm.lua | 9 | 6810 | --
-- Copyright (c) 2015, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Author: Alexander M Rush <srush@seas.harvard.edu>
-- Sumit Chopra <spchopra@fb.com>
-- Jason Weston <jase@fb.com>
-- Ngram neural language model with auxiliary model
require('nn')
require('nngraph')
require('fbnn')
require('cunn')
require('sys')
local utils = require('summary.util')
local nnlm = {}
function nnlm.addOpts()
cmd:option('-epochs', 5, "Number of epochs to train.")
cmd:option('-miniBatchSize', 64, "Size of training minibatch.")
cmd:option('-printEvery', 10000, "How often to print during training.")
cmd:option('-modelFilename', '', "File for saving loading/model.")
cmd:option('-window', 5, "Size of NNLM window.")
cmd:option('-embeddingDim', 50, "Size of NNLM embeddings.")
cmd:option('-hiddenSize', 100, "Size of NNLM hiddent layer.")
cmd:option('-learningRate', 0.1, "SGD learning rate.")
end
function nnlm.create_lm(opt, dict, encoder, encoder_size, encoder_dict)
local new_mlp = {}
setmetatable(new_mlp, { __index = nnlm })
new_mlp.opt = opt
new_mlp.dict = dict
new_mlp.encoder_dict = encoder_dict
new_mlp.encoder_model = encoder
new_mlp.window = opt.window
if encoder ~= nil then
new_mlp:build_mlp(encoder, encoder_size)
end
return new_mlp
end
function nnlm:build_mlp(encoder, encoder_size)
-- Set constants
local D = self.opt.embeddingDim
local N = self.opt.window
local H = self.opt.hiddenSize
local V = #self.dict.index_to_symbol
local P = encoder_size
print(H, P)
-- Input
local context_input = nn.Identity()()
local encoder_input = nn.Identity()()
local position_input = nn.Identity()()
local lookup = nn.LookupTable(V, D)(context_input)
local encoder_node = encoder({encoder_input, position_input, context_input})
-- tanh W (E y)
local lm_mlp = nn.Tanh()(nn.Linear(D * N, H)(nn.View(D * N)(lookup)))
-- Second layer: takes LM and encoder model.
local mlp = nn.Linear(H + P, V)(nn.View(H + P)(nn.JoinTable(2)(
{lm_mlp, encoder_node})))
self.soft_max = nn.LogSoftMax()(mlp)
-- Input is conditional context and ngram context.
self.mlp = nn.gModule({encoder_input, position_input, context_input},
{self.soft_max})
self.criterion = nn.ClassNLLCriterion()
self.lookup = lookup.data.module
self.mlp:cuda()
self.criterion:cuda()
collectgarbage()
end
-- Run validation
function nnlm:validation(valid_data)
print("[Running Validation]")
local offset = 1000
local loss = 0
local total = 0
valid_data:reset()
while not valid_data:is_done() do
local input, target = valid_data:next_batch(offset)
local out = self.mlp:forward(input)
local err = self.criterion:forward(out, target) * target:size(1)
-- Augment counters.
loss = loss + err
total = total + target:size(1)
end
print(string.format("[perp: %f validation: %f total: %d]",
math.exp(loss/total),
loss/total, total))
return loss / total
end
function nnlm:renorm(data, th)
local size = data:size(1)
for i = 1, size do
local norm = data[i]:norm()
if norm > th then
data[i]:div(norm/th)
end
end
end
function nnlm:renorm_tables()
-- Renormalize the lookup tables.
if self.lookup ~= nil then
print(self.lookup.weight:size())
print(self.lookup.weight:type())
self:renorm(self.lookup.weight, 1)
end
if self.encoder_model.lookup ~= nil then
self:renorm(self.encoder_model.lookup.weight, 1)
if self.encoder_model.title_lookup ~= nil then
self:renorm(self.encoder_model.title_lookup.weight, 1)
end
end
if self.encoder_model.lookups ~= nil then
for i = 1, #self.encoder_model.lookups do
self:renorm(self.encoder_model.lookups[i].weight, 1)
end
end
end
function nnlm:run_valid(valid_data)
-- Run validation.
if valid_data ~= nil then
local cur_valid_loss = self:validation(valid_data)
-- If valid loss does not improve drop learning rate.
if cur_valid_loss > self.last_valid_loss then
self.opt.learningRate = self.opt.learningRate / 2
end
self.last_valid_loss = cur_valid_loss
end
-- Save the model.
self:save(self.opt.modelFilename)
end
function nnlm:train(data, valid_data)
-- Best loss seen yet.
self.last_valid_loss = 1e9
-- Train
for epoch = 1, self.opt.epochs do
data:reset()
self:renorm_tables()
self:run_valid(valid_data)
-- Loss for the epoch.
local epoch_loss = 0
local batch = 1
local last_batch = 1
local total = 0
local loss = 0
sys.tic()
while not data:is_done() do
local input, target = data:next_batch(self.opt.miniBatchSize)
if data:is_done() then break end
local out = self.mlp:forward(input)
local err = self.criterion:forward(out, target) * target:size(1)
local deriv = self.criterion:backward(out, target)
if not utils.isnan(err) then
loss = loss + err
epoch_loss = epoch_loss + err
self.mlp:zeroGradParameters()
self.mlp:backward(input, deriv)
self.mlp:updateParameters(self.opt.learningRate)
else
print("NaN")
print(input)
end
-- Logging
if batch % self.opt.printEvery == 1 then
print(string.format(
"[Loss: %f Epoch: %d Position: %d Rate: %f Time: %f]",
loss / ((batch - last_batch) * self.opt.miniBatchSize),
epoch,
batch * self.opt.miniBatchSize,
self.opt.learningRate,
sys.toc()
))
sys.tic()
last_batch = batch
loss = 0
end
batch = batch + 1
total = total + input[1]:size(1)
end
print(string.format("[EPOCH : %d LOSS: %f TOTAL: %d BATCHES: %d]",
epoch, epoch_loss / total, total, batch))
end
end
function nnlm:save(fname)
print("[saving mlp: " .. fname .. "]")
torch.save(fname, self)
return true
end
function nnlm:load(fname)
local new_self = torch.load(fname)
for k, v in pairs(new_self) do
if k ~= 'opt' then
self[k] = v
end
end
return true
end
return nnlm
| bsd-3-clause |
Lsty/ygopro-scripts | c70913714.lua | 2 | 2958 | --古神ハストール
function c70913714.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(70913714,0))
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c70913714.eqcon)
e1:SetTarget(c70913714.eqtg)
e1:SetOperation(c70913714.eqop)
c:RegisterEffect(e1)
end
function c70913714.eqcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_MZONE)
end
function c70913714.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsFaceup() end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,0,LOCATION_MZONE,1,1,nil)
end
function c70913714.eqlimit(e,c)
return e:GetOwner()==c
end
function c70913714.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsFaceup() and tc:IsRelateToEffect(e) then
Duel.Equip(tp,c,tc,true)
--Add Equip limit
local e1=Effect.CreateEffect(tc)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(c70913714.eqlimit)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_DISABLE)
e2:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_CANNOT_ATTACK)
c:RegisterEffect(e3)
--control
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(70913714,1))
e4:SetCategory(CATEGORY_CONTROL)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_LEAVE_FIELD)
e4:SetCondition(c70913714.ctcon)
e4:SetTarget(c70913714.cttg)
e4:SetOperation(c70913714.ctop)
e4:SetReset(RESET_EVENT+0x1020000)
c:RegisterEffect(e4)
end
end
function c70913714.ctcon(e,tp,eg,ep,ev,re,r,rp)
return not e:GetHandler():IsReason(REASON_LOST_TARGET)
end
function c70913714.cttg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local ec=e:GetHandler():GetPreviousEquipTarget()
if ec:IsLocation(LOCATION_MZONE) and ec:IsControlerCanBeChanged() then
Duel.SetTargetCard(ec)
Duel.SetOperationInfo(0,CATEGORY_CONTROL,ec,1,0,0)
end
end
function c70913714.ctop(e,tp,eg,ep,ev,re,r,rp)
local ec=Duel.GetFirstTarget()
if ec and ec:IsRelateToEffect(e) and not Duel.GetControl(ec,tp) then
if not ec:IsImmuneToEffect(e) and ec:IsAbleToChangeControler() then
Duel.Destroy(ec,REASON_EFFECT)
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c78474168.lua | 3 | 2885 | --ブレイクスルー・スキル
function c78474168.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DISABLE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,0x1c0)
e1:SetTarget(c78474168.target)
e1:SetOperation(c78474168.activate)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(78474168,0))
e2:SetCategory(CATEGORY_DISABLE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetRange(LOCATION_GRAVE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetCondition(c78474168.negcon)
e2:SetCost(c78474168.negcost)
e2:SetTarget(c78474168.target)
e2:SetOperation(c78474168.activate2)
c:RegisterEffect(e2)
end
function c78474168.filter(c)
return c:IsFaceup() and c:IsType(TYPE_EFFECT) and not c:IsDisabled()
end
function c78474168.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c78474168.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c78474168.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c78474168.filter,tp,0,LOCATION_MZONE,1,1,nil)
end
function c78474168.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() and not tc:IsDisabled() and tc:IsControler(1-tp) then
Duel.NegateRelatedChain(tc,RESET_TURN_SET)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e2)
end
end
function c78474168.negcon(e,tp,eg,ep,ev,re,r,rp)
return aux.exccon(e) and Duel.GetTurnPlayer()==tp
end
function c78474168.negcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c78474168.activate2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() and not tc:IsDisabled() and tc:IsControler(1-tp) and tc:IsType(TYPE_EFFECT) then
Duel.NegateRelatedChain(tc,RESET_TURN_SET)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e2)
end
end
| gpl-2.0 |
mati865/vlc | share/lua/playlist/cue.lua | 60 | 4393 | --[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function is_utf8( src )
return vlc.strings.from_charset( "UTF-8", src ) == src
end
function cue_string( src )
if not is_utf8( src ) then
-- Convert to UTF-8 since it's probably Latin1
src = vlc.strings.from_charset( "ISO_8859-1", src )
end
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return vlc.strings.make_uri(src)
end
local slash = string.find( string.reverse( vlc.path ), '/' )
local prefix = vlc.access .. "://" .. string.sub( vlc.path, 1, -slash )
-- FIXME: postfix may not be encoded correctly (esp. slashes)
local postfix = vlc.strings.encode_uri_component(src)
return prefix .. postfix
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = cue_path( track.file or global.file )
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. track.index01}
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. track.index01)
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
| gpl-2.0 |
Lsty/ygopro-scripts | c13803864.lua | 3 | 1590 | --キング・もけもけ
function c13803864.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcCodeRep(c,27288416,3,true,true)
--Special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(13803864,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c13803864.spcon)
e1:SetTarget(c13803864.sptg)
e1:SetOperation(c13803864.spop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_REMOVE)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_TO_DECK)
c:RegisterEffect(e3)
end
function c13803864.spfilter(c,e,tp)
return c:IsCode(27288416) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c13803864.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousPosition(POS_FACEUP) and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c13803864.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c13803864.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function c13803864.spop(e,tp,eg,ep,ev,re,r,rp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c13803864.spfilter,tp,LOCATION_GRAVE,0,ft,ft,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c21790410.lua | 3 | 2994 | --甲虫装機 センチピード
function c21790410.initial_effect(c)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(21790410,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetTarget(c21790410.eqtg)
e1:SetOperation(c21790410.eqop)
c:RegisterEffect(e1)
--equip effect
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_LEVEL)
e2:SetValue(3)
c:RegisterEffect(e2)
--search
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(21790410,1))
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c21790410.shcon)
e3:SetTarget(c21790410.shtg)
e3:SetOperation(c21790410.shop)
c:RegisterEffect(e3)
end
function c21790410.filter(c)
return c:IsSetCard(0x56) and c:IsType(TYPE_MONSTER) and not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c21790410.eqtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingMatchingCard(c21790410.filter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,nil,1,tp,LOCATION_GRAVE+LOCATION_HAND)
end
function c21790410.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
local g=Duel.SelectMatchingCard(tp,c21790410.filter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,1,nil)
local tc=g:GetFirst()
if tc then
if not Duel.Equip(tp,tc,c,true) then return end
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_COPY_INHERIT+EFFECT_FLAG_OWNER_RELATE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(c21790410.eqlimit)
tc:RegisterEffect(e1)
end
end
function c21790410.eqlimit(e,c)
return e:GetOwner()==c
end
function c21790410.cfilter(c,ec,tp)
return c:IsLocation(LOCATION_GRAVE) and c:IsControler(tp) and c:GetEquipTarget()==ec
end
function c21790410.shcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c21790410.cfilter,1,nil,e:GetHandler(),tp)
end
function c21790410.tgfilter(c)
return c:IsSetCard(0x56) and c:IsAbleToHand()
end
function c21790410.shtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsRelateToEffect(e) and e:GetHandler():IsFaceup()
and Duel.IsExistingMatchingCard(c21790410.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c21790410.shop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c21790410.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/commands/cnation.lua | 22 | 2003 | ---------------------------------------------------------------------------------------------------
-- func: cnation <target> <campaign allegiance>
-- desc: check or alter target characters campaign allegiance
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "ss"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!cnation <player> <campaign allegiance>");
end;
function onTrigger(player, target, nation)
-- nation xref tables
local nationNameToNum = {
["NONE"] = 0,
["SANDORIA"] = 1,
["BASTOK"] = 2,
["WINDURST"] = 3
}
local nationNumToName ={};
for k,v in pairs(nationNameToNum) do
nationNumToName[v]=k;
end
-- validate target
if (target == nil) then
error(player, "You must specify an online player by name.");
return;
end
local targ = GetPlayerByName( target );
if (targ == nil) then
error(player, string.format( "Player named '%s' not found!", target ) );
return;
end;
-- show or set allegiance
if (nation == nil) then
player:PrintToPlayer(string.format("%s's current campaign allegiance: %s", targ:getName(), nationNumToName[targ:getCampaignAllegiance()]));
else
nation = tonumber(nation) or nationNameToNum[string.upper(nation)];
if (nation == nil or nation < 0 or nation > 3) then
error(player, "Invalid campaign allegiange. Valid choices are SANDORIA (1), BASTOK (2), or WINDURST (3).");
return;
end
player:PrintToPlayer(string.format("%s's old campaign allegiance: %s", targ:getName(), nationNumToName[targ:getCampaignAllegiance()]));
targ:setCampaignAllegiance(nation);
player:PrintToPlayer(string.format("%s's new campaign allegiance: %s", targ:getName(), nationNumToName[targ:getCampaignAllegiance()]));
end
end; | gpl-3.0 |
MalRD/darkstar | scripts/globals/abilities/pets/attachments/auto-repair_kit.lua | 11 | 1486 | -----------------------------------
-- Attachment: Auto-repair Kit
-----------------------------------
require("scripts/globals/automaton")
require("scripts/globals/status")
-----------------------------------
function onEquip(pet)
-- We do not have support to do a fraction of a percent so we rounded
local frame = pet:getAutomatonFrame()
if frame == dsp.frames.HARLEQUIN then
pet:addMod(dsp.mod.HPP, 5)
elseif frame == dsp.frames.VALOREDGE then
pet:addMod(dsp.mod.HPP, 4)
elseif frame == dsp.frames.SHARPSHOT then
pet:addMod(dsp.mod.HPP, 6)
elseif frame == dsp.frames.STORMWAKER then
pet:addMod(dsp.mod.HPP, 7)
end
end
function onUnequip(pet)
local frame = pet:getAutomatonFrame()
if frame == dsp.frames.HARLEQUIN then
pet:delMod(dsp.mod.HPP, 5)
elseif frame == dsp.frames.VALOREDGE then
pet:delMod(dsp.mod.HPP, 4)
elseif frame == dsp.frames.SHARPSHOT then
pet:delMod(dsp.mod.HPP, 6)
elseif frame == dsp.frames.STORMWAKER then
pet:delMod(dsp.mod.HPP, 7)
end
end
function onManeuverGain(pet, maneuvers)
onUpdate(pet, maneuvers)
end
function onManeuverLose(pet, maneuvers)
onUpdate(pet, maneuvers - 1)
end
function onUpdate(pet, maneuvers)
local power = 0
if maneuvers > 0 then
power = math.floor(maneuvers + (pet:getMaxHP() * (0.125 * maneuvers) / 100))
end
updateModPerformance(pet, dsp.mod.REGEN, 'autorepair_kit_mod', power)
end
| gpl-3.0 |
maxrio/luci981213 | applications/luci-app-radvd/luasrc/model/cbi/radvd/interface.lua | 61 | 7787 | -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sid = arg[1]
local utl = require "luci.util"
m = Map("radvd", translatef("Radvd - Interface %q", "?"),
translate("Radvd is a router advertisement daemon for IPv6. " ..
"It listens to router solicitations and sends router advertisements " ..
"as described in RFC 4861."))
m.redirect = luci.dispatcher.build_url("admin/network/radvd")
if m.uci:get("radvd", sid) ~= "interface" then
luci.http.redirect(m.redirect)
return
end
m.uci:foreach("radvd", "interface",
function(s)
if s['.name'] == sid and s.interface then
m.title = translatef("Radvd - Interface %q", s.interface)
return false
end
end)
s = m:section(NamedSection, sid, "interface", translate("Interface Configuration"))
s.addremove = false
s:tab("general", translate("General"))
s:tab("timing", translate("Timing"))
s:tab("mobile", translate("Mobile IPv6"))
--
-- General
--
o = s:taboption("general", Flag, "ignore", translate("Enable"))
o.rmempty = false
function o.cfgvalue(...)
local v = Flag.cfgvalue(...)
return v == "1" and "0" or "1"
end
function o.write(self, section, value)
Flag.write(self, section, value == "1" and "0" or "1")
end
o = s:taboption("general", Value, "interface", translate("Interface"),
translate("Specifies the logical interface name this section belongs to"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.optional = false
function o.formvalue(...)
return Value.formvalue(...) or "-"
end
function o.validate(self, value)
if value == "-" then
return nil, translate("Interface required")
end
return value
end
function o.write(self, section, value)
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "interface", value)
end
o = s:taboption("general", DynamicList, "client", translate("Clients"),
translate("Restrict communication to specified clients, leave empty to use multicast"))
o.rmempty = true
o.datatype = "ip6addr"
o.placeholder = "any"
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
local l = { }
for v in utl.imatch(v) do
l[#l+1] = v
end
return l
end
o = s:taboption("general", Flag, "AdvSendAdvert", translate("Enable advertisements"),
translate("Enables router advertisements and solicitations"))
o.rmempty = false
function o.write(self, section, value)
if value == "1" then
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "IgnoreIfMissing", 1)
end
m.uci:set("radvd", section, "AdvSendAdvert", value)
end
o = s:taboption("general", Flag, "UnicastOnly", translate("Unicast only"),
translate("Indicates that the underlying link is not broadcast capable, prevents unsolicited advertisements from being sent"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Flag, "AdvManagedFlag", translate("Managed flag"),
translate("Enables the additional stateful administered autoconfiguration protocol (RFC2462)"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Flag, "AdvOtherConfigFlag", translate("Configuration flag"),
translate("Enables the autoconfiguration of additional, non address information (RFC2462)"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Flag, "AdvSourceLLAddress", translate("Source link-layer address"),
translate("Includes the link-layer address of the outgoing interface in the RA"))
o.rmempty = false
o.default = "1"
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Value, "AdvLinkMTU", translate("Link MTU"),
translate("Advertises the given link MTU in the RA if specified. 0 disables MTU advertisements"))
o.datatype = "uinteger"
o.placeholder = 0
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Value, "AdvCurHopLimit", translate("Current hop limit"),
translate("Advertises the default Hop Count value for outgoing unicast packets in the RA. 0 disables hopcount advertisements"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 64
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", ListValue, "AdvDefaultPreference", translate("Default preference"),
translate("Advertises the default router preference"))
o.optional = false
o.default = "medium"
o:value("low", translate("low"))
o:value("medium", translate("medium"))
o:value("high", translate("high"))
o:depends("AdvSendAdvert", "1")
--
-- Timing
--
o = s:taboption("timing", Value, "MinRtrAdvInterval", translate("Minimum advertisement interval"),
translate("The minimum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 198
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "MaxRtrAdvInterval", translate("Maximum advertisement interval"),
translate("The maximum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 600
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "MinDelayBetweenRAs", translate("Minimum advertisement delay"),
translate("The minimum time allowed between sending multicast router advertisements from the interface, in seconds"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 3
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "AdvReachableTime", translate("Reachable time"),
translate("Advertises assumed reachability time in milliseconds of neighbours in the RA if specified. 0 disables reachability advertisements"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 0
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "AdvRetransTimer", translate("Retransmit timer"),
translate("Advertises wait time in milliseconds between Neighbor Solicitation messages in the RA if specified. 0 disables retransmit advertisements"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 0
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "AdvDefaultLifetime", translate("Default lifetime"),
translate("Advertises the lifetime of the default router in seconds. 0 indicates that the node is no default router"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 1800
o:depends("AdvSendAdvert", "1")
--
-- Mobile
--
o = s:taboption("mobile", Flag, "AdvHomeAgentFlag", translate("Advertise Home Agent flag"),
translate("Advertises Mobile IPv6 Home Agent capability (RFC3775)"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("mobile", Flag, "AdvIntervalOpt", translate("Mobile IPv6 interval option"),
translate("Include Mobile IPv6 Advertisement Interval option to RA"))
o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Flag, "AdvHomeAgentInfo", translate("Home Agent information"),
translate("Include Home Agent Information in the RA"))
o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Flag, "AdvMobRtrSupportFlag", translate("Mobile IPv6 router registration"),
translate("Advertises Mobile Router registration capability (NEMO Basic)"))
o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Value, "HomeAgentLifetime", translate("Home Agent lifetime"),
translate("Advertises the time in seconds the router is offering Mobile IPv6 Home Agent services"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 1800
o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Value, "HomeAgentPreference", translate("Home Agent preference"),
translate("The preference for the Home Agent sending this RA"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 0
o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"})
return m
| apache-2.0 |
Frenzie/koreader | plugins/terminal.koplugin/terminputtext.lua | 4 | 28685 | --[[--
module used for terminal emulator to override InputText
@module koplugin.terminal
]]
local InputText = require("ui/widget/inputtext")
local UIManager = require("ui/uimanager")
local dbg = require("dbg")
local logger = require("logger")
local util = require("util")
local esc = "\027"
local esc_seq = {
backspace = "\008",
cursor_left = "\027[D",
cursor_right = "\027[C",
cursor_up = "\027[A",
cursor_down = "\027[B",
cursor_pos1 = "\027[7~",
cursor_end = "\027[8~",
page_up = "\027[5~",
page_down = "\027[6~",
}
local function isNum(char)
if #char ~= 1 then return end
if char:byte() >= ("0"):byte() and char:byte() <= ("9"):byte() then
return true
end
end
local function isPrintable(ch)
return ch:byte() >= 32 or ch == "\010" or ch == "\013"
end
local TermInputText = InputText:extend{
maxr = 40,
maxc = 80,
min_buffer_size = 2 * 40 * 80, -- minimal size of scrollback buffer
strike_callback = nil,
sequence_state = "",
store_pos_dec = nil,
store_pos_sco = nil,
store_position = nil, -- when entered alternate keypad
scroll_region_bottom = nil,
scroll_region_top = nil,
scroll_region_line = nil,
wrap = true,
alternate_buffer = nil, -- table
save_buffer = nil, -- table
}
function TermInputText:init()
self.alternate_buffer = {}
self.save_buffer = {}
InputText.init(self)
end
-- disable positioning cursor by tap in emulator mode
function TermInputText:onTapTextBox(arg, ges)
return true
end
function TermInputText:resize(maxr, maxc)
self.maxr = maxr
self.maxc = maxc
self.min_buffer_size = 2 * self.maxr * self.maxc
end
-- reduce the size of the buffer,
function TermInputText:trimBuffer(new_size)
if not new_size or new_size < self.min_buffer_size then
new_size = self.min_buffer_size
end
if #self.charlist > new_size then
local old_pos = self.charpos -- for adjusting saved positions
-- remove char from beginning
while #self.charlist > new_size do
table.remove(self.charlist, 1)
self.charpos = self.charpos - 1
end
-- remove the (rest) of the first line
while self.charlist[1] and self.charlist[1] ~= "\n" do
table.remove(self.charlist, 1)
self.charpos = self.charpos - 1
end
-- remove newline at the first line
if self.charlist[1] and self.charlist[1] == "\n" then
table.remove(self.charlist, 1)
self.charpos = self.charpos - 1
end
-- IMPORTANT: update stored positions if the buffer has to be trimmed
local shift_pos = old_pos - self.charpos
if self.store_position then
self.store_position = self.store_position - shift_pos
if self.store_position < 1 then
self.store_position = 1
end
end
if self.store_pos_dec then
self.store_pos_dec = self.store_pos_dec - shift_pos
if self.store_pos_dec < 1 then
self.store_pos_dec = 1
end
end
if self.store_pos_sco then
self.store_pos_sco = self.store_pos_sco - shift_pos
if self.store_pos_sco < 1 then
self.store_pos_sco = 1
end
end
-- unlikely but this could happen if the cursor is at the beginning
-- and the buffer has to be trimmed
if self.charpos < 1 then
self.charpos = 1
end
self:initTextBox(table.concat(self.charlist), true)
end
end
function TermInputText:saveBuffer(buffer)
table.insert(self[buffer],
{
self.charlist,
self.charpos,
self.store_pos_dec,
self.store_pos_sco,
self.store_position,
self.scroll_region_bottom,
self.scroll_region_top,
self.scroll_region_line,
self.wrap,
})
self.charlist = {}
self.charpos = 1
self.store_pos_dec = nil
self.store_pos_sco = nil
self.store_position = nil
self.scroll_region_bottom = nil
self.scroll_region_top = nil
self.scroll_region_line = nil
self.wrap = true
end
function TermInputText:restoreBuffer(buffer)
local former_buffer = table.remove(self[buffer])
if type(former_buffer[1]) == "table" then
self.charlist,
self.charpos,
self.store_pos_dec,
self.store_pos_sco,
self.store_position,
self.scroll_region_bottom,
self.scroll_region_top,
self.scroll_region_line,
self.wrap = unpack(former_buffer)
end
end
function TermInputText:_helperVT52VT100(cmd, mode, param1, param2, param3)
if cmd == "A" then -- cursor up
param1 = param1 == 0 and 1 or param1
for i = 1, param1 do
if self.scroll_region_line then
self:scrollRegionDown()
end
self:moveCursorUp(true)
end
return true
elseif cmd == "B" then -- cursor down
param1 = param1 == 0 and 1 or param1
for i = 1, param1 do
self:moveCursorDown(true)
end
return true
elseif cmd == "C" then -- cursor right
param1 = param1 == 0 and 1 or param1
for i = 1, param1 do
self:rightChar(true)
end
return true
elseif cmd == "D" then -- cursor left
param1 = param1 == 0 and 1 or param1
for i = 1, param1 do
self:leftChar(true)
end
return true
elseif cmd == "H" then -- cursor home
param1 = param1 == 0 and 1 or param1
param2 = param2 == 0 and 1 or param2
self:moveCursorToRowCol(param1, param2)
if self.scroll_region_line and param1 <= self.scroll_region_bottom
and param1 >= self.scroll_region_top then
self.scroll_region_line = param1
end
return true
elseif cmd == "J" then -- clear to end of screen
if param1 == 0 then
self:clearToEndOfScreen()
elseif param1 == 1 then
return false --- @todo not implemented
elseif param1 == 2 then
local saved_pos = self.charpos
self:moveCursorToRowCol(1, 1)
self:clearToEndOfScreen()
self.charpos = saved_pos
end
return true
elseif cmd == "K" then -- clear to end of line
self:delToEndOfLine()
return true
elseif cmd == "L" then
if self.scroll_region_line then
self:scrollRegionDown()
end
return true
elseif cmd == "h" and mode == "?" then --
--- if param2 == 25 then set cursor visible
if param2 == 7 then -- enable wrap around
self.wrap = true
elseif param2 == 47 then -- save screen
self:saveBuffer("save_buffer")
print("xxxxxxxxxxxx save screen")
elseif param2 == 1049 then -- enable alternate buffer
self:saveBuffer("alternate_buffer")
print("xxxxxxxxxxxx enable alternate buffer")
end
return true
elseif cmd == "l" and mode == "?" then --
--- if param2 == 25 then set cursor invisible
if param2 == 7 then -- enable wrap around
self.wrap = false
elseif param2 == 47 then -- restore screen
self:restoreBuffer("save_buffer")
print("xxxxxxxxxxxx restore screen")
elseif param2 == 1049 then -- disable alternate buffer
self:restoreBuffer("alternate_buffer")
print("xxxxxxxxxxxx disable alternate buffer")
end
return true
elseif cmd == "m" then
-- graphics mode not supported yet(?)
return true
elseif cmd == "n" then
--- @todo
return true
elseif cmd == "r" then
if param2 > 0 and param2 < self.maxr then
self.scroll_region_bottom = param2
else
self.scroll_region_bottom = nil
end
if self.scroll_region_bottom and param1 < self.maxr and param1 <= param2 and param1 > 0 then
self.scroll_region_top = param1
self.scroll_region_line = 1
else
self.scroll_region_bottom = nil
self.scroll_region_top = nil
self.scroll_region_line = nil
end
logger.dbg("Terminal: set scroll region", param1, param2, self.scroll_region_top, self.scroll_region_bottom, self.scroll_region_line)
return true
end
return false
end
function TermInputText:interpretAnsiSeq(text)
local pos = 1
local param1, param2, param3 = 0, 0, 0
while pos <= #text do
local next_byte = text:sub(pos, pos)
if self.sequence_state == "" then
if next_byte == esc then
self.sequence_state = "esc"
elseif isPrintable(next_byte) then
local part = next_byte
-- all bytes up to the next control sequence
while pos < #text and isPrintable(next_byte) do
next_byte = text:sub(pos+1, pos+1)
if next_byte ~= "" and pos < #text and isPrintable(next_byte) then
part = part .. next_byte
pos = pos + 1
end
end
self:addChars(part, true, true)
elseif next_byte == "\008" then
self.charpos = self.charpos - 1
end
elseif self.sequence_state == "esc" then
self.sequence_state = ""
if next_byte == "A" then -- cursor up
self:moveCursorUp(true)
elseif next_byte == "B" then -- cursor down
self:moveCursorDown(true)
elseif next_byte == "C" then -- cursor right
self:rightChar(true)
elseif next_byte == "D" then -- cursor left
self:leftChar(true)
elseif next_byte == "F" then -- enter graphics mode
logger.dbg("Terminal: enter graphics mode not supported")
elseif next_byte == "G" then -- exit graphics mod
logger.dbg("Terminal: leave graphics mode not supported")
elseif next_byte == "H" then -- cursor home
self:moveCursorToRowCol(1, 1)
elseif next_byte == "I" then -- reverse line feed (cursor up and insert line)
self:reverseLineFeed(true)
elseif next_byte == "J" then -- clear to end of screen
self:clearToEndOfScreen()
elseif next_byte == "K" then -- clear to end of line
self:delToEndOfLine()
elseif next_byte == "L" then -- insert line
logger.dbg("Terminal: insert not supported")
elseif next_byte == "M" then -- remove line
logger.dbg("Terminal: remove line not supported")
elseif next_byte == "Y" then -- set cursor pos (row, col)
self.sequence_state = "escY"
elseif next_byte == "Z" then -- ident(ify)
self.strike_callback("\027/K") -- identify as VT52 without printer
elseif next_byte == "=" then -- alternate keypad
self:enterAlternateKeypad()
elseif next_byte == ">" then -- exit alternate keypad
self:exitAlternateKeypad()
elseif next_byte == "[" then
self.sequence_state = "CSI1"
elseif next_byte == "7" then
self.store_pos_dec = self.charpos
elseif next_byte == "8" then
self.charpos = self.store_pos_dec
end
elseif self.sequence_state == "escY" then
param1 = next_byte
self.sequence_state = "escYrow"
elseif self.sequence_state == "escYrow" then
param2 = next_byte
-- row and column are offsetted with 32 (' ')
if param1 ~= 0 and param2 ~= 0 then
local row = param1 and (param1:byte() - (" "):byte() + 1) or 1
local col = param2 and (param2:byte() - (" "):byte() + 1) or 1
self:moveCursorToRowCol(row, col)
param1, param2, param3 = 0, 0, 0
end
self.sequence_state = ""
elseif self.sequence_state == "CSI1" then
if next_byte == "s" then -- save cursor pos
self.store_pos_sco = self.charpos
elseif next_byte == "u" then -- restore cursor pos
self.charpos = self.store_pos_sco
elseif next_byte == "?" then
self.sequence_mode = "?"
self.sequence_state = "escParam2"
elseif isNum(next_byte) then
param1 = param1 * 10 + next_byte:byte() - ("0"):byte()
else
if next_byte == ";" then
self.sequence_state = "escParam2"
else
pos = pos - 1
self.sequence_state = "escOtherCmd"
end
end
elseif self.sequence_state == "escParam2" then
if isNum(next_byte) then
param2 = param2 * 10 + next_byte:byte() - ("0"):byte()
else
if next_byte == ";" then
self.sequence_state = "escParam3"
else
pos = pos - 1
self.sequence_state = "escOtherCmd"
end
end
elseif self.sequence_state == "escParam3" then
if isNum(next_byte) then
param3 = param3 * 10 + next_byte:byte() - ("0"):byte()
else
pos = pos - 1
self.sequence_state = "escOtherCmd"
end
elseif self.sequence_state == "escOtherCmd" then
if not self:_helperVT52VT100(next_byte, self.sequence_mode, param1, param2, param3) then
-- drop other VT100 sequences
logger.info("Terminal: ANSI-final: not supported", next_byte,
next_byte:byte(), next_byte, param1, param2, param3)
end
param1, param2, param3 = 0, 0, 0
self.sequence_state = ""
self.sequence_mode = ""
else
logger.dbg("Terminal: detected error in esc sequence, not my fault.")
self.sequence_state = ""
end -- self.sequence_state
pos = pos + 1
end
self:initTextBox(table.concat(self.charlist), true)
end
function TermInputText:scrollRegionDown(column)
column = column or 1
if self.scroll_region_line > self.scroll_region_top then
self.scroll_region_line = self.scroll_region_line - 1
else -- scroll down
local pos = self.charpos
for i = self.scroll_region_line, self.scroll_region_bottom do
while pos > 1 and self.charlist[pos] ~= "\n" do
pos = pos + 1
end
if pos < #self.charlist then
pos = pos + 1
end
end
pos = pos - 1
table.remove(self.charlist, pos)
while self.charlist[pos] ~= "\n" do
table.remove(self.charlist, pos)
end
pos = self.charpos
for i = column, self.maxc - column + 1 do
table.insert(self.charlist, pos, ".")
pos = pos + 1
end
table.insert(self.charlist, pos, "\n")
end
end
function TermInputText:scrollRegionUp(column)
column = column or 1
if self.scroll_region_line < self.scroll_region_bottom then
self.scroll_region_line = self.scroll_region_line + 1
else -- scroll up
local pos = self.charpos
for i = self.scroll_region_line, self.scroll_region_top + 1, -1 do
while pos > 1 and self.charlist[pos] ~= "\n" do
pos = pos - 1
end
if pos > 1 then
pos = pos - 1
end
end
pos = pos + 1
table.remove(self.charlist, pos)
self.charpos = self.charpos - 1
pos = pos - 1
while pos > 0 and self.charlist[pos] ~= "\n" do
table.remove(self.charlist, pos)
pos = pos - 1
end
pos = self.charpos + 1
for i = column, self.maxc - column do
table.insert(self.charlist, pos, " ")
pos = pos + 1
end
table.insert(self.charlist, pos, "\n")
for i = 1, column - 1 do
table.insert(self.charlist, pos, " ")
pos = pos + 1
end
end
end
function TermInputText:addChars(chars, skip_callback, skip_table_concat)
-- the same as in inputtext.lua
if not chars then
-- VirtualKeyboard:addChar(key) gave us 'nil' once (?!)
-- which would crash table.concat()
return
end
if self.enter_callback and chars == "\n" and not skip_callback then
UIManager:scheduleIn(0.3, function() self.enter_callback() end)
return
end
-- this is an addon to inputtext.lua
if self.strike_callback and not skip_callback then
self.strike_callback(chars)
return
end
-- the same as in inputtext.lua
if self.readonly or not self:isTextEditable(true) then
return
end
self.is_text_edited = true
if #self.charlist == 0 then -- widget text is empty or a hint text is displayed
self.charpos = 1 -- move cursor to the first position
end
-- this is a modification of inputtext.lua
local chars_list = util.splitToChars(chars) -- for UTF8
for i = 1, #chars_list do
if chars_list[i] == "\n" then
-- detect current column
local pos = self.charpos
while pos > 0 and self.charlist[pos] ~= "\n" do
pos = pos - 1
end
local column = self.charpos - pos
if self.scroll_region_line then
self:scrollRegionUp(column)
end
-- go to EOL
while self.charlist[self.charpos] and self.charlist[self.charpos] ~= "\n" do
self.charpos = self.charpos + 1
end
if not self.charlist[self.charpos] then -- add new line if necessary
table.insert(self.charlist, self.charpos, "\n")
self.charpos = self.charpos + 1
end
-- go to column in next line
for j = 1, column-1 do
if not self.charlist[self.charpos] then
table.insert(self.charlist, self.charpos, " ")
self.charpos = self.charpos + 1
else
break
end
end
if self.charlist[self.charpos] then
self.charpos = self.charpos + 1
end
-- fill line
pos = self.charpos
for j = column, self.maxc do
if not self.charlist[pos] then
table.insert(self.charlist, pos, " ")
end
pos = pos + 1
end
if not self.charlist[pos] then
table.insert(self.charlist, pos, "\n")
end
elseif chars_list[i] == "\r" then
if self.charlist[self.charpos] == "\n" then
self.charpos = self.charpos - 1
end
while self.charpos >= 1 and self.charlist[self.charpos] ~= "\n" do
self.charpos = self.charpos - 1
end
self.charpos = self.charpos + 1
elseif chars_list[i] == "\b" then
self.charpos = self.charpos - 1
else
if self.wrap then
if self.charlist[self.charpos] == "\n" then
self.charpos = self.charpos + 1
for j = 0, self.maxc-1 do
if not self.charlist[self.charpos + j] then
table.insert(self.charlist, self.charpos + j, " ")
end
end
end
else
local column = 1
local pos = self.charpos
while pos > 0 and self.charlist[pos] ~= "\n" do
pos = pos - 1
column = column + 1
end
if self.charlist[self.charpos] == "\n" or column > self.maxc then
self.charpos = self.charpos - 1
end
end
table.remove(self.charlist, self.charpos)
table.insert(self.charlist, self.charpos, chars_list[i])
self.charpos = self.charpos + 1
end
end
-- the same as in inputtext.lua
if not skip_table_concat then
self:initTextBox(table.concat(self.charlist), true)
end
end
dbg:guard(TermInputText, "addChars",
function(self, chars)
assert(type(chars) == "string",
"TermInputText: Wrong chars value type (expected string)!")
end)
function TermInputText:enterAlternateKeypad()
self.store_position = self.charpos
self:formatTerminal(true)
end
function TermInputText:exitAlternateKeypad()
if self.store_position then
self.charpos = self.store_position
self.store_position = nil
-- clear the alternate keypad buffer
while self.charlist[self.charpos] do
table.remove(self.charlist, self.charpos)
end
end
end
--- generates a "tty-matrix"
-- @param maxr number of rows
-- @param maxc number of columns
-- @param clear if true, fill the matrix ' '
function TermInputText:formatTerminal(clear)
local i = self.store_position or 1
-- so we end up in a maxr x maxc array for positioning
for r = 1, self.maxr do
for c = 1, self.maxc do
if not self.charlist[i] then -- end of text
table.insert(self.charlist, i, "\n")
end
if self.charlist[i] ~= "\n" then
if clear then
self.charlist[i] = ' '
end
else
table.insert(self.charlist, i, ' ')
end
i = i + 1
end
if self.charlist[i] ~= "\n" then
table.insert(self.charlist, i, "\n")
end
i = i + 1 -- skip newline
end
-- table.remove(self.charlist, i - 1)
end
function TermInputText:moveCursorToRowCol(r, c)
self:formatTerminal()
local cur_r, cur_c = 1, 0
local i = self.store_position or 1
while i < #self.charlist do
if self.charlist[i] ~= "\n" then
cur_c = cur_c + 1
else
cur_c = 0 -- as we are at the last NL
cur_r = cur_r + 1
end
self.charpos = i
if cur_r == r and cur_c == c then
break
end
i = i + 1
end
self:moveCursorToCharPos(self.charpos)
end
function TermInputText:clearToEndOfScreen()
local pos = self.charpos
while pos <= #self.charlist do
if self.charlist[pos] ~= "\n" then
self.charlist[pos] = " "
end
pos = pos + 1
end
self.is_text_edited = true
self:initTextBox(table.concat(self.charlist))
-- self:moveCursorToCharPos(self.charpos)
end
function TermInputText:delToEndOfLine()
if self.readonly or not self:isTextEditable(true) then
return
end
local cur_pos = self.charpos
-- self.charlist[self.charpos] is the char after the cursor
while self.charlist[cur_pos] and self.charlist[cur_pos] ~= "\n" do
self.charlist[cur_pos] = " "
cur_pos = cur_pos + 1
end
self:initTextBox(table.concat(self.charlist))
end
function TermInputText:reverseLineFeed(skip_callback)
if self.strike_callback and not skip_callback then
self.strike_callback(esc_seq.page_down)
return
end
if self.charpos > 1 and self.charlist[self.charpos] == "\n" then
self.charpos = self.charpos - 1
end
local cur_col = 0
while self.charpos > 1 and self.charlist[self.charpos] ~= "\n" do
self.charpos = self.charpos - 1
cur_col = cur_col + 1
end
if self.charpos > 1 then
self.charpos = self.charpos + 1
end
for i = 1, 80 do
table.insert(self.charlist, self.charpos, " ")
end
end
------------------------------------------------------------------
-- overridden InputText methods --
------------------------------------------------------------------
function TermInputText:leftChar(skip_callback)
if self.charpos == 1 then return end
if self.strike_callback and not skip_callback then
self.strike_callback(esc_seq.cursor_left)
return
end
local left_char = self.charlist[self.charpos - 1]
if not left_char or left_char == "\n" then
return
end
--InputText.leftChar(self)
self.charpos = self.charpos - 1
end
function TermInputText:rightChar(skip_callback)
if self.strike_callback and not skip_callback then
self.strike_callback(esc_seq.cursor_right)
return
end
if self.charpos > #self.charlist then return end
local right_char = self.charlist[self.charpos + 1]
if not right_char and right_char == "\n" then
return
end
InputText.rightChar(self)
end
function TermInputText:moveCursorUp()
local pos = self.charpos
while self.charlist[pos] and self.charlist[pos] ~= "\n" do
pos = pos - 1
end
local column = self.charpos - pos
pos = pos - 1
while self.charlist[pos] and self.charlist[pos] ~= "\n" do
pos = pos - 1
end
self.charpos = pos + column
self:moveCursorToCharPos(self.charpos)
end
function TermInputText:moveCursorDown()
local pos = self.charpos
-- detect current column
while pos > 0 and self.charlist[pos] ~= "\n" do
pos = pos - 1
end
local column = self.charpos - pos
while self.charlist[self.charpos] and self.charlist[self.charpos] ~= "\n" do
self.charpos = self.charpos + 1
end
self.charpos = self.charpos + 1
for i = 1, column-1 do
if self.charlist[pos+i] or self.charlist[pos+i] ~= "\n" then
self.charpos = self.charpos + 1
else
break
end
end
self:moveCursorToCharPos(self.charpos)
end
function TermInputText:delChar()
if self.readonly or not self:isTextEditable(true) then
return
end
if self.charpos == 1 then return end
if self.strike_callback then
self.strike_callback(esc_seq.backspace)
return
end
InputText.delChar(self)
end
function TermInputText:delToStartOfLine()
return
end
function TermInputText:scrollDown(skip_callback)
if self.strike_callback and not skip_callback then
self.strike_callback(esc_seq.page_down)
return
end
InputText.scrollDown(self)
end
function TermInputText:scrollUp(skip_callback)
if self.strike_callback and not skip_callback then
self.strike_callback(esc_seq.page_up)
return
end
InputText.scrollUp(self)
end
function TermInputText:goToStartOfLine(skip_callback)
if self.strike_callback then
if not skip_callback then
self.strike_callback(esc_seq.cursor_pos1)
else
if self.charlist[self.charpos] == "\n" then
self.charpos = self.charpos - 1
end
while self.charpos >= 1 and self.charlist[self.charpos] ~= "\n" do
self.charpos = self.charpos - 1
end
self.charpos = self.charpos + 1
self.text_widget:moveCursorToCharPos(self.charpos)
end
return
end
InputText.goToStartOfLine(self)
end
function TermInputText:goToEndOfLine(skip_callback)
if self.strike_callback then
if not skip_callback then
self.strike_callback(esc_seq.cursor_end)
else
while self.charpos <= #self.charlist and self.charlist[self.charpos] ~= "\n" do
self.charpos = self.charpos + 1
end
end
self.text_widget:moveCursorToCharPos(self.charpos)
return
end
InputText.goToEndOfLine(self)
end
function TermInputText:upLine(skip_callback)
if self.strike_callback and not skip_callback then
self.strike_callback(esc_seq.cursor_up)
return
end
InputText.upLine(self)
end
function TermInputText:downLine(skip_callback)
if #self.charlist == 0 then return end -- Avoid cursor moving within a hint.
if self.strike_callback and not skip_callback then
self.strike_callback(esc_seq.cursor_down)
return
end
InputText.downLine(self)
end
return TermInputText
| agpl-3.0 |
ashkanpj/yagoopfire | plugins/torrent_search.lua | 223 | 1059 | local https = require ('ssl.https')
local ltn12 = require ("ltn12")
local function search_kickass(query)
local url = 'https://kat.cr/json.php?q='..URL.escape(query)
local resp = {}
local b,c = https.request
{
url = url,
protocol = "tlsv1",
sink = ltn12.sink.table(resp)
}
resp = table.concat(resp)
local data = json:decode(resp)
local text = 'Results: '..data.total_results..'\n\n'
local results = math.min(#data.list, 5)
for i=1,results do
local torrent = data.list[i]
local link = torrent.torrentLink
link = link:gsub('%?title=.+','')
text = text..torrent.title
..'\n'..'Seeds: '..torrent.seeds
..' '..'Leeches: '..torrent.leechs
..'\n'..link
--..'\n magnet:?xt=urn:btih:'..torrent.hash
..'\n\n'
end
return text
end
local function run(msg, matches)
local query = matches[1]
return search_kickass(query)
end
return {
description = "Search Torrents",
usage = "!torrent <search term>: Search for torrent",
patterns = {
"^!torrent (.+)$"
},
run = run
}
| gpl-2.0 |
Lsty/ygopro-scripts | c69042950.lua | 5 | 1878 | --バグ・ロード
function c69042950.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c69042950.target)
e1:SetOperation(c69042950.activate)
c:RegisterEffect(e1)
end
function c69042950.mfilter(c,clv)
return c:IsFaceup() and c:GetLevel()==clv
end
function c69042950.mfilter2(c)
return c:IsFaceup() and c:IsLevelBelow(4)
end
function c69042950.spfilter(c,e,tp)
local lv=c:GetLevel()
return lv>0 and lv<=4 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and Duel.IsExistingMatchingCard(c69042950.mfilter,tp,LOCATION_MZONE,0,1,nil,lv)
end
function c69042950.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c69042950.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp)
and Duel.IsExistingMatchingCard(c69042950.mfilter2,tp,0,LOCATION_MZONE,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c69042950.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c69042950.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()~=0 then
Duel.SpecialSummonStep(g:GetFirst(),0,tp,tp,false,false,POS_FACEUP)
end
end
if Duel.GetLocationCount(1-tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c69042950.spfilter,1-tp,LOCATION_HAND,0,1,nil,e,1-tp)
and Duel.SelectYesNo(1-tp,aux.Stringid(69042950,0)) then
Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(1-tp,c69042950.spfilter,1-tp,LOCATION_HAND,0,1,1,nil,e,1-tp)
if g:GetCount()~=0 then
Duel.SpecialSummonStep(g:GetFirst(),0,1-tp,1-tp,false,false,POS_FACEUP)
end
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
Lsty/ygopro-scripts | c38318146.lua | 9 | 1439 | --暴君の暴力
function c38318146.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c38318146.cost)
c:RegisterEffect(e1)
--activate cost
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_ACTIVATE_COST)
e2:SetRange(LOCATION_SZONE)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetTargetRange(0,1)
e2:SetCondition(c38318146.accon)
e2:SetTarget(c38318146.actarget)
e2:SetCost(c38318146.accost)
e2:SetOperation(c38318146.acop)
c:RegisterEffect(e2)
end
function c38318146.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,nil,2,nil) end
local rg=Duel.SelectReleaseGroup(tp,nil,2,2,nil)
Duel.Release(rg,REASON_COST)
end
function c38318146.accon(e)
c38318146[0]=false
return true
end
function c38318146.acfilter(c)
return c:IsType(TYPE_SPELL) and c:IsAbleToGraveAsCost()
end
function c38318146.actarget(e,te,tp)
return te:IsActiveType(TYPE_SPELL) and te:IsHasType(EFFECT_TYPE_ACTIVATE)
end
function c38318146.accost(e,te,tp)
return Duel.IsExistingMatchingCard(c38318146.acfilter,tp,LOCATION_DECK,0,1,nil)
end
function c38318146.acop(e,tp,eg,ep,ev,re,r,rp)
if c38318146[0] then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c38318146.acfilter,tp,LOCATION_DECK,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
c38318146[0]=true
end
| gpl-2.0 |
Lsty/ygopro-scripts | c80978111.lua | 3 | 1557 | --飛翔するG
function c80978111.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(80978111,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCondition(c80978111.condition)
e1:SetTarget(c80978111.target)
e1:SetOperation(c80978111.operation)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
--
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetTargetRange(1,0)
e3:SetTarget(c80978111.splimit)
c:RegisterEffect(e3)
end
function c80978111.cfilter(c,tp)
return c:GetSummonPlayer()==tp
end
function c80978111.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c80978111.cfilter,1,nil,1-tp)
end
function c80978111.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(1-tp,LOCATION_MZONE,tp)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c80978111.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.GetLocationCount(1-tp,LOCATION_MZONE,tp)>0 then
Duel.SpecialSummon(c,0,tp,1-tp,false,false,POS_FACEUP_DEFENCE)
end
end
function c80978111.splimit(e,c,tp,sumtp,sumpos)
return bit.band(sumtp,SUMMON_TYPE_XYZ)==SUMMON_TYPE_XYZ
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/items/inferno_sword.lua | 12 | 1073 | -----------------------------------------
-- ID: 16594
-- Item: Inferno Sword
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------
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, dsp.magic.ele.FIRE, target, dmg, params)
dmg = dmg * applyResistanceAddEffect(player,target,dsp.magic.ele.FIRE,0)
dmg = adjustForTarget(target,dmg,dsp.magic.ele.FIRE)
dmg = finalMagicNonSpellAdjustments(player,target,dsp.magic.ele.FIRE,dmg)
local message = dsp.msg.basic.ADD_EFFECT_DMG
if (dmg < 0) then
message = dsp.msg.basic.ADD_EFFECT_HEAL
end
return dsp.subEffect.FIRE_DAMAGE,message,dmg
end
end | gpl-3.0 |
avinashThummala/Boundary_Luvit_PingCheck | init.lua | 1 | 2214 | local boundary = require('boundary')
local ping = require('ping')
local timer = require('timer')
local async = require('async')
local HOST_IS_DOWN = -1
local param = boundary.param
--[[
If we do not have a poll Interval for the plugin set it
each host has its own poll interval
]]
local pollInterval = param.pollInterval or 1000
-- Keep track of the host's last polled time so we don't hammer the host
local previous = {}
function logSuccess(source, duration)
io.stdout:write('PING_RESPONSETIME '..duration..' '..source..'\n')
end
function logFailure(err, source, duration)
if (err) then
io.stderr:write(err .. '\n')
else
io.stdout:write('PING_RESPONSETIME '..HOST_IS_DOWN..' '..source..'\n')
end
end
function complete(err)
if (err) then io.stderr:write(err) end
end
-- Validate we have Hosts to ping
if (not param.items) then
io.stdout:write('No configuration has been setup yet, so we\'re exiting\n')
os.exit(1);
end
-- Validate the hosts intervals
table.foreach(param.items, function(hIndex)
local host = param.items[hIndex]
local pollInterval = 5
if host.pollInterval then
pollInterval = tonumber(host.pollInterval)
end
--Lets assume that the poll interval associated with hosts is provided in seconds
host.pollInterval = pollInterval
end)
function pingHost(host, cb)
-- Check if we need to poll again
local source = host.source
if(not previous[source]) then
previous[source] = os.time()
end
local now = os.time()
if ( (previous[source] + host.pollInterval) > now ) then
return cb(nil)
else
previous[source] = now
end
-- Ping the host
ping.ping(host.host, function(err, responseTime)
if (err) then
logFailure(err, source, responseTime)
elseif (responseTime == nil or responseTime < 0) then
logFailure(nil, source, responseTime)
else
logSuccess(source, responseTime)
end
return cb(nil)
end)
end
function poll()
async.forEach(param.items, pingHost, complete)
timer.setTimeout(pollInterval, poll)
end
-- Lets get the party started
poll() | apache-2.0 |
Lsty/ygopro-scripts | c39987164.lua | 5 | 3138 | --ヴァイロン・ディシグマ
function c39987164.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,4,3)
c:EnableReviveLimit()
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(39987164,0))
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c39987164.eqcost)
e1:SetTarget(c39987164.eqtg)
e1:SetOperation(c39987164.eqop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(39987164,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_BATTLE_START)
e2:SetCondition(c39987164.descon)
e2:SetTarget(c39987164.destg)
e2:SetOperation(c39987164.desop)
c:RegisterEffect(e2)
end
function c39987164.eqcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c39987164.filter(c)
return c:IsFaceup() and c:IsAttackPos() and c:IsType(TYPE_EFFECT) and c:IsAbleToChangeControler()
end
function c39987164.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c39987164.filter(chkc) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c39987164.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
local g=Duel.SelectTarget(tp,c39987164.filter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0)
end
function c39987164.eqlimit(e,c)
return e:GetOwner()==c
end
function c39987164.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) and tc:IsAttackPos() and tc:IsRelateToEffect(e) then
if c:IsFaceup() and c:IsRelateToEffect(e) then
if not Duel.Equip(tp,tc,c,false) then return end
--Add Equip limit
tc:RegisterFlagEffect(39987164,RESET_EVENT+0x1fe0000,0,0)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_COPY_INHERIT+EFFECT_FLAG_OWNER_RELATE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(c39987164.eqlimit)
tc:RegisterEffect(e1)
else Duel.SendtoGrave(tc,REASON_EFFECT) end
end
end
function c39987164.desfilter(c,att)
return c:GetFlagEffect(39987164)~=0 and c:IsAttribute(att)
end
function c39987164.descon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local dt=Duel.GetAttacker()
if dt==c then dt=Duel.GetAttackTarget() end
if not dt or dt:IsFacedown() then return false end
e:SetLabelObject(dt)
local att=dt:GetAttribute()
return c:GetEquipGroup():IsExists(c39987164.desfilter,1,nil,att)
end
function c39987164.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetLabelObject(),1,0,0)
end
function c39987164.desop(e,tp,eg,ep,ev,re,r,rp)
local dt=e:GetLabelObject()
if dt:IsRelateToBattle() then
Duel.Destroy(dt,REASON_EFFECT)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c55428811.lua | 3 | 1556 | --ホープ・オブ・フィフス
function c55428811.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c55428811.target)
e1:SetOperation(c55428811.activate)
c:RegisterEffect(e1)
end
function c55428811.filter(c)
return c:IsSetCard(0x3008) and c:IsAbleToDeck()
end
function c55428811.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c55428811.filter(chkc) end
local dc=2
if not Duel.IsExistingMatchingCard(nil,tp,LOCATION_HAND+LOCATION_ONFIELD,0,1,e:GetHandler()) then dc=3 end
if chk==0 then return Duel.IsPlayerCanDraw(tp,dc)
and Duel.IsExistingTarget(c55428811.filter,tp,LOCATION_GRAVE,0,5,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c55428811.filter,tp,LOCATION_GRAVE,0,5,5,nil)
e:SetLabel(dc)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,dc)
end
function c55428811.activate(e,tp,eg,ep,ev,re,r,rp)
local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if not tg or tg:FilterCount(Card.IsRelateToEffect,nil,e)~=5 then return end
Duel.SendtoDeck(tg,nil,0,REASON_EFFECT)
local g=Duel.GetOperatedGroup()
local ct=g:FilterCount(Card.IsLocation,nil,LOCATION_DECK+LOCATION_EXTRA)
if ct==5 then
Duel.ShuffleDeck(tp)
Duel.BreakEffect()
Duel.Draw(tp,e:GetLabel(),REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Attohwa_Chasm/Zone.lua | 12 | 3751 | -----------------------------------
--
-- Zone: Attohwa_Chasm (7)
--
-----------------------------------
local ID = require("scripts/zones/Attohwa_Chasm/IDs")
require("scripts/globals/settings")
require("scripts/globals/helm")
require("scripts/globals/zone")
-----------------------------------
function onInitialize(zone)
-- Poison Flowers!
zone:registerRegion(1, -475.809, 5, 316.499, 0,0,0);
zone:registerRegion(2, -440.938, 7, 281.749, 0,0,0);
zone:registerRegion(3, -388.027, 5, 264.831, 0,0,0);
zone:registerRegion(4, -534.104, 5, 217.833, 0,0,0);
zone:registerRegion(5, -530.000, 5, 210.000, 0,0,0);
zone:registerRegion(6, -482.192, 5, 198.647, 0,0,0);
zone:registerRegion(7, -595.756, 7, 157.532, 0,0,0);
zone:registerRegion(8, -514.000, 5, 166.000, 0,0,0);
zone:registerRegion(9, -396.844, 5, 164.790, 0,0,0);
zone:registerRegion(10, -382.919, 5, 143.572, 0,0,0);
zone:registerRegion(11, -537.558, 5, 102.683, 0,0,0);
zone:registerRegion(12, -393.979, 5, 101.877, 0,0,0);
zone:registerRegion(13, -367.892, 5, 75.774, 0,0,0);
zone:registerRegion(14, -369.333, 5, 69.333, 0,0,0);
zone:registerRegion(15, -351.717, 5, 64.773, 0,0,0);
zone:registerRegion(16, -386.000, 5, 50.000, 0,0,0);
zone:registerRegion(17, -360.705, 5, 51.505, 0,0,0);
zone:registerRegion(18, -475.667, 5, 37.081, 0,0,0);
zone:registerRegion(19, -321.902, 5, 36.697, 0,0,0);
zone:registerRegion(20, -351.916, 5, 10.501, 0,0,0);
zone:registerRegion(21, -554.739, 5, -3.057, 0,0,0);
zone:registerRegion(22, -397.667, 5, -5.563, 0,0,0);
zone:registerRegion(23, -330.062, 5, -18.832, 0,0,0);
zone:registerRegion(24, -233.015, 5, -19.049, 0,0,0);
zone:registerRegion(25, -553.523, 5, -72.071, 0,0,0);
zone:registerRegion(26, -535.904, 7, -67.914, 0,0,0);
zone:registerRegion(27, -435.438, 5, -74.171, 0,0,0);
zone:registerRegion(28, -369.343, 5, -73.449, 0,0,0);
zone:registerRegion(29, -238, 5, -118, 0,0,0);
zone:registerRegion(30, -385.349, 5, -173.973, 0,0,0);
UpdateNMSpawnPoint(ID.mob.TIAMAT);
GetMobByID(ID.mob.TIAMAT):setRespawnTime(math.random(86400, 259200));
dsp.helm.initZone(zone, dsp.helm.type.EXCAVATION)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-194.487,-13.766,338.704,141);
end
return cs;
end;
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onRegionEnter(player,region)
-- TODO: Gasponia's shouldn't "always" poison you. However, in retail regions constantly reapply themselves without having to re-enter the region. In DSP that doesn't happen so I'm leaving it as-is for now.
local regionId = region:GetRegionID();
if (regionId <= 30) then
local gasponia = GetNPCByID(ID.npc.GASPONIA_OFFSET + (regionId - 1));
if (gasponia ~= nil) then
gasponia:openDoor(3);
if (not player:hasStatusEffect(dsp.effect.POISON)) then
player:addStatusEffect(dsp.effect.POISON, 15, 0, math.random(30,60));
player:messageSpecial(ID.text.GASPONIA_POISON);
end
end
end
end;
function onRegionLeave(player,region)
end;
function onGameHour(zone)
--[[
the hard-coded id that was here was wrong. there are 22 miasmas in attohwa chasm
starting at ID.npc.MIASMA_OFFSET. some are supposed to toggle open, but need retail test
to determine which. for now, they're just statically set per npc_list.animation
--]]
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end; | gpl-3.0 |
Lsty/ygopro-scripts | c73507661.lua | 3 | 1157 | --妖精の風
function c73507661.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetTarget(c73507661.target)
e1:SetOperation(c73507661.activate)
c:RegisterEffect(e1)
end
function c73507661.filter(c)
return c:IsFaceup() and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable()
end
function c73507661.target(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return Duel.IsExistingMatchingCard(c73507661.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,c) end
local sg=Duel.GetMatchingGroup(c73507661.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,c)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,sg,sg:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,PLAYER_ALL,sg:GetCount()*300)
end
function c73507661.activate(e,tp,eg,ep,ev,re,r,rp)
local sg=Duel.GetMatchingGroup(c73507661.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler())
local ct=Duel.Destroy(sg,REASON_EFFECT)
Duel.Damage(tp,ct*300,REASON_EFFECT)
Duel.Damage(1-tp,ct*300,REASON_EFFECT)
end
| gpl-2.0 |
misterdustinface/snow | snow/src/TestBoots/reports/translate.lua | 3 | 1635 | -- Copyright (C) 2015 Dustin Shaffer
-- Licensed under the GNU GENERAL PUBLIC LICENSE, Version 2
LANGUAGE = "ENGLISH"
local translations = {
["X"] = {
["TEST"] = "X",
["RESULT"] = "X",
["EXPECTED"] = "X",
["OPERATION"] = "X",
["RECEIVED"] = "X",
["LABEL"] = "X",
["PASS"] = "X",
["FAIL"] = "X",
["PASSED ALL TESTS"] = "X",
["RAN"] = "X",
["TESTS"] = "X",
["PASSED"] = "X",
["FAILED"] = "X",
["EXPLOSIONS"] = "X",
["TIME"] = "X",
["sec"] = "X",
["SEED"] = "X",
["TEST PASSED"] = "X",
["TEST FAILED"] = "X",
["INVALID TEST"] = "X",
["( X__X )"] = "( X__X )",
},
["FRENCH"] = {
["TEST"] = "test",
["RESULT"] = "résultat",
["EXPECTED"] = "attendu",
["OPERATION"] = "opération",
["RECEIVED"] = "reçu",
["LABEL"] = "étiquette",
["PASS"] = "moyenne",
["FAIL"] = "manquer",
["PASSED ALL TESTS"] = "passé tous les tests",
["RAN"] = "courut",
["TESTS"] = "essais",
["PASSED"] = "passé",
["FAILED"] = "échoué",
["EXPLOSIONS"] = "explosions",
["TIME"] = "temps d'exécution",
["sec"] = "secondes",
["SEED"] = "graine",
["TEST PASSED"] = "test réussi",
["TEST FAILED"] = "test a échoué",
["INVALID TEST"] = "essai non valide",
["( X__X )"] = "( X__X )",
}
}
function setLanguage(xLang)
if translations[xLang] then
LANGUAGE = xLang
end
end
function T(xString)
local translation
if LANGUAGE == "ENGLISH" then
translation = xString
else
translation = translations[LANGUAGE][xString] or xString
end
return translation
end | gpl-2.0 |
tarulas/luadch | core/cfg.lua | 1 | 104886 | --[[
cfg.lua by blastbeat
v0.48: by tarulas
- basic settings:
- added "disable_email" option
- added "hub_listen" option
- added "forbid_plaintext" option
- added "hadm_password" option
v0.47: by pulsar
- etc_trafficmanager.lua settings:
- added "etc_trafficmanager_check_minshare" function
v0.46: by pulsar
- added usr_uptime.lua settings
- added "usr_uptime_permission" function
- added "usr_uptime_minlevel" function
- added "usr_uptime.lua" to scriptstable
- optimized loadlanguage() function a little bit
- added checkusers()
- make a user.tbl.bak backup on start; restore corrupt user.tbl if a backup exists
- cmd_nickchange.lua settings:
- removed "cmd_nickchange_maxnicklength" function
- basic settings:
- added "min_nickname_length" function
- added "max_nickname_length" function
v0.45: by pulsar
- cmd_gag settings:
- added "cmd_gag_user_notifiy" function
- cmd_rules.lua settings:
- removed "cmd_rules_rules" function
- cmd_setpass.lua settings:
- renamed "cmd_setpass_min_length" function to "min_password_length" function
- moved "min_password_length" function to basic settings
- etc_banner.lua settings:
- removed "etc_banner_banner" function
- etc_motd.lua settings:
- removed "etc_motd_motd" function
- etc_trafficmanager.lua settings:
- removed "etc_trafficmanager_block_ctm" function
- removed "etc_trafficmanager_block_rcm" function
- removed "etc_trafficmanager_block_sch" function
- usr_hide_share.lua settings:
- added "usr_hide_share_restrictions" function
- changed "usr_hide_share_permission" function
- basic settings:
- added "max_password_length" function
v0.44: by pulsar
- hub_runtime.lua settings:
- added "hub_runtime_minlevel" function
- added "hub_runtime_report" function
- added "hub_runtime_report_opchat" function
- added "hub_runtime_report_hubbot" function
- added "hub_runtime_llevel" function
- cmd_setpass.lua settings:
- renamed "cmd_setpas_permission" to "cmd_setpass_permission"
- renamed "cmd_setpas_advanced_rc" to "cmd_setpass_advanced_rc"
- renamed "cmd_setpas_min_length" to "cmd_setpass_min_length"
- etc_cmdlog.lua settings:
- changed "etc_cmdlog_command_tbl"
- improved out_error messages
v0.43: by blastbeat
- changes in saveusers() function
v0.42: by pulsar
- etc_trafficmanager.lua settings:
- added "etc_trafficmanager_send_loop" function
- added "etc_trafficmanager_loop_time" function
- cmd_topic.lua settings:
- added "cmd_topic_report" function
- added "cmd_topic_report_hubbot" function
- added "cmd_topic_report_opchat" function
- added "cmd_topic_llevel" function
- cmd_setpas.lua settings:
- added "cmd_setpas_min_length" function
- cmd_unban.lua settings:
- removed "cmd_unban_report" function
- removed "cmd_unban_report_hubbot" function
- removed "cmd_unban_report_opchat" function
- removed "cmd_unban_llevel" function
- etc_motd.lua settings:
- added "etc_motd_activate" function
- added "cmd_sslinfo.lua settings"
- added "cmd_sslinfo_minlevel" function
- etc_userlogininfo.lua settings:
- added "etc_userlogininfo_activate" function
- cmd_myinf.lua settings:
- added "cmd_myinf_permission"
- bot_regchat.lua settings:
- added "bot_regchat_oplevel" function
- bot_opchat.lua settings:
- added "bot_opchat_oplevel" function
- scripts table:
- changed the order of some scripts
- renamed "cmd_setpas.lua" to "cmd_setpass.lua"
- added "cmd_sslinfo.lua"
- added "cmd_myinf.lua"
- removed "hub_pass" function
v0.41: by pulsar
- usr_redirect.lua settings:
- changed comment title part from "usr_redirect.lua settings" to "cmd_redirect.lua settings"
- changed var names:
- from "usr_redirect_activate" to "cmd_redirect_activate"
- from "usr_redirect_permission" to "cmd_redirect_permission"
- from "usr_redirect_level" to "cmd_redirect_level"
- from "usr_redirect_url" to "cmd_redirect_url"
- from "usr_redirect_report" to "cmd_redirect_report"
- from "usr_redirect_report_opchat" to "cmd_redirect_report_opchat"
- from "usr_redirect_report_hubbot" to "cmd_redirect_report_hubbot"
- from "usr_redirect_llevel" to "cmd_redirect_llevel"
- changed "usr_redirect.lua" to "cmd_redirect.lua" in scripttable
- added "cafile" param to the SSL parameter settings
- etc_motd.lua settings:
- add "etc_motd_destination_main" function
- add "etc_motd_destination_pm" function
- cmd_rules.lua settings:
- add "cmd_rules_destination_main" function
- add "cmd_rules_destination_pm" function
v0.40: by pulsar
- usr_redirect.lua settings:
- add "usr_redirect_permission" function
v0.39: by pulsar
- etc_trafficmanager.lua settings:
- add "etc_trafficmanager_permission" function
- add "etc_trafficmanager_report" function
- add "etc_trafficmanager_report_hubbot" function
- add "etc_trafficmanager_report_opchat" function
- add "etc_trafficmanager_llevel" function
- etc_msgmanager.lua settings:
- add "etc_msgmanager_activate" function
- add "etc_msgmanager_permission" function
- add "etc_msgmanager_report" function
- add "etc_msgmanager_report_hubbot" function
- add "etc_msgmanager_report_opchat" function
- add "etc_msgmanager_llevel" function
- etc_cmdlog.lua settings:
- added "trafficmanager" to command table
- cmd_ban.lua settings:
- removed "cmd_ban_minlevel" function
- cmd_unban.lua settings:
- removed "cmd_unban_minlevel" function
- cmd_reg.lua settings:
- removed "cmd_reg_minlevel" function
- cmd_delreg.lua settings:
- removed "cmd_delreg_minlevel" function
- cmd_upgrade.lua settings:
- removed "cmd_upgrade_minlevel" function
- cmd_accinfo.lua settings:
- removed "cmd_accinfo_minlevel" function
- removed "cmd_accinfo_oplevel" function
- cmd_setpas.lua settings:
- removed "cmd_setpas_oplevel" function
- cmd_userinfo.lua settings:
- removed "cmd_userinfo_minlevel" function
- cmd_gag.lua settings:
- removed "cmd_gag_minlevel" function
- cmd_reload.lua settings:
- removed "cmd_reload_minlevel" function
- cmd_restart.lua settings:
- removed "cmd_restart_minlevel" function
- cmd_shutdown.lua settings:
- removed "cmd_shutdown_minlevel" function
- cmd_errors.lua settings:
- removed "cmd_errors_minlevel" function
- cmd_mass.lua settings:
- removed "cmd_mass_minlevel" function
- etc_chatlog.lua settings:
- removed "etc_chatlog_min_level" function
- etc_offlineusers.lua settings:
- removed "etc_offlineusers_min_level" function
v0.38: by pulsar
- added: level 55 [SBOT] to all script permissions
- changing default permission values of some scripts
v0.37: by pulsar
- added: functions for "usr_redirect.lua settings"
- added: "usr_redirect.lua" to scripttable
v0.36: by pulsar
- etc_trafficmanager.lua settings:
- add "etc_trafficmanager_sharecheck"
v0.35: by pulsar
- add "hub_runtime.lua" to scripttable
- removed "cmd_error.lua" from scripttable
v0.34: by pulsar
- usr_hubs.lua settings: / thx DerWahre
- add "usr_hubs_report" function
- add "usr_hubs_report_hubbot" function
- add "usr_hubs_report_opchat" function
- add "usr_hubs_llevel" function
- cmd_accinfo.lua settings:
- add "cmd_accinfo_minlevel" function
- etc_offlineusers.lua settings:
- add "etc_offlineusers_max_offline_days_auto" function
- add "etc_offlineusers_report" function
- add "etc_offlineusers_report_hubbot" function
- add "etc_offlineusers_report_opchat" function
- add "etc_offlineusers_llevel" function
- bot_regchat.lua settings:
- add "bot_regchat_activate" function
- bot_opchat.lua settings:
- add "bot_opchat_activate" function
v0.33: by pulsar
- changes in "ssl_params"
v0.32: by pulsar
- add "etc_ccpmblocker.lua" function
- add "etc_ccpmblocker.lua" to scripttable
v0.31: by pulsar
- changing TLS Cipher from: "AES256-SHA" to "ECDHE-RSA-AES256-SHA"
v0.30: by pulsar
- removed: cmd_managebans.lua functions
- removed: cmd_managebans.lua from scriptlist
- etc_dhtblocker.lua settings:
- add "etc_dhtblocker.lua" to scripttable
- add "etc_dhtblocker_activate" function
- add "etc_dhtblocker_block_level" function
- add "etc_dhtblocker_block_time" function
- add "etc_dhtblocker_report" function
- add "etc_dhtblocker_report_toopchat" function
- add "etc_dhtblocker_report_hubbot" function
- add "etc_dhtblocker_report_level" function
v0.29: by pulsar
- bot_regchat.lua settings:
- add "bot_regchat_history" function
- add "bot_regchat_max_entrys" function
- bot_opchat.lua settings:
- add "bot_opchat_history" function
- add "bot_opchat_max_entrys" function
v0.28: by pulsar
- bot_opchat.lua settings:
- removed "bot_opchat_activate" function
- bot_regchat.lua settings:
- removed "bot_regchat_activate" function
v0.27: by pulsar
- etc_banner.lua settings:
- added "etc_banner_activate" function
- cmd_delreg.lua settings:
- changing type of permission table function (array of integer instead of array of boolean)
- add level 0 to "min_share" function
- add level 0 to "max_share" function
- add level 0 to "min_slots" function
- add level 0 to "max_slots" function
- add level 0 to "cmd_ban_permission" function
- add level 0 to "cmd_unban_permission" function
- add level 0 to "cmd_reg_permission" function
- add level 0 to "cmd_delreg_permission" function
- add level 0 to "cmd_upgrade_permission" function
- add level 0 to "cmd_accinfo_permission" function
- add level 0 to "cmd_setpas_permission" function
- add level 0 to "cmd_userinfo_permission" function
- add level 0 to "cmd_gag_permission" function
v0.26: by pulsar
- usr_share.lua settings:
- remove "usr_share_godlevel" function
- change "min_share" function
- change "max_share" function
- usr_slots.lua settings:
- remove "usr_slots_godlevel" function
- change "min_slots" function
- change "max_slots" function
v0.25: by pulsar
- cmd_ban.lua settings:
- added "cmd_ban_report_hubbot" function
- added "cmd_ban_report_opchat" function
- cmd_unban.lua settings:
- added "cmd_unban_report_hubbot" function
- added "cmd_unban_report_opchat" function
- cmd_reg.lua settings:
- added "cmd_reg_report_hubbot" function
- added "cmd_reg_report_opchat" function
- cmd_delreg.lua settings:
- added "cmd_delreg_report_hubbot" function
- added "cmd_delreg_report_opchat" function
- cmd_disconnect.lua settings:
- added "cmd_disconnect_report_hubbot" function
- added "cmd_disconnect_report_opchat" function
- cmd_gag.lua settings:
- added "cmd_gag_report" function
- added "cmd_gag_report_hubbot" function
- added "cmd_gag_report_opchat" function
- cmd_nickchange.lua settings:
- added "cmd_nickchange_report_hubbot" function
- added "cmd_nickchange_report_opchat" function
- cmd_upgrade.lua settings:
- added "cmd_upgrade_report" function
- added "cmd_upgrade_report_hubbot" function
- added "cmd_upgrade_report_opchat" function
- added "cmd_upgrade_llevel" function
v0.24: by pulsar
- added "etc_msgmanager.lua" to scripttable
- added "etc_msgmanager.lua" functions
v0.23: by pulsar
- added "cmd_pm2offliners_advanced_rc" function
- added "cmd_accinfo_advanced_rc" function
- added "cmd_setpas_advanced_rc" function
- added "cmd_nickchange_advanced_rc" function
- added "cmd_upgrade_advanced_rc" function
v0.22: by pulsar
- small permission fix in "bot_pm2ops.lua settings"
- added "bot_regchat.lua" function
- added "bot_opchat.lua" function
v0.21: by pulsar
- added "bot_pm2ops.lua" to scripttable
- added "bot_pm2ops.lua" functions
v0.20: by pulsar
- added "usr_hide_share.lua" to scripttable
- added "usr_hide_share.lua" functions
v0.19: by pulsar
- added permission table to: "usr_nick_prefix.lua"
- possibility to choose which levels should be tagged
- added permission table to: "usr_desc_prefix.lua"
- possibility to choose which levels should be tagged
- added "cmd_hubstats.lua" to scripttable
- added "cmd_hubstats.lua" function
v0.18: by pulsar
- added "etc_records.lua" to scripttable
- added "etc_records.lua" functions
- added "bot_session_chat.lua" to scripttable
- added "bot_session_chat.lua" functions
- added "cmd_myip.lua" to scripttable
v0.17: by pulsar
- added "cmd_nickchange.lua" to scripttable
- added "cmd_nickchange.lua" functions
- added "nickchange" to "etc_cmdlog_command_tbl"
- added "etc_trafficmanager.lua" to scripttable
- added "etc_trafficmanager.lua" functions
- added "cmd_gag.lua" to scripttable
- added "cmd_gag.lua" functions
v0.16: by pulsar
- added "cmd_slots.lua" to scripttable
- added "cmd_slots_minlevel" permission
v0.15: by pulsar
- added "max_hubs" permission for script: "usr_hubs.lua"
- added "bot_regchat.lua" to scripttable
v0.14: by pulsar
- added "hub_bot_cleaner.lua" to scripttable
v0.13: by pulsar
- added "cmd_usersearch.lua" functions
- added "cmd_usersearch.lua" to scripttable
- added "cmd_uptime.lua" function
- added "cmd_uptime.lua" to scripttable
- added "cmd_setpas_oplevel" function
v0.12: by pulsar
- added "onlogin" function for script: "cmd_hubinfo.lua"
- removed "etc_userlogininfo_line" function
v0.11: by pulsar
- added "cmd_mass_oplevel" function
v0.10: by pulsar
- renamed "cmd_version.lua" to "cmd_hubinfo.lua" in scriptlist
- renamed "cmd_version_minlevel" to "cmd_hubinfo_minlevel" function
v0.09: by pulsar
- added "cmd_topic.lua" function
- added "cmd_topic.lua" to scripttable
- added "etc_chatlog.lua" functions
- added "etc_chatlog.lua" to scripttable
v0.08: by pulsar
- removed "etc_cmdlog_label_top" and "etc_cmdlog_label_bottom" function
v0.07: by pulsar
- added "cmd_pm2offliners.lua" functions
v0.06: by pulsar
- rename scriptname from "etc_pm2offliners" to "cmd_pm2offliners"
- import scriptsettings from "scripts/cmd_pm2offliners.lua"
v0.05: by pulsar
- added "etc_pm2offliners.lua" to scripttable
v0.04: by pulsar
- removed "hub_user_ranks.lua" from scripttable
v0.03: by pulsar
- added scriptsettings to "/cfg/cfg.tbl"
v0.02: by pulsar
- added keyprint feature
v0.01: by blastbeat
- this script manages the configuration files
]]--
----------------------------------// DECLARATION //--
--// lua functions //--
local type = use "type"
local pairs = use "pairs"
local ipairs = use "ipairs"
local assert = use "assert"
local tostring = use "tostring"
--// lua lib methods //--
local os_date = use "os".date
--// core scripts //--
local out
local util = use "util"
local const = use "const"
local types = use "types"
--// core methods //--
local out_error
local util_savetable = util.savetable
local util_loadtable = util.loadtable
local util_savearray = util.savearray
local util_maketable = util.maketable
local types_utf8 = types.utf8
local types_table = types.get "table"
local types_number = types.get "number"
local types_boolean = types.get "boolean"
local types_adcstr
local CONFIG_PATH = const.CONFIG_PATH
--// functions //--
local set
local get
local init
local checkcfg
local reload
local loadusers
local saveusers
local loadlanguage
local registerevent
local checklanguage
local loadcfgprofile
local checkusers
--// tables //--
local _event
local _settings
local _defaultsettings
--// simple data types //--
local _
local _cfgfile
--local _cfgfile_basic
--local _cfgfile_expert
local _cfgbackup
--local _cfgbackup_basic
--local _cfgbackup_expert
----------------------------------// DEFINITION //--
_settings = { }
_event = { reload = { } }
_cfgfile = CONFIG_PATH .. "cfg.tbl"
--_cfgfile_basic = CONFIG_PATH .. "cfg_basic.tbl"
--_cfgfile_expert = CONFIG_PATH .. "cfg_expert.tbl"
_cfgbackup = CONFIG_PATH .. "cfg.tbl.backup"
--_cfgbackup_basic = CONFIG_PATH .. "cfg_basic.tbl.backup"
--_cfgbackup_expert = CONFIG_PATH .. "cfg_expert.tbl.backup"
_defaultsettings = {
---------------------------------------------------------------------------------------------------------------------------------
--// Basic Settings
hub_name = { "Luadch Hub",
function( value )
return types_utf8( value, nil, true )
end
},
hub_description = { "your hub description",
function( value )
return types_utf8( value, nil, true )
end
},
hub_bot = { "[BOT]HubSecurity",
function( value )
if not types_adcstr( value, nil, true ) or #value == 0 then
return false
end
return true
end
},
hub_bot_desc = { "[ BOT ] hub security",
function( value )
return types_utf8( value, nil, true )
end
},
hub_hostaddress = { "your.host.addy.org",
function( value )
return types_utf8( value, nil, true )
end
},
tcp_ports = { { 5000 },
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not types_number( k, nil, true ) then
return false
end
end
end
return true
end
},
ssl_ports = { { 5001 },
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not types_number( k, nil, true ) then
return false
end
end
end
return true
end
},
use_ssl = { false,
function( value )
return types_boolean( value, nil, true )
end
},
use_keyprint = { false,
function( value )
return types_boolean( value, nil, true )
end
},
keyprint_type = { "/?kp=SHA256/",
function( value )
return types_utf8( value, nil, true )
end
},
keyprint_hash = { "<your_kp>",
function( value )
return types_utf8( value, nil, true )
end
},
hub_listen = { { "*" },
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not types_utf8( k, nil, true ) then
return false
end
end
end
return true
end
},
hub_website = { "http://yourwebsite.org",
function( value )
return types_utf8( value, nil, true )
end
},
hub_network = { "your hubnetwork name",
function( value )
return types_utf8( value, nil, true )
end
},
hub_owner = { "you",
function( value )
return types_utf8( value, nil, true )
end
},
reg_only = { false,
function( value )
return types_boolean( value, nil, true )
end
},
nick_change = { false,
function( value )
return types_boolean( value, nil, true )
end
},
max_users = { 100,
function( value )
return types_number( value, nil, true )
end
},
user_path = { CONFIG_PATH,
function( value )
return types_utf8( value, nil, true )
end
},
reg_level = { 20,
function( value )
return types_number( value, nil, true )
end
},
key_level = { 50,
function( value )
return types_number( value, nil, true )
end
},
bot_level = { 55,
function( value )
return types_number( value, nil, true )
end
},
debug = { true,
function( value )
return types_boolean( value, nil, true )
end
},
log_errors = { true,
function( value )
return types_boolean( value, nil, true )
end
},
log_events = { false,
function( value )
return types_boolean( value, nil, true )
end
},
log_scripts = { false,
function( value )
return types_boolean( value, nil, true )
end
},
log_path = { "././log/",
function( value )
return types_utf8( value, nil, true )
end
},
language = { "en",
function( value )
return types_utf8( value, nil, true )
end
},
core_lang_path = { "lang/",
function( value )
return types_utf8( value, nil, true )
end
},
scripts_lang_path = { "././scripts/lang/",
function( value )
return types_utf8( value, nil, true )
end
},
--[[
hub_pass = { "jsjfjs87374737472374jdjdfj384",
function( value )
return types_boolean( value, nil, true ) or types_adcstr( value, nil, true )
end
},
]]
max_bad_password = { 5,
function( value )
return types_number( value, nil, true )
end
},
bad_pass_timeout = { 300,
function( value )
return types_number( value, nil, true )
end
},
min_password_length = { 10,
function( value )
return types_number( value, nil, true )
end
},
max_password_length = { 30,
function( value )
return types_number( value, nil, true )
end
},
min_nickname_length = { 3,
function( value )
return types_number( value, nil, true )
end
},
max_nickname_length = { 30,
function( value )
return types_number( value, nil, true )
end
},
no_cid_taken = { true,
function( value )
return types_boolean( value, nil, true )
end
},
ranks = { {
"Bot",
"Reg",
"Op",
"Admin",
"Owner",
},
function( value )
if not types_table( value ) then
return false
else
for i, k in ipairs( value ) do
if not types_utf8( k, nil, true ) then
return false
end
end
end
return true
end
},
bot_rank = { 1,
function( value )
return types_number( value, nil, true )
end
},
reg_rank = { 2,
function( value )
return types_number( value, nil, true )
end
},
op_rank = { 4,
function( value )
return types_number( value, nil, true )
end
},
admin_rank = { 8,
function( value )
return types_number( value, nil, true )
end
},
owner_rank = { 16,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// Your hub levels with level names (array of strings)
levels = { {
[ 0 ] = "UNREG",
[ 10 ] = "GUEST",
[ 20 ] = "REG",
[ 30 ] = "VIP",
[ 40 ] = "SVIP",
[ 50 ] = "SERVER",
[ 55 ] = "SBOT",
[ 60 ] = "OPERATOR",
[ 70 ] = "SUPERVISOR",
[ 80 ] = "ADMIN",
[ 100 ] = "HUBOWNER",
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_utf8( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// bot_regchat.lua settings
bot_regchat_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
bot_regchat_nick = { "[CHAT]RegChat",
function( value )
return types_utf8( value, nil, true )
end
},
bot_regchat_desc = { "[ CHAT ] chatroom for reg users",
function( value )
return types_utf8( value, nil, true )
end
},
bot_regchat_history = { true,
function( value )
return types_boolean( value, nil, true )
end
},
bot_regchat_max_entrys = { 300,
function( value )
return types_number( value, nil, true )
end
},
bot_regchat_oplevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
bot_regchat_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = true,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// bot_opchat.lua settings
bot_opchat_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
bot_opchat_nick = { "[CHAT]OpChat",
function( value )
return types_utf8( value, nil, true )
end
},
bot_opchat_desc = { "[ CHAT ] chatroom for operators",
function( value )
return types_utf8( value, nil, true )
end
},
bot_opchat_history = { true,
function( value )
return types_boolean( value, nil, true )
end
},
bot_opchat_max_entrys = { 300,
function( value )
return types_number( value, nil, true )
end
},
bot_opchat_oplevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
bot_opchat_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// bot_pm2ops.lua settings
bot_pm2ops_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
bot_pm2ops_nick = { "[CHAT]PmToOps",
function( value )
return types_utf8( value, nil, true )
end
},
bot_pm2ops_desc = { "[ CHAT ] send msg to all ops",
function( value )
return types_utf8( value, nil, true )
end
},
bot_pm2ops_permission = { {
[ 0 ] = false,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_accinfo.lua settings
cmd_accinfo_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 50,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_accinfo_advanced_rc = { false,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_ascii.lua settings
cmd_ascii_minlevel = { 20,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_slots.lua settings
cmd_slots_minlevel = { 0,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_ban.lua settings
cmd_ban_default_time = { 20,
function( value )
return types_number( value, nil, true )
end
},
cmd_ban_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_ban_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_ban_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_ban_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 50,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_ban_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_delreg.lua settings
cmd_delreg_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_delreg_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_delreg_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_delreg_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
cmd_delreg_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 0,
[ 70 ] = 0,
[ 80 ] = 0,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_disconnect.lua settings
cmd_disconnect_minlevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
cmd_disconnect_sendmainmsg = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_disconnect_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_disconnect_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_disconnect_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_disconnect_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_errors.lua settings
cmd_errors_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_mass.lua settings
cmd_mass_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = true,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_mass_oplevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_reg.lua settings
cmd_reg_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
cmd_reg_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_reg_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_reg_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_reg_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 20,
[ 70 ] = 30,
[ 80 ] = 60,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_reload.lua settings
cmd_reload_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_restart.lua settings
cmd_restart_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = false,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_restart_toggle_countdown = { true,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_rules.lua settings
cmd_rules_minlevel = { 0,
function( value )
return types_number( value, nil, true )
end
},
cmd_rules_destination_main = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_rules_destination_pm = { false,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_setpass.lua settings
cmd_setpass_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 0,
[ 70 ] = 0,
[ 80 ] = 0,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_setpass_advanced_rc = { false,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_nickchange.lua settings
cmd_nickchange_minlevel = { 20,
function( value )
return types_number( value, nil, true )
end
},
cmd_nickchange_oplevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
cmd_nickchange_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_nickchange_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_nickchange_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_nickchange_advanced_rc = { false,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_shutdown.lua settings
cmd_shutdown_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = false,
[ 80 ] = false,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_shutdown_toggle_countdown = { true,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_talk.lua settings
cmd_talk_minlevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_pm2offliners.lua settings
cmd_pm2offliners_minlevel = { 30,
function( value )
return types_number( value, nil, true )
end
},
cmd_pm2offliners_oplevel = { 100,
function( value )
return types_number( value, nil, true )
end
},
cmd_pm2offliners_delay = { 7,
function( value )
return types_number( value, nil, true )
end
},
cmd_pm2offliners_advanced_rc = { false,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_unban.lua settings
cmd_unban_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 60,
[ 70 ] = 70,
[ 80 ] = 80,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_upgrade.lua settings
cmd_upgrade_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_upgrade_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_upgrade_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_upgrade_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
cmd_upgrade_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 0,
[ 70 ] = 0,
[ 80 ] = 0,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_upgrade_advanced_rc = { false,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_userinfo.lua settings
cmd_userinfo_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 50,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_userlist.lua settings
cmd_userlist_minlevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_usersearch.lua settings
cmd_usersearch_minlevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
cmd_usersearch_max_limit = { 20,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_hubinfo.lua settings
cmd_hubinfo_minlevel = { 10,
function( value )
return types_number( value, nil, true )
end
},
cmd_hubinfo_onlogin = { true,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_uptime.lua settings
cmd_uptime_minlevel = { 0,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_banner.lua settings
etc_banner_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_banner_time = { 1,
function( value )
return types_number( value, nil, true )
end
},
etc_banner_destination_main = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_banner_destination_pm = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_banner_permission = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_chatlog.lua settings
etc_chatlog_min_level_adv = { 100,
function( value )
return types_number( value, nil, true )
end
},
etc_chatlog_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_chatlog_max_lines = { 200,
function( value )
return types_number( value, nil, true )
end
},
etc_chatlog_default_lines = { 5,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_blacklist.lua settings
etc_blacklist_oplevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
etc_blacklist_masterlevel = { 100,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_cmdlog.lua settings
etc_cmdlog_minlevel = { 100,
function( value )
return types_number( value, nil, true )
end
},
etc_cmdlog_command_tbl = { {
[ "reg" ] = true,
[ "delreg" ] = true,
[ "disconnect" ] = true,
[ "ban" ] = true,
[ "unban" ] = true,
[ "upgrade" ] = true,
[ "accinfo" ] = true,
[ "nickchange" ] = true,
[ "reload" ] = true,
[ "restart" ] = true,
[ "shutdown" ] = true,
[ "trafficmanager" ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_utf8( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_log_cleaner.lua settings
etc_log_cleaner_minlevel = { 100,
function( value )
return types_number( value, nil, true )
end
},
etc_log_cleaner_activate_error = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_log_cleaner_activate_cmd = { true,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_motd.lua settings
etc_motd_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_motd_permission = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_motd_destination_main = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_motd_destination_pm = { false,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_offlineusers.lua settings
etc_offlineusers_min_level_owner = { 100,
function( value )
return types_number( value, nil, true )
end
},
etc_offlineusers_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = false,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_offlineusers_max_offline_days_auto = { {
[ 0 ] = 7,
[ 10 ] = 90,
[ 20 ] = 90,
[ 30 ] = 90,
[ 40 ] = 180,
[ 50 ] = 180,
[ 55 ] = 180,
[ 60 ] = 360,
[ 70 ] = 360,
[ 80 ] = 999,
[ 100 ] = 999,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_offlineusers_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_offlineusers_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_offlineusers_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_offlineusers_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_usercommands.lua settings
etc_usercommands_toplevelmenu = { "Luadch Commands",
function( value )
return types_utf8( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_userlogininfo.lua settings
etc_userlogininfo_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_userlogininfo_permission = { {
[ 0 ] = false,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_userlogininfo_show_hubversion = { true,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_nick_prefix.lua settings
usr_nick_prefix_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
usr_nick_prefix_prefix_table = { {
[ 0 ] = "[UNREG]",
[ 10 ] = "[GUEST]",
[ 20 ] = "[REG]",
[ 30 ] = "[VIP]",
[ 40 ] = "[SVIP]",
[ 50 ] = "[SERVER]",
[ 55 ] = "[SBOT]",
[ 60 ] = "[OPERATOR]",
[ 70 ] = "[SUPERVISOR]",
[ 80 ] = "[ADMIN]",
[ 100 ] = "[HUBOWNER]",
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_utf8( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
usr_nick_prefix_permission = { {
[ 0 ] = false,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = true,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_desc_prefix.lua settings
usr_desc_prefix_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
usr_desc_prefix_prefix_table = { {
[ 0 ] = "[ UNREG ] ",
[ 10 ] = "[ GUEST ] ",
[ 20 ] = "[ REG ] ",
[ 30 ] = "[ VIP ] ",
[ 40 ] = "[ SVIP ] ",
[ 50 ] = "[ SERVER ] ",
[ 55 ] = "[ SBOT ] ",
[ 60 ] = "[ OPERATOR ] ",
[ 70 ] = "[ SUPERVISOR ] ",
[ 80 ] = "[ ADMIN ] ",
[ 100 ] = "[ HUBOWNER ] ",
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_utf8( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
usr_desc_prefix_permission = { {
[ 0 ] = false,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = true,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_slots.lua settings
min_slots = { {
[ 0 ] = 2,
[ 10 ] = 2,
[ 20 ] = 2,
[ 30 ] = 2,
[ 40 ] = 2,
[ 50 ] = 2,
[ 55 ] = 0,
[ 60 ] = 0,
[ 70 ] = 0,
[ 80 ] = 0,
[ 100 ] = 0,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
max_slots = { {
[ 0 ] = 20,
[ 10 ] = 20,
[ 20 ] = 20,
[ 30 ] = 20,
[ 40 ] = 20,
[ 50 ] = 20,
[ 55 ] = 20,
[ 60 ] = 20,
[ 70 ] = 20,
[ 80 ] = 20,
[ 100 ] = 20,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_share.lua settings
min_share = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 0,
[ 70 ] = 0,
[ 80 ] = 0,
[ 100 ] = 0,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
max_share = { {
[ 0 ] = 200,
[ 10 ] = 200,
[ 20 ] = 200,
[ 30 ] = 200,
[ 40 ] = 200,
[ 50 ] = 200,
[ 55 ] = 200,
[ 60 ] = 200,
[ 70 ] = 200,
[ 80 ] = 200,
[ 100 ] = 200,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_hubs.lua settings
max_hubs = { 20,
function( value )
return types_number( value, nil, true )
end
},
max_user_hubs = { 20,
function( value )
return types_number( value, nil, true )
end
},
max_reg_hubs = { 20,
function( value )
return types_number( value, nil, true )
end
},
max_op_hubs = { 20,
function( value )
return types_number( value, nil, true )
end
},
usr_hubs_godlevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
usr_hubs_block_time = { 15,
function( value )
return types_number( value, nil, true )
end
},
usr_hubs_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
usr_hubs_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
usr_hubs_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
usr_hubs_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_topic.lua settings
cmd_topic_minlevel = { 100,
function( value )
return types_number( value, nil, true )
end
},
cmd_topic_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_topic_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_topic_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_topic_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_trafficmanager.lua settings
etc_trafficmanager_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 40,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_trafficmanager_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
etc_trafficmanager_blocklevel_tbl = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = false,
[ 80 ] = false,
[ 100 ] = false,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_trafficmanager_sharecheck = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_check_minshare = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_oplevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
etc_trafficmanager_login_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_report_main = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_report_pm = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_send_loop = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_trafficmanager_loop_time = { 6,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_msgmanager.lua settings
etc_msgmanager_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_msgmanager_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 40,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_msgmanager_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_msgmanager_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_msgmanager_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_msgmanager_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
etc_msgmanager_permission_pm = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = true,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_msgmanager_permission_main = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = true,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_hide_share.lua settings
usr_hide_share_activate = { false,
function( value )
return types_boolean( value, nil, true )
end
},
usr_hide_share_restrictions = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = false,
[ 80 ] = false,
[ 100 ] = false,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
usr_hide_share_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 40,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_gag.lua settings
cmd_gag_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_gag_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_gag_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_gag_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
cmd_gag_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 50,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_gag_user_notifiy = { true,
function( value )
return types_boolean( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_records.lua settings
etc_records_min_level = { 20,
function( value )
return types_number( value, nil, true )
end
},
etc_records_whereto_main = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_records_whereto_pm = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_records_reportlvl = { 20,
function( value )
return types_number( value, nil, true )
end
},
etc_records_sendMain = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_records_sendPM = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_records_delay = { 300,
function( value )
return types_number( value, nil, true )
end
},
etc_records_min_level_reset = { 100,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// bot_session_chat.lua settings
bot_session_chat_minlevel = { 20,
function( value )
return types_number( value, nil, true )
end
},
bot_session_chat_masterlevel = { 100,
function( value )
return types_number( value, nil, true )
end
},
bot_session_chat_chatprefix = { "[SESSION-CHAT]",
function( value )
return types_utf8( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_hubstats.lua settings
cmd_hubstats_oplevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_dhtblocker.lua settings
etc_dhtblocker_activate = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_dhtblocker_block_level = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = true,
[ 30 ] = true,
[ 40 ] = true,
[ 50 ] = true,
[ 55 ] = true,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
etc_dhtblocker_block_time = { 15,
function( value )
return types_number( value, nil, true )
end
},
etc_dhtblocker_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_dhtblocker_report_toopchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
etc_dhtblocker_report_tohubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
etc_dhtblocker_report_level = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// etc_ccpmblocker.lua settings
etc_ccpmblocker_block_level = { {
[ 0 ] = true,
[ 10 ] = true,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = false,
[ 80 ] = false,
[ 100 ] = false,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_redirect.lua settings
cmd_redirect_activate = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_redirect_permission = { {
[ 0 ] = 0,
[ 10 ] = 0,
[ 20 ] = 0,
[ 30 ] = 0,
[ 40 ] = 0,
[ 50 ] = 0,
[ 55 ] = 0,
[ 60 ] = 50,
[ 70 ] = 60,
[ 80 ] = 70,
[ 100 ] = 100,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_number( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_redirect_level = { {
[ 0 ] = true,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = false,
[ 70 ] = false,
[ 80 ] = false,
[ 100 ] = false,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
cmd_redirect_url = { "adc://addy:port",
function( value )
return types_utf8( value, nil, true )
end
},
cmd_redirect_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_redirect_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_redirect_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
cmd_redirect_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_sslinfo.lua settings
cmd_sslinfo_minlevel = { 10,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// cmd_myinf.lua settings
cmd_myinf_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// hub_runtime.lua settings
hub_runtime_minlevel = { 100,
function( value )
return types_number( value, nil, true )
end
},
hub_runtime_report = { true,
function( value )
return types_boolean( value, nil, true )
end
},
hub_runtime_report_opchat = { true,
function( value )
return types_boolean( value, nil, true )
end
},
hub_runtime_report_hubbot = { false,
function( value )
return types_boolean( value, nil, true )
end
},
hub_runtime_llevel = { 60,
function( value )
return types_number( value, nil, true )
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// usr_uptime.lua settings
usr_uptime_minlevel = { 10,
function( value )
return types_number( value, nil, true )
end
},
usr_uptime_permission = { {
[ 0 ] = false,
[ 10 ] = false,
[ 20 ] = false,
[ 30 ] = false,
[ 40 ] = false,
[ 50 ] = false,
[ 55 ] = false,
[ 60 ] = true,
[ 70 ] = true,
[ 80 ] = true,
[ 100 ] = true,
},
function( value )
if not types_table( value ) then
return false
else
for i, k in pairs( value ) do
if not ( types_boolean( k, nil, true ) and types_number( i, nil, true ) ) then
return false
end
end
end
return true
end
},
---------------------------------------------------------------------------------------------------------------------------------
--// user scripts (string array); scripts will be executed in this order!
scripts = { {
"hub_cmd_manager.lua", -- must be the first script in the table!
"etc_cmdlog.lua", -- must be the second script in the table!
"bot_opchat.lua", -- must be above all other scripts who wants to use the opchat import
"etc_report.lua", -- must be above all other scripts who wants to use the report import / needs opchat
"cmd_ban.lua", -- must be above all other scripts who wants to use the ban import / needs report
"usr_uptime.lua", -- must be above all other scripts who wants to use the usersuptime import
"hub_inf_manager.lua",
"hub_runtime.lua",
"bot_regchat.lua",
"bot_session_chat.lua",
"bot_pm2ops.lua",
"usr_slots.lua",
"usr_share.lua",
"usr_hubs.lua",
"usr_nick_prefix.lua",
"usr_desc_prefix.lua",
"usr_hide_share.lua",
"cmd_help.lua",
"cmd_redirect.lua",
"cmd_uptime.lua",
"cmd_hubinfo.lua",
"cmd_hubstats.lua",
"cmd_myip.lua",
"cmd_myinf.lua",
"cmd_rules.lua",
"cmd_userinfo.lua",
"cmd_usersearch.lua",
"cmd_slots.lua",
"cmd_accinfo.lua",
"cmd_setpass.lua",
"cmd_nickchange.lua",
"cmd_mass.lua",
"cmd_talk.lua",
"cmd_pm2offliners.lua",
"cmd_topic.lua",
"cmd_userlist.lua",
"cmd_disconnect.lua",
"cmd_reg.lua",
"cmd_upgrade.lua",
"cmd_delreg.lua",
"cmd_errors.lua",
"cmd_reload.lua",
"cmd_restart.lua",
"cmd_shutdown.lua",
"cmd_ascii.lua",
"cmd_gag.lua",
"cmd_sslinfo.lua",
"etc_hubcommands.lua",
"etc_usercommands.lua",
"etc_blacklist.lua",
"etc_log_cleaner.lua",
"etc_motd.lua",
"etc_userlogininfo.lua",
"etc_banner.lua",
"etc_offlineusers.lua",
"etc_chatlog.lua",
"etc_msgmanager.lua",
"etc_trafficmanager.lua",
"etc_records.lua",
"etc_dhtblocker.lua",
"etc_ccpmblocker.lua",
"hub_bot_cleaner.lua",
"etc_unknown_command.lua",
},
function( value )
if not types_table( value ) then
return false
else
for i, k in ipairs( value ) do
if not types_utf8( k, nil, true ) then
return false
end
end
end
return true
end
},
script_path = { "././scripts/",
function( value )
return types_utf8( value, nil, true )
end
},
ssl_params = { {
mode = "server", -- do not touch this
key = "certs/serverkey.pem", -- your ssl key
certificate = "certs/servercert.pem", -- your cert
cafile = "certs/cacert.pem", -- your ca file
options = { "no_sslv2", "no_sslv3" }, -- do not touch this
curve = "prime256v1", -- do not touch this
protocol = "tlsv1_2",
ciphers = "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256", -- TLSv1.2 with AES128 + AES256
}, function( ) return true end },
scripts_cfg_profile = { "default",
function( value )
return types_utf8( value, nil, true )
end
},
scripts_cfg_path = { "././scripts/cfg/",
function( value )
return types_utf8( value, nil, true )
end
},
no_global_scripting = { true,
function( value )
return types_boolean( value, nil, true )
end
},
kill_wrong_ips = { false,
function( value )
return types_boolean( value, nil, true )
end
},
--// PING //--
use_ping = { true,
function( value )
return types_boolean( value, nil, true )
end
},
disable_email = { false,
function( value )
return types_boolean( value, nil, true )
end
},
forbid_plaintext = { false,
function( value )
return types_boolean( value, nil, true )
end
},
hadm_password = { "",
function( value )
return types_utf8( value, nil, true )
end
},
}
checkcfg = function( )
for key, value in pairs( _settings ) do
local dst = _defaultsettings[ key ]
if not ( dst and dst[ 2 ]( value ) ) then
out_error( "cfg.lua: function 'checkcfg': corrupt cfg.tbl: invalid key/value: ", key, "/", value, "; using default cfg" )
_settings = { }
break
end
end
end
checklanguage = function( lang )
--[[for i, k in pairs( lang ) do
if not ( types_utf8( k, nil, true ) and types_utf8( i, nil, true ) ) then
out_error( "cfg.lua: function 'checklanguage': error while loading hub language: invalid key/value: ", i, "/", k, "; using default" )
return { }
end
end]]
return lang
end
checkusers = function()
local users, err = util_loadtable( get "user_path" .. "user.tbl" )
if users then
util_maketable( nil, get "user_path" .. "user.tbl.bak" )
local _, err = util_savearray( users, get( "user_path" ) .. "user.tbl.bak" )
_ = err and out_error( "cfg.lua: function 'checkusers': error while saving user db backup: ", err )
else
local users, err = util_loadtable( get "user_path" .. "user.tbl.bak" )
if users then
util_maketable( nil, get "user_path" .. "user.tbl" )
local _, err = util_savearray( users, get( "user_path" ) .. "user.tbl" )
_ = err and out_error( "cfg.lua: function 'checkusers': error while restoring corrupt user db from backup: ", err )
end
end
end
--[[
set = function( target, newvalue )
local dst = _defaultsettings[ target ]
if dst and dst[ 2 ]( newvalue ) then
_settings[ target ] = newvalue
local _, err = util_savetable( _settings, "settings", _cfgbackup .. "." .. os_date( "[%d.%m.%y.%H.%M.%S]" ) )
_ = err and out_error( "cfg.lua: function 'set': error while backup hub settings: ", err )
local _, err = util_savetable( _settings, "settings", _cfgfile )
_ = err and out_error( "cfg.lua: function 'set': error while saving hub settings: ", err )
return err
else
out_error( "cfg.lua: function 'set': invalid access to settings: invalid target/newvalue: ", target, "/", newvalue, "; using old value" )
return "invalid target or newvalue"
end
end
]]
get = function( target )
if _settings[ target ] == nil then
return _defaultsettings[ target ][ 1 ]
end
return _settings[ target ]
end
loadusers = function( )
local users, err = util_loadtable( get "user_path" .. "user.tbl" )
_ = err and out_error( "cfg.lua: function 'loadusers': error while loading users: ", err )
return ( users or { } ), err
end
saveusers = function( regusers )
--local _, err = util_savearray( regusers, get( "user_path" ) .. "user.tbl.BACKUP." .. os_date( "[%d.%m.%y.%H.%M.%S]" ) )
--local _, err
--_ = err and out_error( "cfg.lua: error while backup user db: ", err )
local _, err = util_savearray( regusers, get( "user_path" ) .. "user.tbl" )
_ = err and out_error( "cfg.lua: function 'saveusers': error while saving user db: ", err )
if err then
return false, err
else
return true
end
end
--[[
loadlanguage = function( language, name )
language = tostring( language or get "language" ) -- default language
local path
if not name then
path = get "core_lang_path" .. language .. ".tbl"
else
path = get "scripts_lang_path" .. tostring( name ) .. ".lang." .. language
end
local ret, err = util_loadtable( path )
_ = err and out_error( "cfg.lua: function 'loadlanguage': error while loading language: ", err )
return checklanguage( ret or { } ), err
end
]]
loadlanguage = function( language, name )
language = tostring( language or get "language" ) -- default language
local path
if not name then
path = get "core_lang_path" .. language .. ".tbl"
else
path = get "scripts_lang_path" .. tostring( name ) .. ".lang." .. language
end
local ret, err = util_loadtable( path )
if name then
_ = err and out_error( "cfg.lua: function 'loadlanguage': error while loading language (" .. tostring( name ) .. "): ", err )
else
_ = err and out_error( "cfg.lua: function 'loadlanguage': error while loading language: ", err )
end
return checklanguage( ret or { } ), err
end
loadcfgprofile = function( profile, name )
profile = tostring( profile or get "scripts_cfg_profile" ) -- default profile
ret, err = util_loadtable( get "scripts_cfg_path" .. tostring( name ) .. ".cfg." .. profile )
_ = err and out_error( "cfg.lua: function 'loadcfgprofile': error while loading cfg profile: ", err )
return ret, err
end
registerevent = function( what, listener )
assert( type( listener ) == "function" )
_event[ what ] = _event[ what ] or { }
local tbl = _event[ what ]
_event[ what ][ #tbl + 1 ] = listener
end
reload = function( )
local err
_settings, err = util_loadtable( _cfgfile )
_settings = _settings or { }
_ = err and out_error( "cfg.lua: function 'reload': error while reloading hub settings: ", err, "; using default cfg" )
checkcfg( )
for i, func in ipairs( _event.reload ) do
func( )
end
return _settings, err
end
init = function( )
types_adcstr = types.get "adcstr"
out = use "out"
out_error = out.error
local err
_settings, err = util_loadtable( _cfgfile )
_settings = _settings or { }
_ = err and out_error( "cfg.lua: function 'init': error while loading hub settings: ", err, "; using default cfg" )
checkcfg( )
end
----------------------------------// BEGIN //--
----------------------------------// PUBLIC INTERFACE //--
return {
init = init,
checkusers = checkusers,
--set = set,
get = get,
reload = reload,
loadusers = loadusers,
saveusers = saveusers,
loadlanguage = loadlanguage,
registerevent = registerevent,
loadcfgprofile = loadcfgprofile,
}
| gpl-3.0 |
Lsty/ygopro-scripts | c63176202.lua | 5 | 3085 | --大将軍 紫炎
function c63176202.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c63176202.spcon)
c:RegisterEffect(e1)
--Destroy replace
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DESTROY_REPLACE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c63176202.desreptg)
e2:SetOperation(c63176202.desrepop)
c:RegisterEffect(e2)
--activate limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e3:SetCode(EVENT_CHAINING)
e3:SetRange(LOCATION_MZONE)
e3:SetOperation(c63176202.aclimit1)
c:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e4:SetCode(EVENT_CHAIN_NEGATED)
e4:SetRange(LOCATION_MZONE)
e4:SetOperation(c63176202.aclimit2)
c:RegisterEffect(e4)
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD)
e5:SetCode(EFFECT_CANNOT_ACTIVATE)
e5:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e5:SetRange(LOCATION_MZONE)
e5:SetTargetRange(0,1)
e5:SetCondition(c63176202.econ)
e5:SetValue(c63176202.elimit)
c:RegisterEffect(e5)
end
function c63176202.spfilter(c)
return c:IsFaceup() and c:IsSetCard(0x3d)
end
function c63176202.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c63176202.spfilter,tp,LOCATION_MZONE,0,2,nil)
end
function c63176202.repfilter(c)
return c:IsFaceup() and c:IsSetCard(0x3d) and not c:IsStatus(STATUS_DESTROY_CONFIRMED+STATUS_BATTLE_DESTROYED)
end
function c63176202.desreptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return not c:IsReason(REASON_REPLACE) and c:IsOnField() and c:IsFaceup()
and Duel.IsExistingMatchingCard(c63176202.repfilter,tp,LOCATION_MZONE,0,1,c) end
if Duel.SelectYesNo(tp,aux.Stringid(63176202,0)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESREPLACE)
local g=Duel.SelectMatchingCard(tp,c63176202.repfilter,tp,LOCATION_MZONE,0,1,1,c)
e:SetLabelObject(g:GetFirst())
Duel.HintSelection(g)
g:GetFirst():SetStatus(STATUS_DESTROY_CONFIRMED,true)
return true
else return false end
end
function c63176202.desrepop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
tc:SetStatus(STATUS_DESTROY_CONFIRMED,false)
Duel.Destroy(tc,REASON_EFFECT+REASON_REPLACE)
end
function c63176202.aclimit1(e,tp,eg,ep,ev,re,r,rp)
if ep==tp or not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return end
e:GetHandler():RegisterFlagEffect(63176202,RESET_EVENT+0x3ff0000+RESET_PHASE+PHASE_END,0,1)
end
function c63176202.aclimit2(e,tp,eg,ep,ev,re,r,rp)
if ep==tp or not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return end
e:GetHandler():ResetFlagEffect(63176202)
end
function c63176202.econ(e)
return e:GetHandler():GetFlagEffect(63176202)~=0
end
function c63176202.elimit(e,te,tp)
return te:IsHasType(EFFECT_TYPE_ACTIVATE)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c49204190.lua | 5 | 1749 | --奇策
function c49204190.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c49204190.condition)
e1:SetCost(c49204190.cost)
e1:SetTarget(c49204190.target)
e1:SetOperation(c49204190.activate)
c:RegisterEffect(e1)
end
function c49204190.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c49204190.cfilter(c)
return c:GetAttack()>0 and c:IsDiscardable()
end
function c49204190.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c49204190.cfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DISCARD)
local g=Duel.SelectMatchingCard(tp,c49204190.cfilter,tp,LOCATION_HAND,0,1,1,nil)
e:SetLabel(g:GetFirst():GetAttack())
Duel.SendtoGrave(g,REASON_COST+REASON_DISCARD)
end
function c49204190.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c49204190.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-e:GetLabel())
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
cleytonk/globalfull | data/talkactions/scripts/add_skill.lua | 7 | 1741 | local function getSkillId(skillName)
if skillName == "club" then
return SKILL_CLUB
elseif skillName == "sword" then
return SKILL_SWORD
elseif skillName == "axe" then
return SKILL_AXE
elseif skillName:sub(1, 4) == "dist" then
return SKILL_DISTANCE
elseif skillName:sub(1, 6) == "shield" then
return SKILL_SHIELD
elseif skillName:sub(1, 4) == "fish" then
return SKILL_FISHING
else
return SKILL_FIST
end
end
local function getExpForLevel(level)
level = level - 1
return ((50 * level * level * level) - (150 * level * level) + (400 * level)) / 3
end
function onSay(cid, words, param)
local player = Player(cid)
if not player:getGroup():getAccess() then
return true
end
if player:getAccountType() < ACCOUNT_TYPE_GOD then
return false
end
local split = param:split(",")
if split[2] == nil then
player:sendCancelMessage("Insufficient parameters.")
return false
end
local target = Player(split[1])
if target == nil then
player:sendCancelMessage("A player with that name is not online.")
return false
end
-- Trim left
split[2] = split[2]:gsub("^%s*(.-)$", "%1")
local count = 1
if split[3] ~= nil then
count = tonumber(split[3])
end
local ch = split[2]:sub(1, 1)
for i = 1, count do
if ch == "l" or ch == "e" then
target:addExperience(getExpForLevel(target:getLevel() + 1) - target:getExperience(), false)
elseif ch == "m" then
target:addManaSpent(target:getVocation():getRequiredManaSpent(target:getBaseMagicLevel() + 1) - target:getManaSpent())
else
local skillId = getSkillId(split[2])
target:addSkillTries(skillId, target:getVocation():getRequiredSkillTries(skillId, target:getSkillLevel(skillId) + 1) - target:getSkillTries(skillId))
end
end
return false
end
| gpl-2.0 |
tofurama3000/The-Obscurity-Project | cocos2d/plugin/luabindings/auto/api/ProtocolUser.lua | 146 | 1133 |
--------------------------------
-- @module ProtocolUser
-- @extend PluginProtocol
-- @parent_module plugin
--------------------------------
-- brief config the application info<br>
-- param devInfo This parameter is the info of aplication,<br>
-- different plugin have different format<br>
-- warning Must invoke this interface before other interfaces.<br>
-- And invoked only once.
-- @function [parent=#ProtocolUser] configDeveloperInfo
-- @param self
-- @param #map_table devInfo
--------------------------------
--
-- @function [parent=#ProtocolUser] isLoggedIn
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- brief Get session ID<br>
-- return If user logined, return value is session ID;<br>
-- else return value is empty string.
-- @function [parent=#ProtocolUser] getSessionID
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- brief get Access Token
-- @function [parent=#ProtocolUser] getAccessToken
-- @param self
-- @return string#string ret (return value: string)
return nil
| mit |
MalRD/darkstar | scripts/zones/Windurst_Waters/npcs/Hariga-Origa.lua | 11 | 3372 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Hariga-Origa
-- Starts & Finishes Quest: Glyph Hanger
-- Involved in Mission 2-1
-- !pos -62 -6 105 238
-----------------------------------
local ID = require("scripts/zones/Windurst_Waters/IDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
smudgeStatus = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.A_SMUDGE_ON_ONE_S_RECORD);
if (smudgeStatus == QUEST_ACCEPTED and trade:hasItemQty(637,1) and trade:hasItemQty(4382,1)) then
player:startEvent(417,3000);
end
end;
function onTrigger(player,npc)
GlyphHanger = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.GLYPH_HANGER);
chasingStatus = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.CHASING_TALES);
smudgeStatus = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.A_SMUDGE_ON_ONE_S_RECORD);
Fame = player:getFameLevel(WINDURST);
if (smudgeStatus == QUEST_COMPLETED and player:needToZone() == true) then
player:startEvent(418);
elseif (smudgeStatus == QUEST_ACCEPTED) then
player:startEvent(414,0,637,4382);
elseif (smudgeStatus == QUEST_AVAILABLE and chasingStatus == QUEST_COMPLETED and Fame >= 4) then
player:startEvent(413,0,637,4382);
elseif (GlyphHanger == QUEST_COMPLETED and chasingStatus ~= QUEST_COMPLETED) then
player:startEvent(386);
elseif (GlyphHanger == QUEST_ACCEPTED) then
if (player:hasKeyItem(dsp.ki.NOTES_FROM_IPUPU)) then
player:startEvent(385);
else
player:startEvent(382);
end
elseif (GlyphHanger == QUEST_AVAILABLE) then
player:startEvent(381);
else
player:startEvent(372); -- The line will never be executed
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 381 and option == 0) then
player:addQuest(WINDURST,dsp.quest.id.windurst.GLYPH_HANGER);
player:addKeyItem(dsp.ki.NOTES_FROM_HARIGAORIGA);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.NOTES_FROM_HARIGAORIGA);
elseif (csid == 385) then
player:needToZone(true);
player:delKeyItem(dsp.ki.NOTES_FROM_IPUPU);
if (player:hasKeyItem(dsp.ki.MAP_OF_THE_HORUTOTO_RUINS) == false) then
player:addKeyItem(dsp.ki.MAP_OF_THE_HORUTOTO_RUINS);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MAP_OF_THE_HORUTOTO_RUINS);
end
player:addFame(WINDURST,120);
player:completeQuest(WINDURST,dsp.quest.id.windurst.GLYPH_HANGER);
elseif (csid == 413 and option == 0) then
player:addQuest(WINDURST,dsp.quest.id.windurst.A_SMUDGE_ON_ONE_S_RECORD);
elseif (csid == 417) then
player:needToZone(true);
player:addGil(GIL_RATE*3000);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*3000);
if (player:hasKeyItem(dsp.ki.MAP_OF_FEIYIN) == false) then
player:addKeyItem(dsp.ki.MAP_OF_FEIYIN);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MAP_OF_FEIYIN);
end
player:addFame(WINDURST,120);
player:completeQuest(WINDURST,dsp.quest.id.windurst.A_SMUDGE_ON_ONE_S_RECORD);
end
end; | gpl-3.0 |
cleytonk/globalfull | config.lua | 2 | 2416 | -- Combat settings
-- NOTE: valid values for worldType are: "pvp", "no-pvp" and "pvp-enforced"
worldType = "pvp"
hotkeyAimbotEnabled = "yes"
protectionLevel = 1
killsToRedSkull = 3
killsToBlackSkull = 6
pzLocked = 60000
removeAmmoWhenUsingDistanceWeapon = "yes"
removeChargesFromRunes = "yes"
timeToDecreaseFrags = 24 * 60 * 60 * 1000
whiteSkullTime = 15 * 60 * 1000
stairJumpExhaustion = 2000
experienceByKillingPlayers = "no"
expFromPlayersLevelRange = 75
noDamageToSameLookfeet = "no"
-- Connection Config
-- NOTE: maxPlayers set to 0 means no limit
ip = "127.0.0.1"
bindOnlyGlobalAddress = "no"
loginProtocolPort = 7171
gameProtocolPort = 7172
statusProtocolPort = 7171
maxPlayers = 0
motd = "Welcome to The Forgotten Server!"
onePlayerOnlinePerAccount = "yes"
allowClones = "no"
serverName = "Forgotten"
statusTimeout = 5000
replaceKickOnLogin = "yes"
maxPacketsPerSecond = 25
-- Deaths
-- NOTE: Leave deathLosePercent as -1 if you want to use the default
-- death penalty formula. For the old formula, set it to 10. For
-- no skill/experience loss, set it to 0.
deathLosePercent = -1
-- Houses
-- NOTE: set housePriceEachSQM to -1 to disable the ingame buy house functionality
housePriceEachSQM = 1000
houseRentPeriod = "never"
-- Item Usage
timeBetweenActions = 200
timeBetweenExActions = 1000
-- Map
-- NOTE: set mapName WITHOUT .otbm at the end
mapName = "forgotten"
mapAuthor = "Komic"
-- Market
marketOfferDuration = 30 * 24 * 60 * 60
premiumToCreateMarketOffer = "yes"
checkExpiredMarketOffersEachMinutes = 60
maxMarketOffersAtATimePerPlayer = 100
-- MySQL
mysqlHost = "127.0.0.1"
mysqlUser = "forgottenserver"
mysqlPass = ""
mysqlDatabase = "forgottenserver"
mysqlPort = 3306
mysqlSock = ""
passwordType = sha1
-- Misc.
allowChangeOutfit = "yes"
freePremium = "no"
kickIdlePlayerAfterMinutes = 15
maxMessageBuffer = 4
emoteSpells = "no"
-- Rates
-- NOTE: rateExp is not used if you have enabled stages in data/XML/stages.xml
rateExp = 5
rateSkill = 3
rateLoot = 2
rateMagic = 3
rateSpawn = 1
-- Monsters
deSpawnRange = 2
deSpawnRadius = 50
-- Stamina
staminaSystem = "yes"
-- Scripts
warnUnsafeScripts = "no"
convertUnsafeScripts = "no"
-- Startup
-- NOTE: defaultPriority only works on Windows and sets process priority.
defaultPriority = "high"
startupDatabaseOptimization = "no"
-- Status server information
ownerName = ""
ownerEmail = ""
url = "http://otland.net/"
location = "Sweden"
| gpl-2.0 |
maxrio/luci981213 | applications/luci-app-radicale/luasrc/controller/radicale.lua | 3 | 6688 | -- Copyright 2014 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed under the Apache License, Version 2.0
module("luci.controller.radicale", package.seeall)
local NX = require("nixio")
local NXFS = require("nixio.fs")
local DISP = require "luci.dispatcher"
local HTTP = require("luci.http")
local I18N = require("luci.i18n") -- not globally avalible here
local UTIL = require("luci.util")
local SYS = require("luci.sys")
function index()
entry( {"admin", "services", "radicale"}, alias("admin", "services", "radicale", "edit"), _("CalDAV/CardDAV"), 58)
entry( {"admin", "services", "radicale", "edit"}, cbi("radicale") ).leaf = true
entry( {"admin", "services", "radicale", "logview"}, call("_logread") ).leaf = true
entry( {"admin", "services", "radicale", "startstop"}, post("_startstop") ).leaf = true
entry( {"admin", "services", "radicale", "status"}, call("_status") ).leaf = true
end
-- called by XHR.get from detail_logview.htm
function _logread()
-- read application settings
local uci = UCI.cursor()
local logfile = uci:get("radicale", "radicale", "logfile") or "/var/log/radicale"
uci:unload("radicale")
local ldata=NXFS.readfile(logfile)
if not ldata or #ldata == 0 then
ldata="_nodata_"
end
HTTP.write(ldata)
end
-- called by XHR.get from detail_startstop.htm
function _startstop()
local pid = get_pid()
if pid > 0 then
SYS.call("/etc/init.d/radicale stop")
NX.nanosleep(1) -- sleep a second
if NX.kill(pid, 0) then -- still running
NX.kill(pid, 9) -- send SIGKILL
end
pid = 0
else
SYS.call("/etc/init.d/radicale start")
NX.nanosleep(1) -- sleep a second
pid = get_pid()
if pid > 0 and not NX.kill(pid, 0) then
pid = 0 -- process did not start
end
end
HTTP.write(tostring(pid)) -- HTTP needs string not number
end
-- called by XHR.poll from detail_startstop.htm
function _status()
local pid = get_pid()
HTTP.write(tostring(pid)) -- HTTP needs string not number
end
-- Application / Service specific information functions ########################
function luci_app_name()
return "luci-app-radicale"
end
function service_name()
return "radicale"
end
function service_required()
return "0.10-1"
end
function service_installed()
local v = ipkg_ver_installed("radicale-py2")
if not v or #v == 0 then v = ipkg_ver_installed("radicale-py3") end
if not v or #v == 0 then v = "0" end
return v
end
function service_ok()
return ipkg_ver_compare(service_installed(),">=",service_required())
end
function app_title_main()
return [[<a href="javascript:alert(']]
.. I18N.translate("Version Information")
.. [[\n\n]] .. luci_app_name()
.. [[\n\t]] .. I18N.translate("Version") .. [[:\t]]
.. (ipkg_ver_installed(luci_app_name()) == ""
and I18N.translate("NOT installed")
or ipkg_ver_installed(luci_app_name()) )
.. [[\n\n]] .. service_name() .. [[ ]] .. I18N.translate("required") .. [[:]]
.. [[\n\t]] .. I18N.translate("Version") .. [[:\t]]
.. service_required() .. [[ ]] .. I18N.translate("or higher")
.. [[\n\n]] .. service_name() .. [[ ]] .. I18N.translate("installed") .. [[:]]
.. [[\n\t]] .. I18N.translate("Version") .. [[:\t]]
.. (service_installed() == "0"
and I18N.translate("NOT installed")
or service_installed())
.. [[\n\n]]
.. [[')">]]
.. I18N.translate("Radicale CalDAV/CardDAV Server")
.. [[</a>]]
end
function app_title_back()
return [[<a href="]]
.. DISP.build_url("admin", "services", "radicale")
.. [[">]]
.. I18N.translate("Radicale CalDAV/CardDAV Server")
.. [[</a>]]
end
function app_description()
return I18N.translate("The Radicale Project is a complete CalDAV (calendar) and CardDAV (contact) server solution.") .. [[<br />]]
.. I18N.translate("Calendars and address books are available for both local and remote access, possibly limited through authentication policies.") .. [[<br />]]
.. I18N.translate("They can be viewed and edited by calendar and contact clients on mobile phones or computers.")
end
-- other multiused functions ###################################################
--return pid of running process
function get_pid()
return tonumber(SYS.exec([[ps | grep "[p]ython.*[r]adicale" 2>/dev/null | awk '{print $1}']])) or 0
end
-- compare versions using "<=" "<" ">" ">=" "=" "<<" ">>"
function ipkg_ver_compare(ver1, comp, ver2)
if not ver1 or not ver2
or not comp or not (#comp > 0) then return nil end
-- correct compare string
if comp == "<>" or comp == "><" or comp == "!=" or comp == "~=" then comp = "~="
elseif comp == "<=" or comp == "<" or comp == "=<" then comp = "<="
elseif comp == ">=" or comp == ">" or comp == "=>" then comp = ">="
elseif comp == "=" or comp == "==" then comp = "=="
elseif comp == "<<" then comp = "<"
elseif comp == ">>" then comp = ">"
else return nil end
local av1 = UTIL.split(ver1, "[%.%-]", nil, true)
local av2 = UTIL.split(ver2, "[%.%-]", nil, true)
for i = 1, math.max(table.getn(av1),table.getn(av2)), 1 do
local s1 = av1[i] or ""
local s2 = av2[i] or ""
-- first "not equal" found return true
if comp == "~=" and (s1 ~= s2) then return true end
-- first "lower" found return true
if (comp == "<" or comp == "<=") and (s1 < s2) then return true end
-- first "greater" found return true
if (comp == ">" or comp == ">=") and (s1 > s2) then return true end
-- not equal then return false
if (s1 ~= s2) then return false end
end
-- all equal and not compare greater or lower then true
return not (comp == "<" or comp == ">")
end
-- read version information for given package if installed
function ipkg_ver_installed(pkg)
local version = ""
local control = io.open("/usr/lib/opkg/info/%s.control" % pkg, "r")
if control then
local ln
repeat
ln = control:read("*l")
if ln and ln:match("^Version: ") then
version = ln:gsub("^Version: ", "")
break
end
until not ln
control:close()
end
return version
end
-- replacement of build-in Flag.parse of cbi.lua
-- modified to mark section as changed if value changes
-- current parse did not do this, but it is done AbstaractValue.parse()
function flag_parse(self, section)
local fexists = self.map:formvalue(
luci.cbi.FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option)
if fexists then
local fvalue = self:formvalue(section) and self.enabled or self.disabled
local cvalue = self:cfgvalue(section)
if fvalue ~= self.default or (not self.optional and not self.rmempty) then
self:write(section, fvalue)
else
self:remove(section)
end
if (fvalue ~= cvalue) then self.section.changed = true end
else
self:remove(section)
self.section.changed = true
end
end
| apache-2.0 |
Lsty/ygopro-scripts | c63211608.lua | 3 | 1752 | --A・ジェネクス・リバイバー
function c63211608.initial_effect(c)
--counter
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_CHAINING)
e1:SetRange(LOCATION_HAND)
e1:SetOperation(c63211608.chop1)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_CHAIN_NEGATED)
e2:SetRange(LOCATION_HAND)
e2:SetOperation(c63211608.chop2)
c:RegisterEffect(e2)
e1:SetLabelObject(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(63211608,0))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_CHAIN_END)
e3:SetRange(LOCATION_HAND)
e3:SetCondition(c63211608.sumcon)
e3:SetTarget(c63211608.sumtg)
e3:SetOperation(c63211608.sumop)
e3:SetLabelObject(e2)
c:RegisterEffect(e3)
end
function c63211608.chop1(e,tp,eg,ep,ev,re,r,rp)
e:GetLabelObject():SetLabel(0)
end
function c63211608.chop2(e,tp,eg,ep,ev,re,r,rp)
if rp==tp then return end
local de,dp=Duel.GetChainInfo(ev,CHAININFO_DISABLE_REASON,CHAININFO_DISABLE_PLAYER)
if dp==tp then
e:SetLabel(1)
end
end
function c63211608.sumcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetLabelObject():GetLabel()~=0
end
function c63211608.sumtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c63211608.sumop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
minimumcut/UnnamedEngine | UnnamedEngine/Vendor/bullet/test/InverseDynamics/premake4.lua | 4 | 4328 |
project "Test_InverseDynamicsKinematics"
kind "ConsoleApp"
-- defines { }
includedirs
{
".",
"../../src",
"../../examples/InverseDynamics",
"../../Extras/InverseDynamics",
"../gtest-1.7.0/include"
}
if os.is("Windows") then
--see http://stackoverflow.com/questions/12558327/google-test-in-visual-studio-2012
defines {"_VARIADIC_MAX=10"}
end
links {"BulletInverseDynamicsUtils", "BulletInverseDynamics","Bullet3Common","LinearMath", "gtest"}
files {
"test_invdyn_kinematics.cpp",
}
if os.is("Linux") then
links {"pthread"}
end
project "Test_InverseDynamicsJacobian"
kind "ConsoleApp"
-- defines { }
includedirs
{
".",
"../../src",
"../../examples/InverseDynamics",
"../../Extras/InverseDynamics",
"../gtest-1.7.0/include"
}
if os.is("Windows") then
--see http://stackoverflow.com/questions/12558327/google-test-in-visual-studio-2012
defines {"_VARIADIC_MAX=10"}
end
links {"BulletInverseDynamicsUtils", "BulletInverseDynamics","Bullet3Common","LinearMath", "gtest"}
files {
"test_invdyn_jacobian.cpp",
}
if os.is("Linux") then
links {"pthread"}
end
project "Test_InverseForwardDynamics"
kind "ConsoleApp"
-- defines { }
includedirs
{
".",
"../../src",
"../../examples/InverseDynamics",
"../../examples/ThirdPartyLibs",
"../../Extras/InverseDynamics",
"../gtest-1.7.0/include"
}
if os.is("Windows") then
--see http://stackoverflow.com/questions/12558327/google-test-in-visual-studio-2012
defines {"_VARIADIC_MAX=10"}
end
links {"BulletDynamics", "BulletCollision","BulletInverseDynamicsUtils", "BulletInverseDynamics","Bullet3Common","LinearMath", "gtest"}
files {
"test_invdyn_bullet.cpp",
"../../examples/Utils/b3ResourcePath.cpp",
"../../examples/Importers/ImportURDFDemo/ConvertRigidBodies2MultiBody.h",
"../../examples/Importers/ImportURDFDemo/MultiBodyCreationInterface.h",
"../../examples/Importers/ImportURDFDemo/MyMultiBodyCreator.cpp",
"../../examples/Importers/ImportURDFDemo/MyMultiBodyCreator.h",
"../../examples/Importers/ImportURDFDemo/BulletUrdfImporter.cpp",
"../../examples/Importers/ImportURDFDemo/BulletUrdfImporter.h",
"../../examples/Importers/ImportURDFDemo/urdfStringSplit.cpp",
"../../examples/Importers/ImportURDFDemo/UrdfParser.cpp",
"../../examples/Importers/ImportURDFDemo/UrdfParser.h",
"../../examples/Importers/ImportURDFDemo/URDF2Bullet.cpp",
"../../examples/Importers/ImportURDFDemo/URDF2Bullet.h",
"../../examples/Importers/ImportMeshUtility/b3ImportMeshUtility.cpp",
"../../examples/ThirdPartyLibs/stb_image/stb_image.cpp",
"../../examples/Utils/b3Clock.cpp",
"../../Extras/Serialize/BulletWorldImporter/*",
"../../Extras/Serialize/BulletFileLoader/*",
"../../examples/Importers/ImportURDFDemo/URDFImporterInterface.h",
"../../examples/Importers/ImportURDFDemo/URDFJointTypes.h",
"../../examples/Importers/ImportObjDemo/Wavefront2GLInstanceGraphicsShape.cpp",
"../../examples/Importers/ImportObjDemo/LoadMeshFromObj.cpp",
"../../examples/Importers/ImportSTLDemo/ImportSTLSetup.h",
"../../examples/Importers/ImportSTLDemo/LoadMeshFromSTL.h",
"../../examples/Importers/ImportColladaDemo/LoadMeshFromCollada.cpp",
"../../examples/Importers/ImportColladaDemo/ColladaGraphicsInstance.h",
"../../examples/ThirdPartyLibs/Wavefront/tiny_obj_loader.cpp",
"../../examples/ThirdPartyLibs/tinyxml/tinystr.cpp",
"../../examples/ThirdPartyLibs/tinyxml/tinyxml.cpp",
"../../examples/ThirdPartyLibs/tinyxml/tinyxmlerror.cpp",
"../../examples/ThirdPartyLibs/tinyxml/tinyxmlparser.cpp",
"../../examples/ThirdPartyLibs/urdf/boost_replacement/lexical_cast.h",
}
if os.is("Linux") then
links {"pthread"}
end
| mit |
MalRD/darkstar | scripts/zones/Southern_San_dOria/npcs/Apairemant.lua | 11 | 1266 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Apairemant
-- Gustaberg Regional Merchant
-- !pos 72 2 0 230
-----------------------------------
local ID = require("scripts/zones/Southern_San_dOria/IDs")
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/conquest")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
function onTrade(player,npc,trade)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then
player:messageSpecial(ID.text.FLYER_REFUSED)
else
onHalloweenTrade(player, trade, npc)
end
end
function onTrigger(player,npc)
if GetRegionOwner(dsp.region.GUSTABERG) ~= dsp.nation.SANDORIA then
player:showText(npc, ID.text.APAIREMANT_CLOSED_DIALOG)
else
local stock =
{
1108, 703, -- Sulfur
619, 43, -- Popoto
611, 36, -- Rye Flour
4388, 40, -- Eggplant
}
player:showText(npc, ID.text.APAIREMANT_OPEN_DIALOG)
dsp.shop.general(player, stock, SANDORIA)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c64550682.lua | 3 | 3111 | --スクラップ・オルトロス
function c64550682.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c64550682.spcon)
e1:SetValue(1)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(64550682,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCondition(c64550682.descon)
e2:SetTarget(c64550682.destg)
e2:SetOperation(c64550682.desop)
c:RegisterEffect(e2)
--search
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(64550682,1))
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetCondition(c64550682.thcon)
e3:SetTarget(c64550682.thtg)
e3:SetOperation(c64550682.thop)
c:RegisterEffect(e3)
end
function c64550682.spfilter(c)
return c:IsFaceup() and c:IsSetCard(0x24)
end
function c64550682.spcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c64550682.spfilter,c:GetControler(),LOCATION_MZONE,0,1,nil)
end
function c64550682.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1
end
function c64550682.desfilter(c)
return c:IsFaceup() and c:IsSetCard(0x24) and c:IsDestructable()
end
function c64550682.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c64550682.desfilter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c64550682.desfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c64550682.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c64550682.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return bit.band(c:GetReason(),0x41)==0x41 and re:GetOwner():IsSetCard(0x24)
end
function c64550682.filter(c)
return c:IsSetCard(0x24) and c:IsType(TYPE_MONSTER) and c:GetCode()~=64550682 and c:IsAbleToHand()
end
function c64550682.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c64550682.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c64550682.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c64550682.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c64550682.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c41705642.lua | 3 | 1354 | --サルベージ・ウォリアー
function c41705642.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(41705642,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCondition(c41705642.spcon)
e1:SetTarget(c41705642.sptg)
e1:SetOperation(c41705642.spop)
c:RegisterEffect(e1)
end
function c41705642.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_ADVANCE
end
function c41705642.filter(c,e,tp)
return c:IsType(TYPE_TUNER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c41705642.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c41705642.filter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE+LOCATION_HAND)
end
function c41705642.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c41705642.filter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c93211810.lua | 5 | 4133 | --超音速波
function c93211810.initial_effect(c)
--atkup
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c93211810.condition)
e1:SetCost(c93211810.cost)
e1:SetTarget(c93211810.target)
e1:SetOperation(c93211810.activate)
c:RegisterEffect(e1)
if not c93211810.global_check then
c93211810.global_check=true
c93211810[0]=0
c93211810[1]=0
local ge1=Effect.CreateEffect(c)
ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge1:SetCode(EVENT_ATTACK_ANNOUNCE)
ge1:SetOperation(c93211810.checkop)
Duel.RegisterEffect(ge1,0)
local ge2=Effect.CreateEffect(c)
ge2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge2:SetCode(EVENT_PHASE_START+PHASE_DRAW)
ge2:SetOperation(c93211810.clear)
Duel.RegisterEffect(ge2,0)
end
end
function c93211810.checkop(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
if tc:GetFlagEffect(93211810)==0 then
c93211810[ep]=c93211810[ep]+1
tc:RegisterFlagEffect(93211810,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
end
function c93211810.clear(e,tp,eg,ep,ev,re,r,rp)
c93211810[0]=0
c93211810[1]=0
end
function c93211810.condition(e,tp,eg,ep,ev,re,r,rp)
local ph=Duel.GetCurrentPhase()
return Duel.GetTurnPlayer()==tp and ph<PHASE_MAIN2 and (ph~=PHASE_DAMAGE or not Duel.IsDamageCalculated())
end
function c93211810.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return c93211810[tp]<2 end
end
function c93211810.filter(c,tp)
return c:IsFaceup() and c:IsSetCard(0x101b) and (c93211810[tp]==0 or c:GetFlagEffect(93211810)~=0)
end
function c93211810.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c93211810.filter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(c93211810.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c93211810.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil,tp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetProperty(EFFECT_FLAG_OATH)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetTarget(c93211810.ftarget)
e1:SetLabel(g:GetFirst():GetFieldID())
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c93211810.ftarget(e,c)
return e:GetLabel()~=c:GetFieldID()
end
function c93211810.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(tc:GetBaseAttack()*2)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_PIERCE)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EFFECT_IMMUNE_EFFECT)
e3:SetValue(c93211810.efilter)
e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e4:SetCode(EVENT_PHASE+PHASE_END)
e4:SetCountLimit(1)
e4:SetCondition(c93211810.descon)
e4:SetOperation(c93211810.desop)
e4:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e4,tp)
end
end
function c93211810.efilter(e,te)
return te:IsActiveType(TYPE_SPELL+TYPE_TRAP) and te:GetOwner()~=e:GetOwner()
end
function c93211810.desfilter(c)
return c:IsFaceup() and c:IsRace(RACE_MACHINE)
end
function c93211810.descon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c93211810.desfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c93211810.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c93211810.desfilter,tp,LOCATION_MZONE,0,nil)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
chu11/flux-core | src/shell/lua.d/mvapich.lua | 3 | 1511 | -------------------------------------------------------------
-- Copyright 2020 Lawrence Livermore National Security, LLC
-- (c.f. AUTHORS, NOTICE.LLNS, COPYING)
--
-- This file is part of the Flux resource manager framework.
-- For details, see https://github.com/flux-framework.
--
-- SPDX-License-Identifier: LGPL-3.0
-------------------------------------------------------------
if shell.options.mpi == "none" then return end
local f, err = require 'flux'.new ()
if not f then error (err) end
-- Lua implementation of dirname(3) to avoid pulling in posix module
local function dirname (d)
if not d:match ("/") then return "." end
return d:match ("^(.*[^/])/.-$")
end
local function setenv_prepend (var, val)
local path = shell.getenv (var)
-- If path not already set, then set it to val
if not path then
shell.setenv (var, val)
-- O/w, if val is not already set in path, prepend it
elseif path:match ("^[^:]+") ~= val then
shell.setenv (var, val .. ':' .. path)
end
-- O/w, val already first in path. Do nothing
end
local libpmi = f:getattr ('conf.pmi_library_path')
setenv_prepend ("LD_LIBRARY_PATH", dirname (libpmi))
shell.setenv ("MPIRUN_NTASKS", shell.info.ntasks)
shell.setenv ("MPIRUN_RSH_LAUNCH", 1)
plugin.register {
name = "mvapich",
handlers = {
{
topic = "task.init",
fn = function ()
local rank = task.info.rank
task.setenv ("MPIRUN_RANK", rank)
end
}
}
}
| lgpl-3.0 |
MalRD/darkstar | scripts/globals/weaponskills/shining_blade.lua | 10 | 1350 | -----------------------------------
-- Shining Blade
-- Sword weapon skill
-- Skill Level: 100
-- Deals light elemental damage to enemy. Damage varies with TP.
-- Aligned with the Soil Gorget.
-- Aligned with the Soil Belt.
-- Element: Light
-- Modifiers: STR:40% MND:40%
-- 100%TP 200%TP 300%TP
-- 1.125 2.222 3.523
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 1 params.ftp200 = 2 params.ftp300 = 2.5
params.str_wsc = 0.2 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.2 params.chr_wsc = 0.0
params.ele = dsp.magic.ele.LIGHT
params.skill = dsp.skill.SWORD
params.includemab = true
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.125 params.ftp200 = 2.222 params.ftp300 = 3.523
params.str_wsc = 0.4 params.mnd_wsc = 0.4
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
Lsty/ygopro-scripts | c34294855.lua | 5 | 2125 | --カース・オブ・ヴァンパイア
function c34294855.initial_effect(c)
--reborn preparation
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(34294855,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c34294855.spcon)
e1:SetCost(c34294855.spcost)
e1:SetOperation(c34294855.spop)
c:RegisterEffect(e1)
--reborn
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_STANDBY)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1)
e2:SetCondition(c34294855.spcon2)
e2:SetOperation(c34294855.spop2)
c:RegisterEffect(e2)
--atk up
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(34294855,1))
e3:SetCategory(CATEGORY_ATKCHANGE)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetCondition(c34294855.upcon)
e3:SetOperation(c34294855.upop)
c:RegisterEffect(e3)
end
function c34294855.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE)
end
function c34294855.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,500) end
Duel.PayLPCost(tp,500)
end
function c34294855.spop(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():RegisterFlagEffect(34294855,RESET_EVENT+0x1fe0000,0,0)
end
function c34294855.spcon2(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(34294855)>0
end
function c34294855.spop2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
c:ResetFlagEffect(34294855)
Duel.SpecialSummon(c,1,tp,tp,false,false,POS_FACEUP)
end
function c34294855.upcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1
end
function c34294855.upop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(500)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
end
end | gpl-2.0 |
Lsty/ygopro-scripts | c51554871.lua | 5 | 1201 | --灼熱工の巨匠カエン
function c51554871.initial_effect(c)
--atkup
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(51554871,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_GRAVE)
e1:SetCost(c51554871.cost)
e1:SetTarget(c51554871.target)
e1:SetOperation(c51554871.operation)
c:RegisterEffect(e1)
end
function c51554871.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c51554871.filter(c)
return c:IsFaceup() and c:IsSetCard(0x39)
end
function c51554871.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c51554871.filter,tp,LOCATION_MZONE,0,1,nil) end
end
function c51554871.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c51554871.filter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
if not tc then return end
local c=e:GetHandler()
while tc do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(400)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
| gpl-2.0 |
MahmoudDolah/Firmware-Entry-Points-In-Memory | openwrt/openwrt-generic-x86/usr/lib/lua/nixio/fs.lua | 184 | 3723 | --[[
nixio - Linux I/O library for lua
Copyright 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local table = require "table"
local nixio = require "nixio"
local type, ipairs, setmetatable = type, ipairs, setmetatable
require "nixio.util"
module ("nixio.fs", function(m) setmetatable(m, {__index = nixio.fs}) end)
function readfile(path, limit)
local fd, code, msg = nixio.open(path, "r")
local data
if not fd then
return nil, code, msg
end
data, code, msg = fd:readall(limit)
fd:close()
return data, code, msg
end
function writefile(path, data)
local fd, code, msg, stat = nixio.open(path, "w")
if not fd then
return nil, code, msg
end
stat, code, msg = fd:writeall(data)
fd:close()
return stat, code, msg
end
function datacopy(src, dest, size)
local fdin, code, msg = nixio.open(src, "r")
if not fdin then
return nil, code, msg
end
local fdout, code, msg = nixio.open(dest, "w")
if not fdout then
return nil, code, msg
end
local stat, code, msg, sent = fdin:copy(fdout, size)
fdin:close()
fdout:close()
return stat, code, msg, sent
end
function copy(src, dest)
local stat, code, msg, res = nixio.fs.lstat(src)
if not stat then
return nil, code, msg
end
if stat.type == "dir" then
if nixio.fs.stat(dest, type) ~= "dir" then
res, code, msg = nixio.fs.mkdir(dest)
else
stat = true
end
elseif stat.type == "lnk" then
res, code, msg = nixio.fs.symlink(nixio.fs.readlink(src), dest)
elseif stat.type == "reg" then
res, code, msg = datacopy(src, dest)
end
if not res then
return nil, code, msg
end
nixio.fs.utimes(dest, stat.atime, stat.mtime)
if nixio.fs.lchown then
nixio.fs.lchown(dest, stat.uid, stat.gid)
end
if stat.type ~= "lnk" then
nixio.fs.chmod(dest, stat.modedec)
end
return true
end
function move(src, dest)
local stat, code, msg = nixio.fs.rename(src, dest)
if not stat and code == nixio.const.EXDEV then
stat, code, msg = copy(src, dest)
if stat then
stat, code, msg = nixio.fs.unlink(src)
end
end
return stat, code, msg
end
function mkdirr(dest, mode)
if nixio.fs.stat(dest, "type") == "dir" then
return true
else
local stat, code, msg = nixio.fs.mkdir(dest, mode)
if not stat and code == nixio.const.ENOENT then
stat, code, msg = mkdirr(nixio.fs.dirname(dest), mode)
if stat then
stat, code, msg = nixio.fs.mkdir(dest, mode)
end
end
return stat, code, msg
end
end
local function _recurse(cb, src, dest)
local type = nixio.fs.lstat(src, "type")
if type ~= "dir" then
return cb(src, dest)
else
local stat, se, code, msg, s, c, m = true, nixio.const.sep
if dest then
s, c, m = cb(src, dest)
stat, code, msg = stat and s, c or code, m or msg
end
for e in nixio.fs.dir(src) do
if dest then
s, c, m = _recurse(cb, src .. se .. e, dest .. se .. e)
else
s, c, m = _recurse(cb, src .. se .. e)
end
stat, code, msg = stat and s, c or code, m or msg
end
if not dest then -- Postfix
s, c, m = cb(src)
stat, code, msg = stat and s, c or code, m or msg
end
return stat, code, msg
end
end
function copyr(src, dest)
return _recurse(copy, src, dest)
end
function mover(src, dest)
local stat, code, msg = nixio.fs.rename(src, dest)
if not stat and code == nixio.const.EXDEV then
stat, code, msg = _recurse(copy, src, dest)
if stat then
stat, code, msg = _recurse(nixio.fs.remove, src)
end
end
return stat, code, msg
end
function remover(src)
return _recurse(nixio.fs.remove, src)
end | apache-2.0 |
ThingMesh/openwrt-luci | libs/nixio/lua/nixio/fs.lua | 184 | 3723 | --[[
nixio - Linux I/O library for lua
Copyright 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local table = require "table"
local nixio = require "nixio"
local type, ipairs, setmetatable = type, ipairs, setmetatable
require "nixio.util"
module ("nixio.fs", function(m) setmetatable(m, {__index = nixio.fs}) end)
function readfile(path, limit)
local fd, code, msg = nixio.open(path, "r")
local data
if not fd then
return nil, code, msg
end
data, code, msg = fd:readall(limit)
fd:close()
return data, code, msg
end
function writefile(path, data)
local fd, code, msg, stat = nixio.open(path, "w")
if not fd then
return nil, code, msg
end
stat, code, msg = fd:writeall(data)
fd:close()
return stat, code, msg
end
function datacopy(src, dest, size)
local fdin, code, msg = nixio.open(src, "r")
if not fdin then
return nil, code, msg
end
local fdout, code, msg = nixio.open(dest, "w")
if not fdout then
return nil, code, msg
end
local stat, code, msg, sent = fdin:copy(fdout, size)
fdin:close()
fdout:close()
return stat, code, msg, sent
end
function copy(src, dest)
local stat, code, msg, res = nixio.fs.lstat(src)
if not stat then
return nil, code, msg
end
if stat.type == "dir" then
if nixio.fs.stat(dest, type) ~= "dir" then
res, code, msg = nixio.fs.mkdir(dest)
else
stat = true
end
elseif stat.type == "lnk" then
res, code, msg = nixio.fs.symlink(nixio.fs.readlink(src), dest)
elseif stat.type == "reg" then
res, code, msg = datacopy(src, dest)
end
if not res then
return nil, code, msg
end
nixio.fs.utimes(dest, stat.atime, stat.mtime)
if nixio.fs.lchown then
nixio.fs.lchown(dest, stat.uid, stat.gid)
end
if stat.type ~= "lnk" then
nixio.fs.chmod(dest, stat.modedec)
end
return true
end
function move(src, dest)
local stat, code, msg = nixio.fs.rename(src, dest)
if not stat and code == nixio.const.EXDEV then
stat, code, msg = copy(src, dest)
if stat then
stat, code, msg = nixio.fs.unlink(src)
end
end
return stat, code, msg
end
function mkdirr(dest, mode)
if nixio.fs.stat(dest, "type") == "dir" then
return true
else
local stat, code, msg = nixio.fs.mkdir(dest, mode)
if not stat and code == nixio.const.ENOENT then
stat, code, msg = mkdirr(nixio.fs.dirname(dest), mode)
if stat then
stat, code, msg = nixio.fs.mkdir(dest, mode)
end
end
return stat, code, msg
end
end
local function _recurse(cb, src, dest)
local type = nixio.fs.lstat(src, "type")
if type ~= "dir" then
return cb(src, dest)
else
local stat, se, code, msg, s, c, m = true, nixio.const.sep
if dest then
s, c, m = cb(src, dest)
stat, code, msg = stat and s, c or code, m or msg
end
for e in nixio.fs.dir(src) do
if dest then
s, c, m = _recurse(cb, src .. se .. e, dest .. se .. e)
else
s, c, m = _recurse(cb, src .. se .. e)
end
stat, code, msg = stat and s, c or code, m or msg
end
if not dest then -- Postfix
s, c, m = cb(src)
stat, code, msg = stat and s, c or code, m or msg
end
return stat, code, msg
end
end
function copyr(src, dest)
return _recurse(copy, src, dest)
end
function mover(src, dest)
local stat, code, msg = nixio.fs.rename(src, dest)
if not stat and code == nixio.const.EXDEV then
stat, code, msg = _recurse(copy, src, dest)
if stat then
stat, code, msg = _recurse(nixio.fs.remove, src)
end
end
return stat, code, msg
end
function remover(src)
return _recurse(nixio.fs.remove, src)
end | apache-2.0 |
RamiLego4Game/PlatformerWorld | Engine/Tiles/CoinBronze.lua | 1 | 1540 | --Author : Ramilego4Game - This File Is Part Of Platformer World--
--Type : Class/Tile-liquid--
Tile = class:new()
function Tile:init()
self.name = "CoinBronze"
self.category = "Decor"
self.hover = "Bronze"
self.thumbnail = "coin"..self.hover
self.snap = 70
self.dynamic = true
end
function Tile:create(marker,map)
self.active = 1
self.rayCall = function(fixture, x, y, xn, yn, fraction)
local data = tostring(fixture:getUserData())
if data:len() >= 8 and data:sub(1,6) == "Player" then
local pN = tonumber(data:sub(8))
if _HUD then _HUD:addScore(1,pN) end
self.active = 2
return 0
else
return -1
end
end
end
function Tile:update(marker,map,players,dt)
--[[if self.active == 1 then
local X,Y
for pN,player in pairs(players) do
X,Y = player.object.body:getPosition()
if X >= marker.x-18+35 and X <= marker.x+18+35 and Y >= marker.y-18+35 and Y <= marker.y+18+35 then
if _HUD then _HUD:addScore(1,pN) end
self.active = 2
return
end
end
end]]--
if self.active == 1 then
_World:rayCast( marker.x+23, marker.y+23, marker.x+self.snap-23, marker.y+self.snap-23, self.rayCall )
_World:rayCast( marker.x+self.snap-23, marker.y+23, marker.x+23, marker.y+self.snap-23, self.rayCall )
end
end
function Tile:draw(marker,map)
if self.active == 1 or not self.active then
local X,Y = marker.x,marker.y
love.graphics.setColor(marker.color or {255,255,255,255})
UI:Draw("coin"..self.hover,X,Y,70,70)
end
end | gpl-2.0 |
morfeo642/mta_plr_server | module/util/interiors.lua | 1 | 7073 | --[[!
\file
\brief Es un módulo que permite trabajar con las IDs de interiores y
obtener las IDs de los mundos y las posiciones de los mismos.
]]
loadModule("util/tableutils");
loadModule("util/checkutils");
local interiors =
{
{"(Outside)", 0, 0, 0, 3},
{"24/7 shop 1", 18, -30.95, -91.71, 1002.55},
{"24/7 shop 2", 6, -26.69, -57.81, 1002.55},
{"24/7 shop 3", 4, -27.31, -31.38, 1002.55},
{"Abandoned AC Tower (safehouse)", 10, 422.16, 2536.52, 9.01},
{"Ammu-Nation 1", 1, 286.15, -41.54, 1000.57},
{"Ammu-Nation 2", 4, 285.8, -85.45, 1000.54},
{"Ammu-Nation 3", 6, 296.92, -111.97, 1000.57},
{"Ammu-Nation 4", 6, 316.53, -169.61, 998.66},
{"Ammu-Nation 5 (2 floors)", 7, 309.38, -136.3, 999.60},
{"Andromada", 9, 315.48, 984.13, 1959.11},
{"Atrium lobby entrance", 18, 1726.19, -1638.01, 19.27},
{"Atrium lobby exit", 18, 1700.74, -1668.48, 19.22},
{"Bar 1 (Gaydar Station)", 17, 493.39, -24.92, 999.69},
{"Bar 2 (Ten Green Bottles)", 11, 501.98, -67.75, 997.84},
{"Big Bear's apartment", 3, 1527.38, -11.02, 1002.1},
{"Big Smoke's Crack Palace", 2, 2541.7, -1304.01, 1024.07},
{"Big Spread Ranch", 3, 1212.02, -25.86, 1000.09},
{"Binco", 15, 207.74, -111.42, 1004.27},
{"Brothel", 3, 944.8, 1.96, 1000.93},
{"Brothel 2", 3, 963.0, -47.2, 1001.12},
{"Budget Inn Motel Room", 12, 447.52, 511.49, 1001.4},
{"Burger Shot", 10, 363.11, -74.88, 1000.55},
{"Burning Desire House", 5, 2352.34, -1181.25, 1027},
{"Cafe shop (Catalina)", 1, 681.58, -473.42, 15.59},
{"Caligulas Casino (Roof access)", 1, 2264.49, 1619.58, 1089.5},
{"Cluckin' Bell", 9, 365.67, -11.61, 1000.87},
{"Colonel Fuhrberger's House", 8, 2807.62, -1174.1, 1024.58},
{"Diner 1", 4, 460.1, -88.43, 998.62},
{"Diner 2", 5, 459.35, -111.01, 998.72},
{"Dnameier Sachs", 14, 204.33, -168.7, 999.58},
{"Driving School", 3, -2029.72, -119.55, 1034.17},
{"Francis Int. Airport (Baggage Claim)", 14, -1860.82, 59.74, 1062.14},
{"Gay Gordo's Barbershop", 3, 418.65, -84.14, 1000.96},
{"Hemlock Tattoo", 17, -204.44, -9.17, 1001.3},
{"Insnamee Track Betting", 3, 834.82, 7.42, 1003.18},
{"Insnamee Track Betting (Chinatown SF)", 1, -2166.01, 643.05, 1057.59},
{"Jefferson Motel", 15, 2214.34, -1150.51, 1024.8},
{"Jizzy's Pleasure Domes", 3, -2661.01, 1417.74, 921.31},
{"Johnson House", 3, 2496.05, -1692.73, 1013.75},
{"LS Tattoo Parlour", 16, -204.44, -27.15, 1001.3},
{"LSPD HQ", 6, 246.78, 62.2, 1002.64},
{"LV Meat Factory", 1, 965.38, 2159.33, 1010.02},
{"LV Tattoo Parlour", 3, -204.44, -44.35, 1001.3},
{"LVPD HQ", 3, 238.66, 139.35, 1002.05},
{"Las Venturas Gym", 7, 773.58, -78.2, 999.69},
{"Las Venturas Planning Dep.", 3, 390.87, 173.81, 1007.39},
{"Liberty City", 1, -750.80, 491.00, 1371.70},
{"Lil Probe Inn (UFO Bar)", 18, -229.03, 1401.23, 26.77},
{"Los Santos Gym", 5, 772.11, -5, 999.69},
{"Macisla's Barbershop", 12, 412.02, -54.55, 1000.96},
{"Madd Dogg's Mansion 1", 5, 1260.58, -785.31, 1090.96},
{"Madd Dogg's Mansion 2", 5, 1299.08, -796.83, 1083.03},
{"Millie's Bedroom", 6, 347.52, 306.77, 999.15},
{"Police Station 1", 5, 322.72, 306.4, 999.11},
{"RC Zero's Battlefield", 10, -975.57, 1061.13, 1345.67},
{"RC Zero's Shop", 6, -2241.07, 128.52, 1034.42},
{"Record Label Hallway", 3, 1037.9, 5.35, 1001.28},
{"Reece's Barbershop", 2, 411.63, -23.33, 1000.8},
{"Restaurant 1", 1, 452.89, -18.18, 1000.18},
{"Restaurant 2", 6, 441.98, -49.92, 998.69},
{"Rusty Brown's - Ring Donuts", 17, 378.29, -188.9, 1000.61},
{"SFPD HQ", 10, 246.62, 112.1, 1003.2},
{"Safe House 1", 1, 223.04, 1287.26, 1081.2},
{"Safe House 10", 5, 2233.8, -1115.36, 1049.91},
{"Safe House 11", 8, 2365.3, -1134.92, 1049.91},
{"Safe House 12", 11, 2282.91, -1140.29, 1049.91},
{"Safe House 13", 6, 2196.79, -1204.35, 1048.05},
{"Safe House 14", 10, 2270.39, -1210.45, 1046.57},
{"Safe House 15", 6, 2308.79, -1212.88, 1048.03},
{"Safe House 16", 1, 2217.54, -1076.29, 1049.52},
{"Safe House 17", 2, 2237.59, -1080.87, 1048.07},
{"Safe House 18", 9, 2317.82, -1026.75, 1049.21},
{"Safe House 2", 4, 260.98, 1284.55, 1079.3},
{"Safe House 3", 5, 140.18, 1366.58, 1082.97},
{"Safe House 4", 9, 82.95, 1322.44, 1082.89},
{"Safe House 5", 15, -283.55, 1470.98, 1083.45},
{"Safe House 6", 4, -260.6, 1456.62, 1083.45},
{"Safe House 7", 8, -42.58, 1405.61, 1083.45},
{"Safe House 8", 6, -68.69, 1351.97, 1079.28},
{"Safe House 9", 6, 2333.11, -1077.1, 1048.04},
{"San Fierro Chunk (cutscene place)", 14, -2015.66, 147.20, 29.31},
{"San Fierro Gym", 6, 774.21, -50.02, 999.69},
{"Sex Shop", 3, -100.33, -24.92, 999.74},
{"Shamal", 1, 1.61, 34.74, 1199.0},
{"Stadium 1", 1, -1400.21, 106.89, 1032.27},
{"Stadium 2 (Bloodbowl)", 15, -1394.20, 987.62, 1023.96},
{"Stadium 3 (Kickstart)", 14, -1410.72, 1591.16, 1052.53},
{"Sub Urban", 1, 203.78, -49.89, 1000.8},
{"The Caligulas Casino", 1, 2233.91, 1714.73, 1011.38},
{"The Casino", 12, 1133.07, -12.77, 999.75},
{"The Crack Den", 5, 318.57, 1115.21, 1082.98},
{"The Four Dragons Casino", 10, 2018.95, 1017.09, 995.88},
{"The Four Dragons Casino (office)", 11, 2004.01, 1027.42, 33.53},
{"The Pig Pen", 2, 1204.81, -12.79, 1000.09},
{"The Sherman's Dam Generator Hall", 17, -956.6, 1862.23, 9.01},
{"Train Hard", 3, 207.06, -139.81, 1002.52},
{"Victim", 5, 227.29, -7.43, 1001.26},
{"Warehouse", 1, 1401.3, -15.5, 1002.9},
{"Well Stacked Pizza Co.", 5, 372.35, -133.55, 1000.45},
{"Zip", 18, 161.39, -96.69, 1000.81}
}
--[[!
@return Devuelve una lista de nombres de todos los interiores.
]]
function getAllInteriors()
local aux = {};
for _, interiorInfo in ipairs(interiors) do
local interiorName = unpack(interiorInfo);
aux[#aux+1] = interiorName;
end;
return aux;
end;
--[[!
Obtiene la id del mundo para un interior.
@param interiorName Es el nombre del interior
@return Devuelve la id del mundo a la que pertenece este interior o false si este
nombre no encaja con ningún nombre asociado a ningun interior.
@note Esta id puede usarse como argumento para la función setElementInterior
]]
function getInteriorWorldId(interiorName)
checkArgumentType("getInteriorWorldId", 2, interiorName, 1, "string");
local interiorIndex = table.match(interiors, function(value) return (interiorName == value[1]); end)
if not interiorIndex then
return false;
end;
local _, worldId = unpack(interiors[interiorIndex]);
return worldId;
end;
--[[!
Obtiene las coordenadas X, Y, Z del interior en su mundo.
@param interiorName Es el nombre del interior.
return Devuelve un lista de tres elementos con las coordenadas X,Y,Z del interior o
false si no existe ningún interior que tenga ese nombre.
@note Estas coordenadas pueden usarse como argumentos para la función setElementInterior.
]]
function getInteriorPosition(interiorName)
checkArgumentType("getInteriorPosition", 2, interiorName, 1, "string");
local interiorIndex = table.match(interiors, function(value) return (interiorName == value[1]); end)
if not interiorIndex then
return false;
end;
local _, worldId, posX, posY, posZ = unpack(interiors[interiorIndex]);
return posX, posY, posZ;
end;
| mit |
MalRD/darkstar | scripts/zones/West_Ronfaure/npcs/Esca.lua | 9 | 1839 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Esca
-- Involved in Quest "The Pickpocket"
-- !pos -624.231 -51.499 278.369 100
-----------------------------------
local ID = require("scripts/zones/West_Ronfaure/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onTrade(player, npc, trade)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.THE_PICKPOCKET) == QUEST_ACCEPTED and player:getCharVar("thePickpocket") == 1 and npcUtil.tradeHas(trade, 578) then
player:startEvent(121)
end
end
function onTrigger(player, npc)
local thePickpocketStat = player:getCharVar("thePickpocket")
local chasingQuotasStat = player:getCharVar("ChasingQuotas_Progress")
-- CHASING QUOTAS
if chasingQuotasStat == 4 then
player:startEvent(137) -- My earring! I stole the last dragoon's armor. Chosen option does not matter.
elseif chasingQuotasStat == 5 then
player:startEvent(138) -- Reminder for finding the armor.
-- THE PICKPOCKET
elseif thePickpocketStat == 1 then
player:startEvent(120)
elseif thePickpocketStat == 2 and not player:hasItem(579) then
player:startEvent(128)
elseif thePickpocketStat == 2 then
player:startEvent(123)
-- STANDARD DIALOG
else
player:startEvent(119)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
-- THE PICKPOCKET
if csid == 121 and npcUtil.giveItem(player, 579) then
player:setCharVar("thePickpocket", 2)
player:confirmTrade()
-- CHASING QUOTAS
elseif csid == 137 then
player:setCharVar("ChasingQuotas_Progress", 5)
player:delKeyItem(dsp.ki.SHINY_EARRING)
end
end
| gpl-3.0 |
Lsty/ygopro-scripts | c26708437.lua | 3 | 1310 | --エクシーズ・リボーン
function c26708437.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetTarget(c26708437.target)
e1:SetOperation(c26708437.activate)
c:RegisterEffect(e1)
end
function c26708437.filter(c,e,tp)
return c:IsType(TYPE_XYZ) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c26708437.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c26708437.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c26708437.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c26708437.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c26708437.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 and c:IsRelateToEffect(e) then
c:CancelToGrave()
Duel.Overlay(tc,Group.FromCards(c))
end
end
| gpl-2.0 |
patixx/bostg | plugins/webshot.lua | 11 | 1605 | local helpers = require "OAuth.helpers"
local base = 'https://screenshotmachine.com/'
local url = base .. 'processor.php'
local function get_webshot_url(param)
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
headers = {
referer = base,
dnt = "1",
origin = base,
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
},
redirect = false
}
local arguments = {
urlparam = param,
size = "FULL"
}
request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments)
local ok, response_code, response_headers, response_status_line = https.request(request_constructor)
if not ok or response_code ~= 200 then
return nil
end
local response = table.concat(response_body)
return string.match(response, "href='(.-)'")
end
local function run(msg, matches)
local find = get_webshot_url(matches[1])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
return {
description = "Send an screenshot of a website.",
usage = {
"!عکس [url]: Take an screenshot of the web and send it back to you."
},
patterns = {
"^!عکس (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!عکس ([%w-_%.%?%.:/%+=&]+)$",
"^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!webshot ([%w-_%.%?%.:/%+=&]+)$",
},
run = run
}
| gpl-2.0 |
Lsty/ygopro-scripts | c76080032.lua | 5 | 2828 | --ZW-一角獣皇槍
function c76080032.initial_effect(c)
c:SetUniqueOnField(1,0,76080032)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(76080032,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c76080032.eqcon)
e1:SetTarget(c76080032.eqtg)
e1:SetOperation(c76080032.eqop)
c:RegisterEffect(e1)
--disable
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_BE_BATTLE_TARGET)
e3:SetRange(LOCATION_SZONE)
e3:SetCondition(c76080032.discon)
e3:SetOperation(c76080032.disop)
c:RegisterEffect(e3)
end
function c76080032.eqcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():CheckUniqueOnField(tp)
end
function c76080032.filter(c)
return c:IsFaceup() and c:IsCode(56840427)
end
function c76080032.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c76080032.filter(chkc) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c76080032.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c76080032.filter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c76080032.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 or tc:GetControler()~=tp or tc:IsFacedown() or not tc:IsRelateToEffect(e) or not c:CheckUniqueOnField(tp) then
Duel.SendtoGrave(c,REASON_EFFECT)
return
end
Duel.Equip(tp,c,tc,true)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(c76080032.eqlimit)
e1:SetLabelObject(tc)
c:RegisterEffect(e1)
--atkup
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(1900)
e2:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e2)
end
function c76080032.discon(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetHandler():GetEquipTarget()
return ec and (ec==Duel.GetAttacker() or ec==Duel.GetAttackTarget()) and ec:GetBattleTarget()
end
function c76080032.disop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetEquipTarget():GetBattleTarget()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE)
tc:RegisterEffect(e2)
end
function c76080032.eqlimit(e,c)
return c==e:GetLabelObject()
end
| gpl-2.0 |
Lsty/ygopro-scripts | c39139935.lua | 5 | 2033 | --No.33 先史遺産-超兵器マシュ=マック
function c39139935.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,5,2)
c:EnableReviveLimit()
--attack up
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DAMAGE+CATEGORY_ATKCHANGE)
e1:SetDescription(aux.Stringid(39139935,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c39139935.cost)
e1:SetTarget(c39139935.target)
e1:SetOperation(c39139935.operation)
c:RegisterEffect(e1)
end
c39139935.xyz_number=33
function c39139935.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c39139935.filter(c)
return c:IsFaceup() and c:GetAttack()~=c:GetBaseAttack()
end
function c39139935.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c39139935.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c39139935.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c39139935.filter,tp,0,LOCATION_MZONE,1,1,nil)
local tc=g:GetFirst()
local atk=tc:GetAttack()
local batk=tc:GetBaseAttack()
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,(batk>atk) and (batk-atk) or (atk-batk))
end
function c39139935.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local atk=tc:GetAttack()
local batk=tc:GetBaseAttack()
if batk~=atk then
local dif=(batk>atk) and (batk-atk) or (atk-batk)
local dam=Duel.Damage(1-tp,dif,REASON_EFFECT)
if dam>0 and c:IsRelateToEffect(e) and c:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(dif)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
end
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c39389320.lua | 5 | 1079 | --バーバリアン・キング
function c39389320.initial_effect(c)
--multi attack
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(39389320,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c39389320.condition)
e1:SetCost(c39389320.cost)
e1:SetOperation(c39389320.operation)
c:RegisterEffect(e1)
end
function c39389320.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsAbleToEnterBP()
end
function c39389320.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsRace,1,e:GetHandler(),RACE_WARRIOR) end
local g=Duel.SelectReleaseGroup(tp,Card.IsRace,1,10,e:GetHandler(),RACE_WARRIOR)
local ct=Duel.Release(g,REASON_COST)
e:SetLabel(ct)
end
function c39389320.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EXTRA_ATTACK)
e1:SetValue(e:GetLabel())
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c36560997.lua | 5 | 1795 | --オーバー・コアリミット
function c36560997.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--atk
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x1d))
e2:SetValue(500)
c:RegisterEffect(e2)
--atkup
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(36560997,0))
e3:SetCategory(CATEGORY_TOGRAVE)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_SZONE)
e3:SetCountLimit(1)
e3:SetCost(c36560997.atcost)
e3:SetTarget(c36560997.attg)
e3:SetOperation(c36560997.atop)
c:RegisterEffect(e3)
end
function c36560997.cfilter(c)
return c:IsCode(36623431) and c:IsDiscardable()
end
function c36560997.atcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c36560997.cfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,c36560997.cfilter,1,1,REASON_COST+REASON_DISCARD)
end
function c36560997.filter(c)
return c:IsFaceup() and c:IsSetCard(0x1d)
end
function c36560997.attg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c36560997.filter,tp,LOCATION_MZONE,0,1,nil) end
end
function c36560997.atop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local g=Duel.GetMatchingGroup(c36560997.filter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(1000)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Western_Adoulin/npcs/Shipilolo.lua | 9 | 3081 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Shipilolo
-- Type: Standard NPC and Quest NPC
-- Involved with Quests: 'A Certain Substitute Patrolman'
-- 'Fertile Ground'
-- 'The Old Man and the Harpoon'
-- 'Wayward Waypoints'
-- !pos 84 0 -60 256
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Western_Adoulin/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local TOMATH = player:getQuestStatus(ADOULIN, dsp.quest.id.adoulin.THE_OLD_MAN_AND_THE_HARPOON);
local Fertile_Ground = player:getQuestStatus(ADOULIN, dsp.quest.id.adoulin.FERTILE_GROUND);
local Wayward_Waypoints = player:getQuestStatus(ADOULIN, dsp.quest.id.adoulin.WAYWARD_WAYPOINTS);
Wayward_Waypoints = (Wayward_Waypoints == QUEST_ACCEPTED) and (player:getCharVar("WW_Need_Shipilolo") > 0)
local ACSP = player:getQuestStatus(ADOULIN, dsp.quest.id.adoulin.A_CERTAIN_SUBSTITUTE_PATROLMAN);
local SOA_Mission = player:getCurrentMission(SOA);
if (SOA_Mission >= dsp.mission.id.soa.LIFE_ON_THE_FRONTIER) then
if ((TOMATH == QUEST_ACCEPTED) and player:hasKeyItem(dsp.ki.BROKEN_HARPOON)) then
-- Progresses Quest: 'The Old Man and the Harpoon'
player:startEvent(2543);
elseif ((Fertile_Ground == QUEST_ACCEPTED) and (not player:hasKeyItem(dsp.ki.BOTTLE_OF_FERTILIZER_X))) then
-- Progresses Quest: 'Fertile Ground'
player:startEvent(2850);
elseif (Wayward_Waypoints and (not player:hasKeyItem(dsp.ki.WAYPOINT_RECALIBRATION_KIT))) then
-- Progresses Quest: 'Wayward Waypoints'
player:startEvent(79);
elseif ((ACSP == QUEST_ACCEPTED) and (player:getCharVar("ACSP_NPCs_Visited") == 5)) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:startEvent(2557);
else
-- Standard dialogue
player:startEvent(535);
end
else
-- Dialogue prior to joining colonization effort
player:startEvent(526);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 2543) then
-- Progresses Quest: 'The Old Man and the Harpoon'
player:delKeyItem(dsp.ki.BROKEN_HARPOON);
player:addKeyItem(dsp.ki.EXTRAVAGANT_HARPOON);
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.EXTRAVAGANT_HARPOON);
elseif (csid == 2850) then
-- Progresses Quest: 'Fertile Ground'
player:addKeyItem(dsp.ki.BOTTLE_OF_FERTILIZER_X);
elseif (csid == 79) then
player:addKeyItem(dsp.ki.WAYPOINT_RECALIBRATION_KIT);
player:setCharVar("WW_Need_Shipilolo", 0);
elseif (csid == 2557) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:setCharVar("ACSP_NPCs_Visited", 6);
end
end;
| gpl-3.0 |
HexCodeCC/DynaCode | src/Classes/Render/StageCanvas.lua | 2 | 5850 | local GREYSCALE_FILTER = {
[1] = 256;
[2] = 256;
[4] = 256;
[8] = 1;
[16] = 256;
[32] = 128;
[64] = 256;
[128] = 128;
[256] = 128;
[512] = 256;
[1024] = 128;
[2048] = 128;
[4096] = 128;
[8192] = 256;
[16384] = 128;
[32768] = 128;
}
class "StageCanvas" extends "Canvas" {
frame = nil;
filter = nil;
cache = {};
greyOutWhenNotFocused = true;
}
function StageCanvas:initialise( ... )
local width, height = ParseClassArguments( self, { ... }, { {"width", "number"}, {"height", "number"} }, true, true )
AssertClass( self.stage, "Stage", true, "StageCanvas requires stage to be a Stage instance, not: "..tostring( self.stage ) )
self.super( width, height )
self:updateFilter()
end
function StageCanvas:updateFilter()
if self.stage.focused or not self.greyOutWhenNotFocused then
self.filter = "NONE"
else
self.filter = "GREYSCALE"
end
end
function StageCanvas:setFilter( fil )
-- clear the cache
self.filter = fil
--self:redrawFrame()
end
function StageCanvas:getColour( col )
if self.filter == "NONE" then return col end
if self.filter == "GREYSCALE" then
return GREYSCALE_FILTER[ col ]
end
end
function StageCanvas:redrawFrame()
-- This function creates a table of pixels representing the background and shadow of the stage.
-- Function should only be executed during full clears, not every draw.
local stage = self.stage
local gc = self.getColour
local hasTitleBar = not stage.borderless
local title = OverflowText(stage.title or "", stage.width - ( stage.closeButton and 1 or 0 ) ) or ""
local hasShadow = stage.shadow and stage.focused
local shadowColour = stage.shadowColour
local titleColour = stage.mouseMode and stage.activeTitleTextColour or stage.titleTextColour
local titleBackgroundColour = stage.mouseMode and stage.activeTitleBackgroundColour or stage.titleBackgroundColour
local width = self.width --+ ( stage.shadow and 0 or 0 )
local height = self.height --+ ( stage.shadow and 1 or 0 )
local frame = {}
for y = 0, height - 1 do
local yPos = width * y
for x = 1, width do
-- Find out what goes here (title, shadow, background)
local pos = yPos + x
if hasTitleBar and y == 0 and ( hasShadow and x < width or not hasShadow ) then
-- Draw the correct part of the title bar here.
if x == stage.width and stage.closeButton then
frame[pos] = {"X", stage.closeButtonTextColour, stage.closeButtonBackgroundColour}
else
local char = string.sub( title, x, x )
frame[pos] = {char ~= "" and char or " ", titleColour, titleBackgroundColour}
end
elseif hasShadow and ( ( x == width and y ~= 0 ) or ( x ~= 1 and y == height - 1 ) ) then
-- Draw the shadow
frame[pos] = {" ", shadowColour, shadowColour}
else
local ok = true
if hasShadow and ( ( x == width and y == 0 ) or ( x == 1 and y == height - 1 ) ) then
ok = false
end
if ok then
frame[pos] = { false, false, false } -- background
end
end
end
end
self.frame = frame
end
function StageCanvas:drawToCanvas( canvas, xO, yO, ignoreMap )
local buffer = self.buffer
local frame = self.frame
local stage = self.stage
local gc = self.getColour
local mappingID = self.stage.mappingID
local xO = type( xO ) == "number" and xO - 1 or 0
local yO = type( yO ) == "number" and yO - 1 or 0
local width = self.width --+ ( stage.shadow and 0 or 0 )
local height = self.height -- ( stage.shadow and 1 or 1 )
local map = self.stage.application.layerMap
local cHeight, cWidth = canvas.height, canvas.width
local cBuffer = canvas.buffer
local tc, bg = self.textColour, self.backgroundColour
for y = 0, height - 1 do
local yPos = width * y
local yBPos = canvas.width * ( y + yO )
if y + yO + 1 > 0 and y + yO - 1 < cHeight then
for x = 1, width do
if x + xO > 0 and x + xO - 1 < cWidth then
local bPos = yBPos + (x + xO)
if map[ bPos ] == mappingID then
local pos = yPos + x
local pixel = buffer[ pos ]
if pixel then
if not pixel[1] then
-- draw the frame
local framePixel = frame[ pos ]
if framePixel then
local fP = framePixel[1]
if x == width and y == 0 and not stage.borderless and stage.closeButton and self.greyOutWhenNotFocused then -- keep the closeButton coloured.
cBuffer[ bPos ] = { fP, framePixel[2] or tc, framePixel[3] or bg}
else
cBuffer[ bPos ] = { fP, gc( self, framePixel[2] or tc ), gc( self, framePixel[3] or bg ) }
end
end
else
-- draw the node pixel
cBuffer[ bPos ] = { pixel[1] or " ", gc( self, pixel[2] or tc ), gc( self, pixel[3] or bg ) }
end
else
cBuffer[ bPos ] = { false, false, false }
end
end
end
end
end
end
end
| mit |
MalRD/darkstar | scripts/globals/items/serving_of_zaru_soba.lua | 11 | 1080 | -----------------------------------------
-- ID: 5727
-- Item: serving_of_zaru_soba
-- Food Effect: 30Min?, All Races
-----------------------------------------
-- Agility 3
-- HP % 12 (cap 180)
-- Resist Sleep +5
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5727)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.AGI, 3)
target:addMod(dsp.mod.FOOD_HPP, 12)
target:addMod(dsp.mod.FOOD_HP_CAP, 180)
target:addMod(dsp.mod.SLEEPRES, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.AGI, 3)
target:delMod(dsp.mod.FOOD_HPP, 12)
target:delMod(dsp.mod.FOOD_HP_CAP, 180)
target:delMod(dsp.mod.SLEEPRES, 5)
end
| gpl-3.0 |
TheSAguy/Natural-Evolution | prototypes/Vanilla_Changes/Settings.lua | 1 | 9289 |
require "prototypes.Vanilla_Changes.Functions"
Damage = {
Small_Biter = Biter_Melee_Attack_Healthy(5),
Small_Biter_Mk2 = Biter_Melee_Attack_Infected(8,5),
Small_Biter_Mk3 = Biter_Melee_Attack_Mutated(10,5),
Medium_Biter = Biter_Melee_Attack_Healthy(15),
Medium_Biter_Mk2 = Biter_Melee_Attack_Infected(20,10),
Medium_Biter_Mk3 = Biter_Melee_Attack_Mutated(20,10),
Big_Biter = Biter_Melee_Attack_Healthy(40),
Big_Biter_Mk2 = Biter_Melee_Attack_Infected(45,20),
Big_Biter_Mk3 = Biter_Melee_Attack_Mutated(50,20),
Behemoth_Biter = Biter_Melee_Attack_Healthy(100)
}
Health = {
Small_Biter = 15,
Small_Biter_Mk2 = 30,
Small_Biter_Mk3 = 45,
Medium_Biter = 75,
Medium_Biter_Mk2 = 150,
Medium_Biter_Mk3 = 225,
Big_Biter = 375,
Big_Biter_Mk2 = 750,
Big_Biter_Mk3 = 1125,
Behemoth_Biter = 5000,
Small_Spitter = 10,
Small_Spitter_Mk2 = 20,
Small_Spitter_Mk3 = 30,
Medium_Spitter = 50,
Medium_Spitter_Mk2 = 100,
Medium_Spitter_Mk3 = 150,
Big_Spitter = 200,
Big_Spitter_Mk2 = 450,
Big_Spitter_Mk3 = 700,
Behemoth_Spitter = 2000
}
Resistances = {
Small_Biter = {
{type = "fire", decrease = 0, percent = -45},
{type = "physical", decrease = 1, percent = 5},
{type = "impact", decrease = 1, percent = 0},
{type = "explosion", decrease = 1, percent = 0},
{type = "acid", decrease = 1, percent = 0},
{type = "poison", decrease = 0, percent = 0},
{type = "laser", decrease = 0, percent = 0}},
Small_Biter_Mk2 = {
{type = "fire", decrease = 0, percent = -45},
{type = "physical", decrease = 2, percent = 5},
{type = "impact", decrease = 2, percent = 0},
{type = "explosion", decrease = 2, percent = 0},
{type = "acid", decrease = 2, percent = 0},
{type = "poison", decrease = 0, percent = 0},
{type = "laser", decrease = 0, percent = 0}},
Small_Biter_Mk3 = {
{type = "fire", decrease = 0, percent = -40},
{type = "physical", decrease = 3, percent = 5},
{type = "impact", decrease = 3, percent = 0},
{type = "explosion", decrease = 3, percent = 0},
{type = "acid", decrease = 3, percent = 0},
{type = "poison", decrease = 0, percent = 0},
{type = "laser", decrease = 0, percent = 0}},
Medium_Biter = {
{type = "fire", decrease = 0, percent = -35},
{type = "physical", decrease = 2, percent = 5},
{type = "impact", decrease = 5, percent = 0},
{type = "explosion", decrease = 5, percent = 5},
{type = "acid", decrease = 5, percent = 5},
{type = "poison", decrease = 0, percent = 5},
{type = "laser", decrease = 2, percent = 0}},
Medium_Biter_Mk2 = {
{type = "fire", decrease = 0, percent = -35},
{type = "physical", decrease = 3, percent = 0},
{type = "impact", decrease = 6, percent = 5},
{type = "explosion", decrease = 6, percent = 5},
{type = "acid", decrease = 6, percent = 5},
{type = "poison", decrease = 0, percent = 5},
{type = "laser", decrease = 3, percent = 5}},
Medium_Biter_Mk3 = {
{type = "fire", decrease = 0, percent = -30},
{type = "physical", decrease = 4, percent = 5},
{type = "impact", decrease = 7, percent = 5},
{type = "explosion", decrease = 7, percent = 5},
{type = "acid", decrease = 7, percent = 5},
{type = "poison", decrease = 0, percent = 5},
{type = "laser", decrease = 4, percent = 5}},
Big_Biter = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 8, percent = 15},
{type = "impact", decrease = 10, percent = 10},
{type = "explosion", decrease = 10, percent = 10},
{type = "acid", decrease = 10, percent = 10},
{type = "poison", decrease = 0, percent = 10},
{type = "laser", decrease = 5, percent = 5}},
Big_Biter_Mk2 = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 10, percent = 15},
{type = "impact", decrease = 11, percent = 10},
{type = "explosion", decrease = 11, percent = 10},
{type = "acid", decrease = 11, percent = 10},
{type = "poison", decrease = 0, percent = 10},
{type = "laser", decrease = 5, percent = 10}},
Big_Biter_Mk3 = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 12, percent = 15},
{type = "impact", decrease = 10, percent = 10},
{type = "explosion", decrease = 12, percent = 10},
{type = "acid", decrease = 12, percent = 10},
{type = "poison", decrease = 0, percent = 10},
{type = "laser", decrease = 10, percent = 10}},
Behemoth_Biter = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 15, percent = 20},
{type = "impact", decrease = 15, percent = 15},
{type = "explosion", decrease = 15, percent = 15},
{type = "acid", decrease = 15, percent = 15},
{type = "poison", decrease = 0, percent = 15},
{type = "laser", decrease = 15, percent = 15}},
Small_Spitter = {
{type = "fire", decrease = 0, percent = -45},
{type = "physical", decrease = 1, percent = 0},
{type = "impact", decrease = 1, percent = 0},
{type = "explosion", decrease = 1, percent = 5,},
{type = "acid", decrease = 1, percent = 0},
{type = "poison", decrease = 0, percent = 0},
{type = "laser", decrease = 0, percent = 0}},
Small_Spitter_Mk2 = {
{type = "fire", decrease = 0, percent = -45},
{type = "physical", decrease = 2, percent = 0},
{type = "impact", decrease = 2, percent = 0},
{type = "explosion", decrease = 2, percent = 5,},
{type = "acid", decrease = 2, percent = 0},
{type = "poison", decrease = 0, percent = 0},
{type = "laser", decrease = 0, percent = 0}},
Small_Spitter_Mk3 = {
{type = "fire", decrease = 0, percent = -40},
{type = "physical", decrease = 3, percent = 0},
{type = "impact", decrease = 3, percent = 0},
{type = "explosion", decrease = 3, percent = 5,},
{type = "acid", decrease = 3, percent = 0},
{type = "poison", decrease = 0, percent = 0},
{type = "laser", decrease = 0, percent = 0}},
Medium_Spitter = {
{type = "fire", decrease = 0, percent = -35},
{type = "physical", decrease = 1, percent = 0},
{type = "impact", decrease = 5, percent = 5},
{type = "explosion", decrease = 5, percent = 10},
{type = "acid", decrease = 5, percent = 5},
{type = "poison", decrease = 0, percent = 5},
{type = "laser", decrease = 0, percent = 0}},
Medium_Spitter_Mk2 = {
{type = "fire", decrease = 0, percent = -35},
{type = "physical", decrease = 2, percent = 0},
{type = "impact", decrease = 6, percent = 5},
{type = "explosion", decrease = 6, percent = 10},
{type = "acid", decrease = 6, percent = 5},
{type = "poison", decrease = 0, percent = 5},
{type = "laser", decrease = 0, percent = 5}},
Medium_Spitter_Mk3 = {
{type = "fire", decrease = 0, percent = -30},
{type = "physical", decrease = 3, percent = 0},
{type = "impact", decrease = 7, percent = 5},
{type = "explosion", decrease = 7, percent = 10},
{type = "acid", decrease = 7, percent = 5},
{type = "poison", decrease = 0, percent = 5},
{type = "laser", decrease = 5, percent = 5}},
Big_Spitter = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 5, percent = 5},
{type = "impact", decrease = 5, percent = 5},
{type = "explosion", decrease = 10, percent = 20},
{type = "acid", decrease = 10, percent = 10},
{type = "poison", decrease = 0, percent = 10},
{type = "laser", decrease = 5, percent = 5}},
Big_Spitter_Mk2 = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 6, percent = 5},
{type = "impact", decrease = 5, percent = 10},
{type = "explosion", decrease = 11, percent = 20},
{type = "acid", decrease = 11, percent = 10},
{type = "poison", decrease = 0, percent = 10},
{type = "laser", decrease = 5, percent = 10}},
Big_Spitter_Mk3 = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 7, percent = 5},
{type = "impact", decrease = 10, percent = 10},
{type = "explosion", decrease = 12, percent = 20},
{type = "acid", decrease = 12, percent = 10},
{type = "poison", decrease = 0, percent = 10},
{type = "laser", decrease = 10, percent = 10}},
Behemoth_Spitter = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 10, percent = 10},
{type = "impact", decrease = 15, percent = 15},
{type = "explosion", decrease = 15, percent = 30},
{type = "acid", decrease = 15, percent = 15},
{type = "poison", decrease = 0, percent = 15},
{type = "laser", decrease = 15, percent = 15}},
Spawner = {
{type = "fire", decrease = 0, percent = -25},
{type = "physical", decrease = 5, percent = 10},
{type = "impact", decrease = 15, percent = 15},
{type = "explosion", decrease = 15, percent = 30},
{type = "acid", decrease = 15, percent = 15},
{type = "poison", decrease = 0, percent = 15},
{type = "laser", decrease = 10, percent = 15}},
Fire = {
{type = "fire", decrease = 0, percent = 75}},
} | mit |
marktsai0316/nodemcu-firmware | lua_modules/hdc1000/HDC1000.lua | 79 | 2703 | -------------------------------------------------------
-- This library was written for the Texas Instruments
-- HDC1000 temperature and humidity sensor.
-- It should work for the HDC1008 too.
-- Written by Francesco Truzzi (francesco@truzzi.me)
-- Released under GNU GPL v2.0 license.
-------------------------------------------------------
-------------- NON-DEFAULT CONFIG VALUES --------------
------------- config() optional arguments -------------
-- HDC1000_HEAT_OFF 0x00 (heater)
-- HDC1000_TEMP_11BIT 0x40 (resolution)
-- HDC1000_HUMI_11BIT 0x01 (resolution)
-- HDC1000_HUMI_8BIT 0x20 (resolution)
-------------------------------------------------------
local modname = ...
local M = {}
_G[modname] = M
local id = 0
local i2c = i2c
local delay = 20000
local _drdyn_pin
local HDC1000_ADDR = 0x40
local HDC1000_TEMP = 0x00
local HDC1000_HUMI = 0x01
local HDC1000_CONFIG = 0x02
local HDC1000_HEAT_ON = 0x20
local HDC1000_TEMP_HUMI_14BIT = 0x00
-- reads 16bits from the sensor
local function read16()
i2c.start(id)
i2c.address(id, HDC1000_ADDR, i2c.RECEIVER)
data_temp = i2c.read(0, 2)
i2c.stop(id)
data = bit.lshift(string.byte(data_temp, 1, 1), 8) + string.byte(data_temp, 2, 2)
return data
end
-- sets the register to read next
local function setReadRegister(register)
i2c.start(id)
i2c.address(id, HDC1000_ADDR, i2c.TRANSMITTER)
i2c.write(id, register)
i2c.stop(id)
end
-- writes the 2 configuration bytes
local function writeConfig(config)
i2c.start(id)
i2c.address(id, HDC1000_ADDR, i2c.TRANSMITTER)
i2c.write(id, HDC1000_CONFIG, config, 0x00)
i2c.stop(id)
end
-- returns true if battery voltage is < 2.7V, false otherwise
function M.batteryDead()
setReadRegister(HDC1000_CONFIG)
return(bit.isset(read16(), 11))
end
-- initalize i2c
function M.init(sda, scl, drdyn_pin)
_drdyn_pin = drdyn_pin
i2c.setup(id, sda, scl, i2c.SLOW)
end
function M.config(addr, resolution, heater)
-- default values are set if the function is called with no arguments
HDC1000_ADDR = addr or HDC1000_ADDR
resolution = resolution or HDC1000_TEMP_HUMI_14BIT
heater = heater or HDC1000_HEAT_ON
writeConfig(bit.bor(resolution, heater))
end
-- outputs temperature in Celsius degrees
function M.getHumi()
setReadRegister(HDC1000_HUMI)
if(_drdyn_pin ~= false) then
gpio.mode(_drdyn_pin, gpio.INPUT)
while(gpio.read(_drdyn_pin)==1) do
end
else tmr.delay(delay) end
return(read16()/65535.0*100)
end
-- outputs humidity in %RH
function M.getTemp()
setReadRegister(HDC1000_TEMP)
if(_drdyn_pin ~= false) then
gpio.mode(_drdyn_pin, gpio.INPUT)
while(gpio.read(_drdyn_pin)==1) do
end
else tmr.delay(delay) end
return(read16()/65535.0*165-40)
end
return M
| mit |
Frenzie/koreader | frontend/apps/reader/modules/readerthumbnail.lua | 4 | 20848 | local Blitbuffer = require("ffi/blitbuffer")
local Cache = require("cache")
local Device = require("device")
local Geom = require("ui/geometry")
local Persist = require("persist")
local RenderImage = require("ui/renderimage")
local TileCacheItem = require("document/tilecacheitem")
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local Screen = Device.screen
local ffiutil = require("ffi/util")
local logger = require("logger")
local util = require("util")
local _ = require("gettext")
-- This ReaderThumbnail module provides a service for generating thumbnails
-- of book pages.
-- It handles launching via the menu or Dispatcher/Gestures two fullscreen
-- widgets related to showing pages and thumbnails that will make use of
-- its services: BookMap and PageBrowser.
local ReaderThumbnail = WidgetContainer:extend{}
function ReaderThumbnail:init()
if not Device:isTouchDevice() then
-- The BookMap and PageBrowser widgets depend too much on gestures,
-- making them work with keys would be hard and very limited, so
-- just don't make them available.
return
end
self.ui.menu:registerToMainMenu(self)
-- Use LuaJIT fast buffer.encode()/decode() when serializing BlitBuffer
-- for exchange between subprocess and parent.
self.codec = Persist.getCodec("luajit")
self:setupColor()
self.thumbnails_requests = {}
self.current_target_size_tag = nil
-- Ensure no multiple executions, and nextTick() the scheduleIn()
-- so we get a chance to process events in-between refreshes and
-- this can be interrupted (otherwise, something scheduleIn(0.1),
-- if a screen refresh is then done and taking longer than 0.1s,
-- would be executed immediately, without emptying any input event).
local schedule_step = 0
self._ensureTileGeneration_action = function(restart)
if restart then
UIManager:unschedule(self._ensureTileGeneration_action)
schedule_step = 0
end
if schedule_step == 0 then
schedule_step = 1
UIManager:nextTick(self._ensureTileGeneration_action)
elseif schedule_step == 1 then
schedule_step = 2
UIManager:scheduleIn(0.1, self._ensureTileGeneration_action)
else
schedule_step = 0
self:ensureTileGeneration()
end
end
end
function ReaderThumbnail:addToMainMenu(menu_items)
menu_items.book_map = {
text = _("Book map"),
callback = function()
self:onShowBookMap()
end,
}
menu_items.page_browser = {
text = _("Page browser"),
callback = function()
self:onShowPageBrowser()
end,
}
end
function ReaderThumbnail:onShowBookMap()
local BookMapWidget = require("ui/widget/bookmapwidget")
UIManager:show(BookMapWidget:new{
ui = self.ui,
})
return true
end
function ReaderThumbnail:onShowPageBrowser()
local PageBrowserWidget = require("ui/widget/pagebrowserwidget")
UIManager:show(PageBrowserWidget:new{
ui = self.ui,
})
return true
end
-- This is made a module local so we can keep track of pids
-- to collect across multiple Reader instantiations
local pids_to_collect = {}
function ReaderThumbnail:collectPids()
if #pids_to_collect == 0 then
return false
end
for i=#pids_to_collect, 1, -1 do
if ffiutil.isSubProcessDone(pids_to_collect[i]) then
table.remove(pids_to_collect, i)
end
end
return #pids_to_collect > 0
end
function ReaderThumbnail:setupColor()
self.bb_type = self.ui.document.render_color and self.ui.document.color_bb_type or Blitbuffer.TYPE_BB8
end
function ReaderThumbnail:setupCache()
if not self.tile_cache then
-- We want to allow browsing at least N pages worth of thumbnails
-- without cache trashing. A little more than N pages (because inter
-- thumbnail margins) will fit in N * screen size.
-- With N=5, this should use from 5 to 15 Mb on a classic eInk device.
local N = 5
local max_bytes = math.ceil(N * Screen:getWidth() * Screen:getHeight() * Blitbuffer.TYPE_TO_BPP[self.bb_type] / 8)
-- We don't really care about limiting any number of slots, so allow
-- for at least 5 pages of 10x10 tiles
local avg_itemsize = math.ceil(max_bytes * (1/500))
self.tile_cache = Cache:new{
size = max_bytes,
avg_itemsize = avg_itemsize, -- will make slots=500
enable_eviction_cb = true,
}
end
end
function ReaderThumbnail:logCacheSize()
logger.info(string.format("Thumbnails cache: %d/%d (%s/%s)",
self.tile_cache.cache.used_slots(),
self.tile_cache.slots,
util.getFriendlySize(self.tile_cache.cache.used_size()),
util.getFriendlySize(self.tile_cache.size)))
end
function ReaderThumbnail:resetCache()
if self.tile_cache then
self.tile_cache:clear()
self.tile_cache = nil
end
end
function ReaderThumbnail:removeFromCache(hash_subs, remove_only_non_matching)
-- Remove from cache all tiles matching any hash from hash_subs.
-- IF only_non_matching=true, keep those matching and remove all others.
if not self.tile_cache then
return
end
if type(hash_subs) ~= "table" then
hash_subs = { hash_subs }
end
local nb_removed, size_removed = 0, 0
local to_remove = {}
for thash, tile in self.tile_cache.cache:pairs() do
local remove = remove_only_non_matching
for _, h in ipairs(hash_subs) do
if thash:find(h, 1, true) then -- plain text match (no pattern needed)
remove = not remove
break
end
end
if remove then
to_remove[thash] = true
nb_removed = nb_removed + 1
size_removed = size_removed + tile.size
end
end
for thash, _ in pairs(to_remove) do
self.tile_cache.cache:delete(thash)
logger.dbg("removed cached thumbnail", thash)
end
return nb_removed, size_removed
end
function ReaderThumbnail:resetCachedPagesForBookmarks(...)
-- Multiple bookmarks may be provided
local start_page, end_page
for i = 1, select("#", ...) do
local bm = select(i, ...)
if self.ui.rolling then
-- Look at all properties that may be xpointers
for _, k in ipairs({"page", "pos0", "pos1"}) do
if bm[k] and type(bm[k]) == "string" then
local p = self.ui.document:getPageFromXPointer(bm[k])
if not start_page or p < start_page then
start_page = p
end
if not end_page or p > end_page then
end_page = p
end
end
end
else
if bm.page and type(bm.page) == "number" then
local p = bm.page
if not start_page or p < start_page then
start_page = p
end
if not end_page or p > end_page then
end_page = p
end
end
end
end
if start_page and end_page then
local hash_subs_to_remove = {}
for p=start_page, end_page do
table.insert(hash_subs_to_remove, string.format("p%d-", p))
end
self:removeFromCache(hash_subs_to_remove)
end
end
function ReaderThumbnail:tidyCache()
if self.current_target_size_tag then
-- Remove all thumbnails generated for an older target size
self:removeFromCache("-"..self.current_target_size_tag, true)
end
end
function ReaderThumbnail:cancelPageThumbnailRequests(batch_id)
if batch_id then
self.thumbnails_requests[batch_id] = nil
else
self.thumbnails_requests = {}
end
if self.req_in_progress and (not batch_id or self.req_in_progress.batch_id == batch_id) then
-- Kill any reference to the module cancelling it
self.req_in_progress.when_generated_callback = nil
end
end
function ReaderThumbnail:getPageThumbnail(page, width, height, batch_id, when_generated_callback)
self:setupCache()
self.current_target_size_tag = string.format("w%d_h%d", width, height)
local hash = string.format("p%d-%s", page, self.current_target_size_tag)
local tile = self.tile_cache and self.tile_cache:check(hash)
if tile then
-- Cached: call callback and we're done.
when_generated_callback(tile, batch_id, false)
return false -- not delayed
end
if not self.thumbnails_requests[batch_id] then
self.thumbnails_requests[batch_id] = {}
end
table.insert(self.thumbnails_requests[batch_id], {
batch_id = batch_id,
hash = hash,
page = page,
width = width,
height = height,
when_generated_callback = when_generated_callback,
})
-- Start tile generation, avoid multiple ones
self._ensureTileGeneration_action(true)
return true -- delayed
end
function ReaderThumbnail:ensureTileGeneration()
local has_pids_still_to_collect = self:collectPids()
local still_in_progress = false
if self.req_in_progress then
local pid_still_to_collect
still_in_progress, pid_still_to_collect = self:checkTileGeneration(self.req_in_progress)
if pid_still_to_collect then
has_pids_still_to_collect = true
end
end
if not still_in_progress then
self.req_in_progress = nil
while true do
local req_id, requests = next(self.thumbnails_requests)
if not req_id then -- no more requests
break
end
local req = table.remove(requests, 1)
if #requests == 0 then
self.thumbnails_requests[req_id] = nil
end
if req.when_generated_callback then -- not cancelled since queued
-- It might have been generated and cached by a previous batch
local tile = self.tile_cache and self.tile_cache:check(req.hash)
if tile then
req.when_generated_callback(tile, req.batch_id, true)
else
if self:startTileGeneration(req) then
self.req_in_progress = req
break
else
-- Failure starting it: let requester know in case it cares, and forget it
req.when_generated_callback(nil, req.batch_id, true)
end
end
end
end
end
if self.req_in_progress or has_pids_still_to_collect or next(self.thumbnails_requests) then
self._ensureTileGeneration_action()
end
end
function ReaderThumbnail:startTileGeneration(request)
local pid, parent_read_fd = ffiutil.runInSubProcess(function(pid, child_write_fd)
-- Get page image as if drawn on the screen
local bb = self:_getPageImage(request.page)
-- Scale it to fit in the requested size
local scale_factor = math.min(request.width / bb:getWidth(), request.height / bb:getHeight())
local target_w = math.floor(bb:getWidth() * scale_factor)
local target_h = math.floor(bb:getHeight() * scale_factor)
-- local time = require("ui/time")
-- local start_time = time.now()
local tile = TileCacheItem:new{
bb = RenderImage:scaleBlitBuffer(bb, target_w, target_h, true),
pageno = request.page,
}
tile.size = tonumber(tile.bb.stride) * tile.bb.h
-- logger.info("tile size", tile.bb.w, tile.bb.h, "=>", tile.size)
-- logger.info(string.format(" scaling took %.3f seconds, %d bpp", time.to_s(time.since(start_time)), tile.bb:getBpp()))
-- bb:free() -- no need to spend time freeing, we're dying soon anyway!
ffiutil.writeToFD(child_write_fd, self.codec.serialize(tile:totable()), true)
end, true) -- with_pipe = true
if pid then
-- Store these in the request object itself
request.pid = pid
request.parent_read_fd = parent_read_fd
return true
end
logger.warn("PageBrowserWidget thumbnail start failure:", parent_read_fd)
return false
end
function ReaderThumbnail:checkTileGeneration(request)
local pid, parent_read_fd = request.pid, request.parent_read_fd
local stuff_to_read = ffiutil.getNonBlockingReadSize(parent_read_fd) ~= 0
local subprocess_done = ffiutil.isSubProcessDone(pid)
logger.dbg("subprocess_done:", subprocess_done, " stuff_to_read:", stuff_to_read)
if stuff_to_read then
-- local time = require("ui/time")
-- local start_time = time.now()
local result, err = self.codec.deserialize(ffiutil.readAllFromFD(parent_read_fd))
if result then
local tile = TileCacheItem:new{}
tile:fromtable(result)
if self.tile_cache then
self.tile_cache:insert(request.hash, tile)
end
if request.when_generated_callback then -- not cancelled
request.when_generated_callback(tile, request.batch_id, true)
end
else
logger.warn("PageBrowserWidget thumbnail deserialize() failed:", err)
if request.when_generated_callback then -- not cancelled
request.when_generated_callback(nil, request.batch_id, true)
end
end
-- logger.info(string.format(" parsing result from subprocess took %.3f seconds", time.to_s(time.since(start_time))))
if not subprocess_done then
table.insert(pids_to_collect, pid)
return false, true
end
return false
elseif subprocess_done then
-- subprocess_done: process exited with no output
ffiutil.readAllFromFD(parent_read_fd) -- close our fd
return false
end
logger.dbg("process not yet done, will check again soon")
return true
end
function ReaderThumbnail:_getPageImage(page)
-- This is run in a subprocess: we can tweak all document settings
-- to get an adequate image of the page.
-- No need to worry about the final state of things: this subprocess
-- will die just after drawing the page, and all will be forgotten,
-- without impact on the parent process.
-- Be sure to limit our impact on the disk-saved book state
self.ui.saveSettings = function() end -- Be sure nothing is flushed
self.ui.statistics = nil -- Don't update statistics for pages we visit
-- By default, our target page size is the current screen size
local target_w, target_h = Screen:getWidth(), Screen:getHeight()
-- This was all mostly chosen by experimenting.
-- Be sure to call the innermost methods enough to get what we want, and
-- not upper event handlers that may trigger other unneeded events and stuff.
-- Especially, be sure to not trigger any paint on the screen buffer, or
-- any processing of input events.
-- No need to worry about UIManager:scheduleIn() or :nextTick(), as
-- we will die before the callback gets a chance to be run.
-- Common to ReaderRolling and ReaderPaging
self.ui.view.footer_visible = false -- We want no footer on page image
if self.ui.view.highlight.lighten_factor < 0.3 then
self.ui.view.highlight.lighten_factor = 0.3 -- make lighten highlight a bit darker
end
if self.ui.rolling then
-- CRE documents: pages all have the aspect ratio of our screen (alt top status bar
-- will be croped out after drawing), we will show them just as rendered.
self.ui.view:onSetViewMode("page") -- Get out of scroll mode
if self.ui.font.gamma_index < 30 then -- Increase font gamma (if not already increased),
self.ui.document:setGammaIndex(30) -- as downscaling will make text grayer
end
self.ui.document:setImageScaling(false) -- No need for smooth scaling as all will be downscaled
self.ui.document:setNightmodeImages(false) -- We don't invert page images even if nightmode set: keep images as-is
self.ui.view.state.page = page -- Be on requested page
self.ui.document:gotoPage(page) -- Current xpointer needs to be updated for some of what follows
self.ui.bookmark:onPageUpdate(page) -- Update dogear state for this page
self.ui.pagemap:onPageUpdate(page) -- Update pagemap labels for this page
end
if self.ui.paging then
-- With PDF/DJVU/Pics, we will show the native page (no reflow, no crop, no zoom
-- to columns...). This makes thumbnail generation faster, and will allow the user
-- to get an overview of the book native pages to better decide which option will
-- be best to use for the book.
-- We also want to get a thumbnail with the aspect ratio of the native page
-- (so we don't get a native landscape page smallish and centered with blank above
-- and below in a portrait thumbnail, if the screen is in portrait mode).
self.ui.view.hinting = false -- Disable hinting
self.ui.view.page_scroll = false -- Get out of scroll mode
self.ui.view.flipping_visible = false -- No page flipping icon
self.ui.document.configurable.text_wrap = false -- Get out of reflow mode
self.ui.document.configurable.trim_page = 3 -- Page crop: none
-- self.ui.document.configurable.trim_page = 1 -- Page crop: auto (very slower)
self.ui.document.configurable.auto_straighten = 0 -- No auto straighten
-- We can let dewatermark if the user has enabled it, it helps
-- limiting annoying eInk refreshes of light gray areas
-- self.ui.document.configurable.page_opt = 0 -- No dewatermark
-- We won't touch the contrast (to try making text less gray), as it applies on
-- images that could get too dark.
-- Get native page dimensions, and update our target bb dimensions so it gets the
-- same aspect ratio (we don't use native dimensions as is, as they may get huge)
local dimen = self.ui.document:getPageDimensions(page, 1, 0)
local scale_factor = math.min(target_w / dimen.w, target_h / dimen.h)
target_w = math.floor(dimen.w * scale_factor)
target_h = math.floor(dimen.h * scale_factor)
dimen = Geom:new{ w=target_w, h=target_h }
-- logger.info("getPageImage", page, dimen, "=>", target_w, target_h, scale_factor)
-- This seems to do it all well:
-- local Event = require("ui/event")
-- self.ui:handleEvent(Event:new("SetDimensions", dimen))
-- self.ui.view.dogear[1].dimen.w = dimen.w -- (hack... its code uses the Screen width)
-- self.ui:handleEvent(Event:new("PageUpdate", page))
-- self.ui:handleEvent(Event:new("SetZoomMode", "page"))
-- Trying to do as little as needed, knowing the internals:
self.ui.view:onSetDimensions(dimen)
self.ui.view:onBBoxUpdate(nil) -- drop any bbox, draw native page
self.ui.view.state.page = page
self.ui.view.state.zoom = scale_factor
self.ui.view.state.rotation = 0
self.ui.view:recalculate()
self.ui.view.dogear[1].dimen.w = dimen.w -- (hack... its code uses the Screen width)
self.ui.bookmark:onPageUpdate(page) -- Update dogear state for this page
end
-- Draw the page on a new BB with the targetted size
local bb = Blitbuffer.new(target_w, target_h, self.bb_type)
self.ui.view:paintTo(bb, 0, 0)
if self.ui.rolling then
-- Crop out the top alt status bar if enabled
local header_height = self.ui.document:getHeaderHeight()
if header_height > 0 then
bb = bb:viewport(0, header_height, bb.w, bb.h - header_height)
end
end
return bb
end
function ReaderThumbnail:onCloseDocument()
self:cancelPageThumbnailRequests()
if self.tile_cache then
self:logCacheSize()
self.tile_cache:clear()
self.tile_cache = nil
end
end
function ReaderThumbnail:onColorRenderingUpdate()
self:setupColor()
self:resetCache()
end
-- CRE: emitted after a re-rendering
ReaderThumbnail.onDocumentRerendered = ReaderThumbnail.resetCache
-- Emitted When adding/removing/updating bookmarks and highlights
ReaderThumbnail.onBookmarkAdded = ReaderThumbnail.resetCachedPagesForBookmarks
ReaderThumbnail.onBookmarkRemoved = ReaderThumbnail.resetCachedPagesForBookmarks
ReaderThumbnail.onBookmarkUpdated = ReaderThumbnail.resetCachedPagesForBookmarks
return ReaderThumbnail
| agpl-3.0 |
Lsty/ygopro-scripts | c46448938.lua | 3 | 2758 | --魔導書の神判
function c46448938.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,46448938+EFFECT_COUNT_CODE_OATH)
e1:SetOperation(c46448938.activate)
c:RegisterEffect(e1)
end
function c46448938.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(c46448938.regcon)
e1:SetOperation(c46448938.regop1)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_CHAIN_NEGATED)
e2:SetCondition(c46448938.regcon)
e2:SetOperation(c46448938.regop2)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_PHASE+PHASE_END)
e3:SetCountLimit(1)
e3:SetCondition(c46448938.effcon)
e3:SetOperation(c46448938.effop)
e3:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e3,tp)
e1:SetLabelObject(e3)
e2:SetLabelObject(e3)
end
function c46448938.regcon(e,tp,eg,ep,ev,re,r,rp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsActiveType(TYPE_SPELL)
end
function c46448938.regop1(e,tp,eg,ep,ev,re,r,rp)
local ct=e:GetLabelObject():GetLabel()
e:GetLabelObject():SetLabel(ct+1)
end
function c46448938.regop2(e,tp,eg,ep,ev,re,r,rp)
local ct=e:GetLabelObject():GetLabel()
if ct==0 then ct=1 end
e:GetLabelObject():SetLabel(ct-1)
end
function c46448938.effcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetLabel()>0
end
function c46448938.sfilter(c)
return c:IsSetCard(0x106e) and c:GetCode()~=46448938 and c:IsType(TYPE_SPELL) and c:IsAbleToHand()
end
function c46448938.spfilter(c,lv,e,tp)
return c:IsLevelBelow(lv) and c:IsRace(RACE_SPELLCASTER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c46448938.effop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_CARD,0,46448938)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c46448938.sfilter,tp,LOCATION_DECK,0,1,e:GetLabel(),nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c46448938.spfilter,tp,LOCATION_DECK,0,1,nil,g:GetCount(),e,tp)
and Duel.SelectYesNo(tp,aux.Stringid(46448938,1)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=Duel.SelectMatchingCard(tp,c46448938.spfilter,tp,LOCATION_DECK,0,1,1,nil,g:GetCount(),e,tp)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c62070231.lua | 5 | 1888 | --No.94 極氷姫クリスタル・ゼロ
function c62070231.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_WATER),5,2)
c:EnableReviveLimit()
--atk down
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(62070231,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_MZONE)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c62070231.condition)
e1:SetCost(c62070231.cost)
e1:SetTarget(c62070231.target)
e1:SetOperation(c62070231.operation)
c:RegisterEffect(e1)
end
c62070231.xyz_number=94
function c62070231.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c62070231.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c62070231.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c62070231.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(tc:GetAttack()/2)
if Duel.GetTurnPlayer()~=tp then
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,2)
else
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,1)
end
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/weaponskills/garland_of_bliss.lua | 10 | 1974 | -----------------------------------
-- Garland Of Bliss
-- Staff weapon skill
-- Skill level: N/A
-- Lowers target's defense. Duration of effect varies with TP. Nirvana: Aftermath effect varies with TP.
-- Reduces enemy's defense by 12.5%.
-- Available only after completing the Unlocking a Myth (Summoner) quest.
-- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget.
-- Aligned with the Flame Belt, Light Belt & Aqua Belt.
-- Element: Light
-- Modifiers: MND:40%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/magic")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.ftp100 = 2 params.ftp200 = 2 params.ftp300 = 2
params.str_wsc = 0.0 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0
params.mnd_wsc = 0.4 params.chr_wsc = 0.0
params.ele = dsp.magic.ele.LIGHT
params.skill = dsp.skill.STAFF
params.includemab = true
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp100 = 2.25 params.ftp200 = 2.25 params.ftp300 = 2.25
params.str_wsc = 0.3 params.mnd_wsc = 0.7
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary)
if damage > 0 then
if not target:hasStatusEffect(dsp.effect.DEFENSE_DOWN) then
local duration = (30 + tp / 1000 * 30) * applyResistanceAddEffect(player, target, dsp.magic.ele.WIND, 0)
target:addStatusEffect(dsp.effect.DEFENSE_DOWN, 12.5, 0, duration)
end
-- Apply Aftermath
dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.MYTHIC)
end
return tpHits, extraHits, criticalHit, damage
end | gpl-3.0 |
Lsty/ygopro-scripts | c13317419.lua | 3 | 3773 | --ロケットハンド
function c13317419.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCountLimit(1,13317419)
e1:SetCondition(c13317419.condition)
e1:SetTarget(c13317419.target)
e1:SetOperation(c13317419.operation)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DESTROY+CATEGORY_ATKCHANGE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_SZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,13317419)
e2:SetCondition(c13317419.descon)
e2:SetCost(c13317419.descost)
e2:SetTarget(c13317419.destg)
e2:SetOperation(c13317419.desop)
c:RegisterEffect(e2)
end
function c13317419.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c13317419.filter(c)
return c:IsPosition(POS_FACEUP_ATTACK) and c:IsAttackAbove(800)
end
function c13317419.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c13317419.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c13317419.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c13317419.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c13317419.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsLocation(LOCATION_SZONE) then return end
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() and tc:IsControler(tp) then
Duel.Equip(tp,c,tc)
c:CancelToGrave()
--Atkup
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_EQUIP)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(800)
e1:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e1)
--Equip limit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_EQUIP_LIMIT)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetValue(1)
e2:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e2)
end
end
function c13317419.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetEquipTarget()
end
function c13317419.descost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end
e:SetLabelObject(e:GetHandler():GetEquipTarget())
Duel.SendtoGrave(e:GetHandler(),REASON_COST)
end
function c13317419.desfilter(c)
return c:IsFaceup() and c:IsDestructable()
end
function c13317419.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and c13317419.desfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c13317419.desfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c13317419.desfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c13317419.desop(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetLabelObject()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)~=0
and ec and ec:IsFaceup() and ec:IsLocation(LOCATION_MZONE) then
Duel.BreakEffect()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(0)
e1:SetReset(RESET_EVENT+0x1fe0000)
ec:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_CHANGE_POSITION)
e2:SetReset(RESET_EVENT+0x1fe0000)
ec:RegisterEffect(e2)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c91279700.lua | 3 | 1721 | --ヴェルズ・オピオン
function c91279700.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0xa),4,2)
c:EnableReviveLimit()
--disable spsummon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,1)
e1:SetTarget(c91279700.sumlimit)
e1:SetCondition(c91279700.dscon)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(91279700,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetCountLimit(1)
e2:SetRange(LOCATION_MZONE)
e2:SetCost(c91279700.cost)
e2:SetTarget(c91279700.target)
e2:SetOperation(c91279700.operation)
c:RegisterEffect(e2)
end
function c91279700.dscon(e)
return e:GetHandler():GetOverlayCount()~=0
end
function c91279700.sumlimit(e,c,sump,sumtype,sumpos,targetp)
return c:IsLevelAbove(5)
end
function c91279700.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c91279700.filter(c)
return c:IsSetCard(0x65) and c:IsAbleToHand()
end
function c91279700.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c91279700.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c91279700.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c91279700.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
TheOneZealot/MelsomDarkRP | lua/darkrp_customthings/jobs.lua | 1 | 2027 | /*---------------------------------------------------------------------------
DarkRP custom jobs
---------------------------------------------------------------------------
This file contains your custom jobs.
This file should also contain jobs from DarkRP that you edited.
Note: If you want to edit a default DarkRP job, first disable it in darkrp_config/disabled_defaults.lua
Once you've done that, copy and paste the job to this file and edit it.
The default jobs can be found here:
https://github.com/FPtje/DarkRP/blob/master/gamemode/config/jobrelated.lua
For examples and explanation please visit this wiki page:
http://wiki.darkrp.com/index.php/DarkRP:CustomJobFields
Add jobs under the following line:
---------------------------------------------------------------------------*/
TEAM_ENGINEER = DarkRP.createJob("Engineer", {
color = Color(80, 5, 255, 0),
model = "models/player/swat.mdl",
description = [[Description.]],
weapons = {},
command = "engi",
max = 1,
salary = 25,
admin = 0,
vote = true,
hasLicense = true,
})
/*---------------------------------------------------------------------------
Define which team joining players spawn into and what team you change to if demoted
---------------------------------------------------------------------------*/
GAMEMODE.DefaultTeam = TEAM_CITIZEN
/*---------------------------------------------------------------------------
Define which teams belong to civil protection
Civil protection can set warrants, make people wanted and do some other police related things
---------------------------------------------------------------------------*/
GAMEMODE.CivilProtection = {
[TEAM_POLICE] = true,
[TEAM_CHIEF] = true,
[TEAM_MAYOR] = true,
}
/*---------------------------------------------------------------------------
Jobs that are hitmen (enables the hitman menu)
---------------------------------------------------------------------------*/
DarkRP.addHitmanTeam(TEAM_MOB)
| mit |
Lsty/ygopro-scripts | c11021521.lua | 7 | 1131 | --ネコマネキング
function c11021521.initial_effect(c)
--end turn
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(11021521,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c11021521.condition)
e1:SetOperation(c11021521.operation)
c:RegisterEffect(e1)
end
function c11021521.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return Duel.GetTurnPlayer()~=tp and c:GetPreviousControler()==tp
and c:IsReason(REASON_EFFECT) and c:GetReasonPlayer()==1-tp
end
function c11021521.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.SkipPhase(1-tp,PHASE_DRAW,RESET_PHASE+PHASE_END,1)
Duel.SkipPhase(1-tp,PHASE_STANDBY,RESET_PHASE+PHASE_END,1)
Duel.SkipPhase(1-tp,PHASE_MAIN1,RESET_PHASE+PHASE_END,1)
Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_END,1,1)
Duel.SkipPhase(1-tp,PHASE_MAIN2,RESET_PHASE+PHASE_END,1)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_BP)
e1:SetTargetRange(0,1)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Kazham/npcs/Thali_Mhobrum.lua | 9 | 1057 | -----------------------------------
-- Area: Kazham
-- NPC: Thali Mhobrum
-- Standard Info NPC
-----------------------------------
local path =
{
55.816410, -11.000000, -43.992680,
54.761787, -11.000000, -44.046181,
51.805824, -11.000000, -44.200321,
52.922001, -11.000000, -44.186420,
51.890709, -11.000000, -44.224312,
47.689358, -11.000000, -44.374969,
52.826096, -11.000000, -44.191029,
47.709465, -11.000000, -44.374393,
52.782181, -11.000000, -44.192482,
47.469643, -11.000000, -44.383091
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(dsp.path.first(path));
onPath(npc);
end;
function onPath(npc)
dsp.path.patrol(npc, path);
end;
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getCharVar("BathedInScent") == 1) then
player:startEvent(163); -- scent from Blue Rafflesias
npc:wait();
else
player:startEvent(190);
npc:wait();
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option,npc)
npc:wait(0);
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c57019473.lua | 5 | 1641 | --ONeサンダー
function c57019473.initial_effect(c)
--remove
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(57019473,0))
e1:SetCategory(CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c57019473.rmtg)
e1:SetOperation(c57019473.rmop)
c:RegisterEffect(e1)
end
function c57019473.filter(c)
return c:IsRace(RACE_THUNDER) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:GetLevel()==4
and c:GetCode()~=57019473 and c:IsAttackBelow(1600) and c:IsAbleToRemove()
end
function c57019473.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c57019473.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c57019473.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c57019473.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,HINTMSG_REMOVE,g,1,0,0)
end
function c57019473.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)>0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetRange(LOCATION_REMOVED)
e1:SetCountLimit(1)
e1:SetOperation(c57019473.thop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
function c57019473.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.SendtoHand(e:GetHandler(),nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,e:GetHandler())
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/weaponskills/thunder_thrust.lua | 10 | 1302 | -----------------------------------
-- Thunder Thrust
-- Polearm weapon skill
-- Skill Level: 30
-- Deals lightning elemental damage to enemy. Damage varies with TP.
-- Aligned with the Light Gorget & Thunder Gorget.
-- Aligned with the Light Belt & Thunder Belt.
-- Element: Lightning
-- Modifiers: STR:40% INT:40%
-- 100%TP 200%TP 300%TP
-- 1.50 2.00 2.50
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.ftp100 = 1.5 params.ftp200 = 2 params.ftp300 = 2.5
params.str_wsc = 0.2 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.2 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.ele = dsp.magic.ele.LIGHTNING
params.skill = dsp.skill.POLEARM
params.includemab = true
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4 params.int_wsc = 0.4
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
Lsty/ygopro-scripts | c9059700.lua | 3 | 1228 | --インフェルニティ・バリア
function c9059700.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(c9059700.condition)
e1:SetTarget(c9059700.target)
e1:SetOperation(c9059700.activate)
c:RegisterEffect(e1)
end
function c9059700.cfilter(c)
return c:IsPosition(POS_FACEUP_ATTACK) and c:IsSetCard(0xb)
end
function c9059700.condition(e,tp,eg,ep,ev,re,r,rp)
if ep==tp or not Duel.IsExistingMatchingCard(c9059700.cfilter,tp,LOCATION_MZONE,0,1,nil)
or Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)~=0 then return false end
return Duel.IsChainNegatable(ev) and (re:IsActiveType(TYPE_MONSTER) or re:IsHasType(EFFECT_TYPE_ACTIVATE))
end
function c9059700.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c9059700.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/items/cutlet_sandwich.lua | 11 | 1449 | -----------------------------------------
-- ID: 6396
-- Item: cutlet_sandwich
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +40
-- STR +7
-- INT -7
-- Fire resistance +20
-- Attack +20% (cap 120)
-- Ranged Attack +20% (cap 120)
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,6396)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 40)
target:addMod(dsp.mod.STR, 7)
target:addMod(dsp.mod.INT, -7)
target:addMod(dsp.mod.FIRERES, 20)
target:addMod(dsp.mod.FOOD_ATTP, 20)
target:addMod(dsp.mod.FOOD_ATT_CAP, 120)
target:addMod(dsp.mod.FOOD_RATTP, 20)
target:addMod(dsp.mod.FOOD_RATT_CAP, 120)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 40)
target:delMod(dsp.mod.STR, 7)
target:delMod(dsp.mod.INT, -7)
target:delMod(dsp.mod.FIRERES, 20)
target:delMod(dsp.mod.FOOD_ATTP, 20)
target:delMod(dsp.mod.FOOD_ATT_CAP, 120)
target:delMod(dsp.mod.FOOD_RATTP, 20)
target:delMod(dsp.mod.FOOD_RATT_CAP, 120)
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/mobskills/freezebite.lua | 10 | 1377 | -----------------------------------
-- Freezebite
-- Great Sword weapon skill
-- Skill Level: 100
-- Delivers an ice elemental attack. Damage varies with TP.
-- Aligned with the Snow Gorget & Breeze Gorget.
-- Aligned with the Snow Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: STR:30% INT:20%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 3.00
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
require("scripts/globals/monstertpmoves")
-----------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local params = {}
params.numHits = 1
params.ftp100 = 1 params.ftp200 = 1.5 params.ftp300 = 3
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.2 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1 params.atk200 = 1 params.atk300 = 1
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(mob, target, 0, params, 0, nil, true, nil)
target:takeDamage(damage, mob, dsp.attackType.MAGICAL, dsp.damageType.ICE)
return damage
end
| gpl-3.0 |
ara8586/9900 | libs/feedparser.lua | 543 | 11955 | local LOM = assert(require("lxp.lom"), "LuaExpat doesn't seem to be installed. feedparser kind of needs it to work...")
local XMLElement = (loadfile "./libs/XMLElement.lua")()
local dateparser = (loadfile "./libs/dateparser.lua")()
local URL = (loadfile "./libs/url.lua")()
local tinsert, tremove, tconcat = table.insert, table.remove, table.concat
local pairs, ipairs = pairs, ipairs
--- feedparser, similar to the Universal Feed Parser for python, but a good deal weaker.
-- see http://feedparser.org for details about the Universal Feed Parser
local feedparser= {
_DESCRIPTION = "RSS and Atom feed parser",
_VERSION = "feedparser 0.71"
}
local blanky = XMLElement.new() --useful in a whole bunch of places
local function resolve(url, base_url)
return URL.absolute(base_url, url)
end
local function rebase(el, base_uri)
local xml_base = el:getAttr('xml:base')
if not xml_base then return base_uri end
return resolve(xml_base, base_uri)
end
local function parse_entries(entries_el, format_str, base)
local entries = {}
for i, entry_el in ipairs(entries_el) do
local entry = {enclosures={}, links={}, contributors={}}
local entry_base = rebase(entry_el, base)
for i, el in ipairs(entry_el:getChildren('*')) do
local tag = el:getTag()
local el_base = rebase(el, entry_base)
--title
if tag == 'title' or tag == 'dc:title' or tag =='rdf:title' then --'dc:title' doesn't occur in atom feeds, but whatever.
entry.title=el:getText()
--link(s)
elseif format_str == 'rss' and tag=='link' then
entry.link=resolve(el:getText(), el_base)
tinsert(entry.links, {href=entry.link})
elseif (format_str=='atom' and tag == 'link') or
(format_str == 'rss' and tag=='atom:link') then
local link = {}
for i, attr in ipairs{'rel','type', 'href','title'} do
link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) --uri
end
tinsert(entry.links, link)
if link.rel=='enclosure' then
tinsert(entry.enclosures, {
href=link.href,
length=el:getAttr('length'),
type=el:getAttr('type')
})
end
--rss enclosures
elseif format_str == 'rss' and tag=='enclosure' then
tinsert(entry.enclosures, {
url=el:getAttr('url'),
length=el:getAttr('length'),
type=el:getAttr('type')
})
--summary
elseif (format_str=='atom' and tag=='summary') or
(format_str=='rss' and(tag=='description' or tag=='dc:description' or tag=='rdf:description')) then
entry.summary=el:getText()
--TODO: summary_detail
--content
elseif (format_str=='atom' and tag=='content') or
(format_str=='rss' and (tag=='body' or tag=='xhtml:body' or tag == 'fullitem' or tag=='content:encoded')) then
entry.content=el:getText()
--TODO: content_detail
--published
elseif (format_str == 'atom' and (tag=='published' or tag=='issued')) or
(format_str == 'rss' and (tag=='dcterms:issued' or tag=='atom:published' or tag=='atom:issued')) then
entry.published = el:getText()
entry.published_parsed=dateparser.parse(entry.published)
--updated
elseif (format_str=='atom' and (tag=='updated' or tag=='modified')) or
(format_str=='rss' and (tag=='dc:date' or tag=='pubDate' or tag=='dcterms:modified')) then
entry.updated=el:getText()
entry.updated_parsed=dateparser.parse(entry.updated)
elseif tag=='created' or tag=='atom:created' or tag=='dcterms:created' then
entry.created=el:getText()
entry.created_parsed=dateparser.parse(entry.created)
--id
elseif (format_str =='atom' and tag=='id') or
(format_str=='rss' and tag=='guid') then
entry.id=resolve(el:getText(), el_base) -- this is a uri, right?...
--author
elseif format_str=='rss' and (tag=='author' or tag=='dc:creator') then --author tag should give the author's email. should I respect this?
entry.author=(el:getChild('name') or el):getText()
entry.author_detail={
name=entry.author
}
elseif format_str=='atom' and tag=='author' then
entry.author=(el:getChild('name') or el):getText()
entry.author_detail = {
name=entry.author,
email=(el:getChild('email') or blanky):getText()
}
local author_url = (el:getChild('url') or blanky):getText()
if author_url and author_url ~= "" then entry.author_detail.href=resolve(author_url, rebase(el:getChild('url'), el_base)) end
elseif tag=='category' or tag=='dc:subject' then
--todo
elseif tag=='source' then
--todo
end
end
--wrap up rss guid
if format_str == 'rss' and (not entry.id) and entry_el:getAttr('rdf:about') then
entry.id=resolve(entry_el:getAttr('rdf:about'), entry_base) --uri
end
--wrap up entry.link
for i, link in pairs(entry.links) do
if link.rel=="alternate" or (not link.rel) or link.rel=="" then
entry.link=link.href --already resolved.
break
end
end
if not entry.link and format_str=='rss' then
entry.link=entry.id
end
tinsert(entries, entry)
end
return entries
end
local function atom_person_construct(person_el, base_uri)
local dude ={
name= (person_el:getChild('name') or blanky):getText(),
email=(person_el:getChild('email') or blanky):getText()
}
local url_el = person_el:getChild('url')
if url_el then dude.href=resolve(url_el:getText(), rebase(url_el, base_uri)) end
return dude
end
local function parse_atom(root, base_uri)
local res = {}
local feed = {
links = {},
contributors={},
language = root:getAttr('lang') or root:getAttr('xml:lang')
}
local root_base = rebase(root, base_uri)
res.feed=feed
res.format='atom'
local version=(root:getAttr('version') or ''):lower()
if version=="1.0" or root:getAttr('xmlns')=='http://www.w3.org/2005/Atom' then res.version='atom10'
elseif version=="0.3" then res.version='atom03'
else res.version='atom' end
for i, el in ipairs(root:getChildren('*')) do
local tag = el:getTag()
local el_base=rebase(el, root_base)
if tag == 'title' or tag == 'dc:title' or tag == 'atom10:title' or tag == 'atom03:title' then
feed.title=el:getText() --sanitize!
--todo: feed.title_detail
--link stuff
elseif tag=='link' then
local link = {}
for i, attr in ipairs{'rel','type', 'href','title'} do
link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr)
end
tinsert(feed.links, link)
--subtitle
elseif tag == 'subtitle' then
feed.subtitle=el:getText() --sanitize!
elseif not feed.subtitle and (tag == 'tagline' or tag =='atom03:tagline' or tag=='dc:description') then
feed.subtitle=el:getText() --sanitize!
--rights
elseif tag == 'copyright' or tag == 'rights' then
feed.rights=el:getText() --sanitize!
--generator
elseif tag == 'generator' then
feed.generator=el:getText() --sanitize!
elseif tag == 'admin:generatorAgent' then
feed.generator = feed.generator or el:getAttr('rdf:resource')
--info
elseif tag == 'info' then --whatever, nobody cared, anyway.
feed.info = el:getText()
--id
elseif tag=='id' then
feed.id=resolve(el:getText(), el_base) --this is a url, right?.,,
--updated
elseif tag == 'updated' or tag == 'dc:date' or tag == 'modified' or tag=='rss:pubDate' then
feed.updated = el:getText()
feed.updated_parsed=dateparser.parse(feed.updated)
--author
elseif tag=='author' or tag=='atom:author' then
feed.author_detail=atom_person_construct(el, el_base)
feed.author=feed.author_detail.name
--contributors
elseif tag=='contributor' or tag=='atom:contributor' then
tinsert(feed.contributors, atom_person_construct(el, el_base))
--icon
elseif tag=='icon' then
feed.icon=resolve(el:getText(), el_base)
--logo
elseif tag=='logo' then
feed.logo=resolve(el:getText(), el_base)
--language
elseif tag=='language' or tag=='dc:language' then
feed.language=feed.language or el:getText()
--licence
end
end
--feed.link (already resolved)
for i, link in pairs(feed.links) do
if link.rel=='alternate' or not link.rel or link.rel=='' then
feed.link=link.href
break
end
end
res.entries=parse_entries(root:getChildren('entry'),'atom', root_base)
return res
end
local function parse_rss(root, base_uri)
local channel = root:getChild({'channel', 'rdf:channel'})
local channel_base = rebase(channel, base_uri)
if not channel then return nil, "can't parse that." end
local feed = {links = {}, contributors={}}
local res = {
feed=feed,
format='rss',
entries={}
}
--this isn't quite right at all.
if root:getTag():lower()=='rdf:rdf' then
res.version='rss10'
else
res.version='rss20'
end
for i, el in ipairs(channel:getChildren('*')) do
local el_base=rebase(el, channel_base)
local tag = el:getTag()
if tag=='link' then
feed.link=resolve(el:getText(), el_base)
tinsert(feed.links, {href=feed.link})
--title
elseif tag == 'title' or tag == 'dc:title' then
feed.title=el:getText() --sanitize!
--subtitle
elseif tag == 'description' or tag =='dc:description' or tag=='itunes:subtitle' then
feed.subtitle=el:getText() --sanitize!
--rights
elseif tag == 'copyright' or tag == 'dc:rights' then
feed.rights=el:getText() --sanitize!
--generator
elseif tag == 'generator' then
feed.generator=el:getText()
elseif tag == 'admin:generatorAgent' then
feed.generator = feed.generator or el:getAttr('rdf:resource')
--info (nobody cares...)
elseif tag == 'feedburner:browserFriendly' then
feed.info = el:getText()
--updated
elseif tag == 'pubDate' or tag == 'dc:date' or tag == 'dcterms:modified' then
feed.updated = el:getText()
feed.updated_parsed = dateparser.parse(feed.updated)
--author
elseif tag=='managingEditor' or tag =='dc:creator' or tag=='itunes:author' or tag =='dc:creator' or tag=='dc:author' then
feed.author=tconcat(el:getChildren('text()'))
feed.author_details={name=feed.author}
elseif tag=='atom:author' then
feed.author_details = atom_person_construct(el, el_base)
feed.author = feed.author_details.name
--contributors
elseif tag == 'dc:contributor' then
tinsert(feed.contributors, {name=el:getText()})
elseif tag == 'atom:contributor' then
tinsert(feed.contributors, atom_person_construct(el, el_base))
--image
elseif tag=='image' or tag=='rdf:image' then
feed.image={
title=el:getChild('title'):getText(),
link=(el:getChild('link') or blanky):getText(),
width=(el:getChild('width') or blanky):getText(),
height=(el:getChild('height') or blanky):getText()
}
local url_el = el:getChild('url')
if url_el then feed.image.href = resolve(url_el:getText(), rebase(url_el, el_base)) end
--language
elseif tag=='language' or tag=='dc:language' then
feed.language=el:getText()
--licence
--publisher
--tags
end
end
res.entries=parse_entries(channel:getChildren('item'),'rss', channel_base)
return res
end
--- parse feed xml
-- @param xml_string feed xml, as a string
-- @param base_url (optional) source url of the feed. useful when resolving relative links found in feed contents
-- @return table with parsed feed info, or nil, error_message on error.
-- the format of the returned table is much like that on http://feedparser.org, with the major difference that
-- dates are parsed into unixtime. Most other fields are very much the same.
function feedparser.parse(xml_string, base_url)
local lom, err = LOM.parse(xml_string)
if not lom then return nil, "couldn't parse xml. lxp says: " .. err or "nothing" end
local rootElement = XMLElement.new(lom)
local root_tag = rootElement:getTag():lower()
if root_tag=='rdf:rdf' or root_tag=='rss' then
return parse_rss(rootElement, base_url)
elseif root_tag=='feed' then
return parse_atom(rootElement, base_url)
else
return nil, "unknown feed format"
end
end
--for the sake of backwards-compatibility, feedparser will export a global reference for lua < 5.3
if _VERSION:sub(-3) < "5.3" then
_G.feedparser=feedparser
end
return feedparser
| agpl-3.0 |
T-L-N/Dev_TLN | libs/feedparser.lua | 543 | 11955 | local LOM = assert(require("lxp.lom"), "LuaExpat doesn't seem to be installed. feedparser kind of needs it to work...")
local XMLElement = (loadfile "./libs/XMLElement.lua")()
local dateparser = (loadfile "./libs/dateparser.lua")()
local URL = (loadfile "./libs/url.lua")()
local tinsert, tremove, tconcat = table.insert, table.remove, table.concat
local pairs, ipairs = pairs, ipairs
--- feedparser, similar to the Universal Feed Parser for python, but a good deal weaker.
-- see http://feedparser.org for details about the Universal Feed Parser
local feedparser= {
_DESCRIPTION = "RSS and Atom feed parser",
_VERSION = "feedparser 0.71"
}
local blanky = XMLElement.new() --useful in a whole bunch of places
local function resolve(url, base_url)
return URL.absolute(base_url, url)
end
local function rebase(el, base_uri)
local xml_base = el:getAttr('xml:base')
if not xml_base then return base_uri end
return resolve(xml_base, base_uri)
end
local function parse_entries(entries_el, format_str, base)
local entries = {}
for i, entry_el in ipairs(entries_el) do
local entry = {enclosures={}, links={}, contributors={}}
local entry_base = rebase(entry_el, base)
for i, el in ipairs(entry_el:getChildren('*')) do
local tag = el:getTag()
local el_base = rebase(el, entry_base)
--title
if tag == 'title' or tag == 'dc:title' or tag =='rdf:title' then --'dc:title' doesn't occur in atom feeds, but whatever.
entry.title=el:getText()
--link(s)
elseif format_str == 'rss' and tag=='link' then
entry.link=resolve(el:getText(), el_base)
tinsert(entry.links, {href=entry.link})
elseif (format_str=='atom' and tag == 'link') or
(format_str == 'rss' and tag=='atom:link') then
local link = {}
for i, attr in ipairs{'rel','type', 'href','title'} do
link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) --uri
end
tinsert(entry.links, link)
if link.rel=='enclosure' then
tinsert(entry.enclosures, {
href=link.href,
length=el:getAttr('length'),
type=el:getAttr('type')
})
end
--rss enclosures
elseif format_str == 'rss' and tag=='enclosure' then
tinsert(entry.enclosures, {
url=el:getAttr('url'),
length=el:getAttr('length'),
type=el:getAttr('type')
})
--summary
elseif (format_str=='atom' and tag=='summary') or
(format_str=='rss' and(tag=='description' or tag=='dc:description' or tag=='rdf:description')) then
entry.summary=el:getText()
--TODO: summary_detail
--content
elseif (format_str=='atom' and tag=='content') or
(format_str=='rss' and (tag=='body' or tag=='xhtml:body' or tag == 'fullitem' or tag=='content:encoded')) then
entry.content=el:getText()
--TODO: content_detail
--published
elseif (format_str == 'atom' and (tag=='published' or tag=='issued')) or
(format_str == 'rss' and (tag=='dcterms:issued' or tag=='atom:published' or tag=='atom:issued')) then
entry.published = el:getText()
entry.published_parsed=dateparser.parse(entry.published)
--updated
elseif (format_str=='atom' and (tag=='updated' or tag=='modified')) or
(format_str=='rss' and (tag=='dc:date' or tag=='pubDate' or tag=='dcterms:modified')) then
entry.updated=el:getText()
entry.updated_parsed=dateparser.parse(entry.updated)
elseif tag=='created' or tag=='atom:created' or tag=='dcterms:created' then
entry.created=el:getText()
entry.created_parsed=dateparser.parse(entry.created)
--id
elseif (format_str =='atom' and tag=='id') or
(format_str=='rss' and tag=='guid') then
entry.id=resolve(el:getText(), el_base) -- this is a uri, right?...
--author
elseif format_str=='rss' and (tag=='author' or tag=='dc:creator') then --author tag should give the author's email. should I respect this?
entry.author=(el:getChild('name') or el):getText()
entry.author_detail={
name=entry.author
}
elseif format_str=='atom' and tag=='author' then
entry.author=(el:getChild('name') or el):getText()
entry.author_detail = {
name=entry.author,
email=(el:getChild('email') or blanky):getText()
}
local author_url = (el:getChild('url') or blanky):getText()
if author_url and author_url ~= "" then entry.author_detail.href=resolve(author_url, rebase(el:getChild('url'), el_base)) end
elseif tag=='category' or tag=='dc:subject' then
--todo
elseif tag=='source' then
--todo
end
end
--wrap up rss guid
if format_str == 'rss' and (not entry.id) and entry_el:getAttr('rdf:about') then
entry.id=resolve(entry_el:getAttr('rdf:about'), entry_base) --uri
end
--wrap up entry.link
for i, link in pairs(entry.links) do
if link.rel=="alternate" or (not link.rel) or link.rel=="" then
entry.link=link.href --already resolved.
break
end
end
if not entry.link and format_str=='rss' then
entry.link=entry.id
end
tinsert(entries, entry)
end
return entries
end
local function atom_person_construct(person_el, base_uri)
local dude ={
name= (person_el:getChild('name') or blanky):getText(),
email=(person_el:getChild('email') or blanky):getText()
}
local url_el = person_el:getChild('url')
if url_el then dude.href=resolve(url_el:getText(), rebase(url_el, base_uri)) end
return dude
end
local function parse_atom(root, base_uri)
local res = {}
local feed = {
links = {},
contributors={},
language = root:getAttr('lang') or root:getAttr('xml:lang')
}
local root_base = rebase(root, base_uri)
res.feed=feed
res.format='atom'
local version=(root:getAttr('version') or ''):lower()
if version=="1.0" or root:getAttr('xmlns')=='http://www.w3.org/2005/Atom' then res.version='atom10'
elseif version=="0.3" then res.version='atom03'
else res.version='atom' end
for i, el in ipairs(root:getChildren('*')) do
local tag = el:getTag()
local el_base=rebase(el, root_base)
if tag == 'title' or tag == 'dc:title' or tag == 'atom10:title' or tag == 'atom03:title' then
feed.title=el:getText() --sanitize!
--todo: feed.title_detail
--link stuff
elseif tag=='link' then
local link = {}
for i, attr in ipairs{'rel','type', 'href','title'} do
link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr)
end
tinsert(feed.links, link)
--subtitle
elseif tag == 'subtitle' then
feed.subtitle=el:getText() --sanitize!
elseif not feed.subtitle and (tag == 'tagline' or tag =='atom03:tagline' or tag=='dc:description') then
feed.subtitle=el:getText() --sanitize!
--rights
elseif tag == 'copyright' or tag == 'rights' then
feed.rights=el:getText() --sanitize!
--generator
elseif tag == 'generator' then
feed.generator=el:getText() --sanitize!
elseif tag == 'admin:generatorAgent' then
feed.generator = feed.generator or el:getAttr('rdf:resource')
--info
elseif tag == 'info' then --whatever, nobody cared, anyway.
feed.info = el:getText()
--id
elseif tag=='id' then
feed.id=resolve(el:getText(), el_base) --this is a url, right?.,,
--updated
elseif tag == 'updated' or tag == 'dc:date' or tag == 'modified' or tag=='rss:pubDate' then
feed.updated = el:getText()
feed.updated_parsed=dateparser.parse(feed.updated)
--author
elseif tag=='author' or tag=='atom:author' then
feed.author_detail=atom_person_construct(el, el_base)
feed.author=feed.author_detail.name
--contributors
elseif tag=='contributor' or tag=='atom:contributor' then
tinsert(feed.contributors, atom_person_construct(el, el_base))
--icon
elseif tag=='icon' then
feed.icon=resolve(el:getText(), el_base)
--logo
elseif tag=='logo' then
feed.logo=resolve(el:getText(), el_base)
--language
elseif tag=='language' or tag=='dc:language' then
feed.language=feed.language or el:getText()
--licence
end
end
--feed.link (already resolved)
for i, link in pairs(feed.links) do
if link.rel=='alternate' or not link.rel or link.rel=='' then
feed.link=link.href
break
end
end
res.entries=parse_entries(root:getChildren('entry'),'atom', root_base)
return res
end
local function parse_rss(root, base_uri)
local channel = root:getChild({'channel', 'rdf:channel'})
local channel_base = rebase(channel, base_uri)
if not channel then return nil, "can't parse that." end
local feed = {links = {}, contributors={}}
local res = {
feed=feed,
format='rss',
entries={}
}
--this isn't quite right at all.
if root:getTag():lower()=='rdf:rdf' then
res.version='rss10'
else
res.version='rss20'
end
for i, el in ipairs(channel:getChildren('*')) do
local el_base=rebase(el, channel_base)
local tag = el:getTag()
if tag=='link' then
feed.link=resolve(el:getText(), el_base)
tinsert(feed.links, {href=feed.link})
--title
elseif tag == 'title' or tag == 'dc:title' then
feed.title=el:getText() --sanitize!
--subtitle
elseif tag == 'description' or tag =='dc:description' or tag=='itunes:subtitle' then
feed.subtitle=el:getText() --sanitize!
--rights
elseif tag == 'copyright' or tag == 'dc:rights' then
feed.rights=el:getText() --sanitize!
--generator
elseif tag == 'generator' then
feed.generator=el:getText()
elseif tag == 'admin:generatorAgent' then
feed.generator = feed.generator or el:getAttr('rdf:resource')
--info (nobody cares...)
elseif tag == 'feedburner:browserFriendly' then
feed.info = el:getText()
--updated
elseif tag == 'pubDate' or tag == 'dc:date' or tag == 'dcterms:modified' then
feed.updated = el:getText()
feed.updated_parsed = dateparser.parse(feed.updated)
--author
elseif tag=='managingEditor' or tag =='dc:creator' or tag=='itunes:author' or tag =='dc:creator' or tag=='dc:author' then
feed.author=tconcat(el:getChildren('text()'))
feed.author_details={name=feed.author}
elseif tag=='atom:author' then
feed.author_details = atom_person_construct(el, el_base)
feed.author = feed.author_details.name
--contributors
elseif tag == 'dc:contributor' then
tinsert(feed.contributors, {name=el:getText()})
elseif tag == 'atom:contributor' then
tinsert(feed.contributors, atom_person_construct(el, el_base))
--image
elseif tag=='image' or tag=='rdf:image' then
feed.image={
title=el:getChild('title'):getText(),
link=(el:getChild('link') or blanky):getText(),
width=(el:getChild('width') or blanky):getText(),
height=(el:getChild('height') or blanky):getText()
}
local url_el = el:getChild('url')
if url_el then feed.image.href = resolve(url_el:getText(), rebase(url_el, el_base)) end
--language
elseif tag=='language' or tag=='dc:language' then
feed.language=el:getText()
--licence
--publisher
--tags
end
end
res.entries=parse_entries(channel:getChildren('item'),'rss', channel_base)
return res
end
--- parse feed xml
-- @param xml_string feed xml, as a string
-- @param base_url (optional) source url of the feed. useful when resolving relative links found in feed contents
-- @return table with parsed feed info, or nil, error_message on error.
-- the format of the returned table is much like that on http://feedparser.org, with the major difference that
-- dates are parsed into unixtime. Most other fields are very much the same.
function feedparser.parse(xml_string, base_url)
local lom, err = LOM.parse(xml_string)
if not lom then return nil, "couldn't parse xml. lxp says: " .. err or "nothing" end
local rootElement = XMLElement.new(lom)
local root_tag = rootElement:getTag():lower()
if root_tag=='rdf:rdf' or root_tag=='rss' then
return parse_rss(rootElement, base_url)
elseif root_tag=='feed' then
return parse_atom(rootElement, base_url)
else
return nil, "unknown feed format"
end
end
--for the sake of backwards-compatibility, feedparser will export a global reference for lua < 5.3
if _VERSION:sub(-3) < "5.3" then
_G.feedparser=feedparser
end
return feedparser
| gpl-2.0 |
TheSAguy/Natural-Evolution | prototypes/Vanilla_Changes/Functions.lua | 1 | 2865 |
---- Biter Attack Function - Normal Biter
function Biter_Melee_Attack_Healthy(damagevalue)
return
{
category = "melee",
target_type = "entity",
action =
{
type = "direct",
action_delivery =
{
type = "instant",
target_effects =
{
type = "damage",
damage = { amount = damagevalue , type = "physical"}
},
}
}
}
end
---- Biter Attack Function - Infected Biter
function Biter_Melee_Attack_Infected(damagevalue, damagevalue2)
return
{
category = "melee",
target_type = "entity",
action =
{
type = "direct",
action_delivery =
{
type = "instant",
target_effects =
{
type = "damage",
damage = { amount = damagevalue2 , type = "physical"}
},
{
type = "damage",
damage = { amount = damagevalue , type = "poison"}
},
}
}
}
end
---- Biter Attack Function - Mutated Biter
function Biter_Melee_Attack_Mutated(damagevalue, damagevalue2)
return
{
category = "melee",
target_type = "entity",
action =
{
type = "direct",
action_delivery =
{
type = "instant",
target_effects =
{
type = "damage",
damage = { amount = damagevalue2 , type = "physical"}
},
{
type = "damage",
damage = { amount = damagevalue , type = "acid"}
},
}
}
}
end
---- Spitter Attack Functions - Infected Spitter
function Spitter_Attack_Infected(data)
return
{
type = "projectile",
ammo_category = "rocket",
cooldown = data.cooldown,
range = data.range,
projectile_creation_distance = 1.9,
damage_modifier = data.damage_modifier,
warmup = 30,
ammo_type =
{
category = "biological",
action =
{
type = "direct",
action_delivery =
{
type = "projectile",
projectile = "Infected-Projectile",
starting_speed = 1
}
}
},
sound = make_spitter_roars(0.75),
animation = spitterattackanimation(data.scale, data.tint),
}
end
---- Spitter Attack Functions - Mutated Spitter
function Spitter_Attack_Mutated(data)
return
{
type = "projectile",
ammo_category = "rocket",
cooldown = data.cooldown,
range = data.range,
projectile_creation_distance = 1.9,
damage_modifier = data.damage_modifier,
warmup = 30,
ammo_type =
{
category = "biological",
action =
{
type = "direct",
action_delivery =
{
type = "projectile",
projectile = "Mutated-Projectile",
starting_speed = 1.5
}
}
},
sound = make_spitter_roars(0.75),
animation = spitterattackanimation(data.scale, data.tint),
}
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.