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 |
|---|---|---|---|---|---|
starlightknight/darkstar | scripts/zones/Bearclaw_Pinnacle/bcnms/flames_for_the_dead.lua | 9 | 1404 | -----------------------------------
-- Flames for the Dead
-- Bearclaw Pinnacle mission battlefield
-----------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/missions")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:getCurrentMission(COP) ~= dsp.mission.id.cop.THREE_PATHS or player:getCharVar("COP_Ulmia_s_Path") ~= 6) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
if player:getCurrentMission(COP) == dsp.mission.id.cop.THREE_PATHS and player:getCharVar("COP_Ulmia_s_Path") == 6 then
player:setCharVar("COP_Ulmia_s_Path", 7)
end
player:addExp(1000)
end
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/coral_fungus.lua | 12 | 1191 | -----------------------------------------
-- ID: 4450
-- Item: coral_fungus
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Strength -4
-- Mind 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4450);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -4);
target:addMod(MOD_MND, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -4);
target:delMod(MOD_MND, 2);
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/serving_of_bass_meuniere_+1.lua | 11 | 1367 | -----------------------------------------
-- ID: 4346
-- Item: serving_of_bass_meuniere_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Health % 3 (cap 130)
-- Dexterity 3
-- Agility 3
-- Mind -3
-- Ranged ACC % 6
-- Ranged ACC Cap 20
-----------------------------------------
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,14400,4346)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 3)
target:addMod(dsp.mod.FOOD_HP_CAP, 130)
target:addMod(dsp.mod.DEX, 3)
target:addMod(dsp.mod.AGI, 3)
target:addMod(dsp.mod.MND, -3)
target:addMod(dsp.mod.FOOD_RACCP, 6)
target:addMod(dsp.mod.FOOD_RACC_CAP, 20)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 3)
target:delMod(dsp.mod.FOOD_HP_CAP, 130)
target:delMod(dsp.mod.DEX, 3)
target:delMod(dsp.mod.AGI, 3)
target:delMod(dsp.mod.MND, -3)
target:delMod(dsp.mod.FOOD_RACCP, 6)
target:delMod(dsp.mod.FOOD_RACC_CAP, 20)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_5.lua | 2 | 3405 | -----------------------------------
-- Area: LaLoff Amphitheater
-- Name: Ark Angels 5 (Galka)
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
-----------------------------------
-- Death cutscenes:
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- Hume
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvan
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
local record = instance:getRecord();
local clearTime = record.clearTime;
if (player:hasCompletedMission(ZILART,ARK_ANGELS)) then
player:startEvent(0x7d01,instance:getEntrance(),clearTime,1,instance:getTimeInside(),180,4,1); -- winning CS (allow player to skip)
else
player:startEvent(0x7d01,instance:getEntrance(),clearTime,1,instance:getTimeInside(),180,4,0); -- winning CS (allow player to skip)
end
elseif (leavecode == 4) then
player:startEvent(0x7d02, 0, 0, 0, 0, 0, instance:getEntrance(), 180); -- player lost
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
local AAKeyitems = (player:hasKeyItem(SHARD_OF_APATHY) and player:hasKeyItem(SHARD_OF_ARROGANCE)
and player:hasKeyItem(SHARD_OF_COWARDICE) and player:hasKeyItem(SHARD_OF_ENVY));
if (csid == 0x7d01) then
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
player:addKeyItem(SHARD_OF_RAGE);
player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_RAGE);
if (AAKeyitems == true) then
player:completeMission(ZILART,ARK_ANGELS);
player:addMission(ZILART,THE_SEALED_SHRINE);
player:setVar("ZilartStatus",0);
end
end
end
local AAKeyitems = (player:hasKeyItem(SHARD_OF_APATHY) and player:hasKeyItem(SHARD_OF_ARROGANCE)
and player:hasKeyItem(SHARD_OF_COWARDICE) and player:hasKeyItem(SHARD_OF_ENVY)
and player:hasKeyItem(SHARD_OF_RAGE));
end; | gpl-3.0 |
focusworld/ghost-bot | plugins/banhammer.lua | 294 | 10470 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
-- Save to redis
local hash = 'superbanned:'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, msg.to.id)
if superbanned or banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, chat_id)
if superbanned then
print('SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
end
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if get_cmd == 'kick' then
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'superban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!')
return superban_user(member_id, chat_id)
elseif get_cmd == 'whitelist user' then
local hash = 'whitelist:user#id'..member_id
redis:set(hash, true)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted')
elseif get_cmd == 'whitelist delete user' then
local hash = 'whitelist:user#id'..member_id
redis:del(hash)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist')
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1] == 'kickme' then
kick_user(msg.from.id, msg.to.id)
end
if not is_momod(msg) then
return nil
end
local receiver = get_receiver(msg)
if matches[4] then
get_cmd = matches[1]..' '..matches[2]..' '..matches[3]
elseif matches[3] then
get_cmd = matches[1]..' '..matches[2]
else
get_cmd = matches[1]
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
ban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'superban' and is_admin(msg) then
local user_id = matches[3]
local chat_id = msg.to.id
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
superban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' globally banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'superbanned:'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
kick_user(matches[2], msg.to.id)
else
local member = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
if string.match(matches[4], '^%d+$') then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
else
local member = string.gsub(matches[4], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
user = "!kickme : Exit from group",
moderator = {
"!whitelist <enable>/<disable> : Enable or disable whitelist mode",
"!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id> : Remove user from whitelist",
"!whitelist delete chat : Remove chat from whitelist",
"!ban user <user_id> : Kick user from chat and kicks it if joins chat again",
"!ban user <username> : Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id> : Unban user",
"!kick <user_id> : Kick user from chat group by id",
"!kick <username> : Kick user from chat group by username",
},
admin = {
"!superban user <user_id> : Kick user from all chat and kicks it if joins again",
"!superban user <username> : Kick user from all chat and kicks it if joins again",
"!superban delete <user_id> : Unban user",
},
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (.*)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (.*)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (.*)$",
"^!(ban) (delete) (.*)$",
"^!(superban) (user) (.*)$",
"^!(superban) (delete) (.*)$",
"^!(kick) (.*)$",
"^!(kickme)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
} | gpl-2.0 |
starlightknight/darkstar | scripts/globals/weaponskills/blade_to.lua | 10 | 1417 | -----------------------------------
-- Blade To
-- Katana weapon skill
-- Skill Level: 100
-- Deals ice elemental damage. Damage varies with TP.
-- Aligned with the Snow Gorget & Breeze Gorget.
-- Aligned with the Snow Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: STR:30% INT:30%
-- 100%TP 200%TP 300%TP
-- 0.50 0.75 1.00
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 0.5 params.ftp200 = 0.75 params.ftp300 = 1
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.3 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1 params.atk200 = 1 params.atk300 = 1
params.hybridWS = true
params.ele = dsp.magic.ele.ICE
params.skill = dsp.skill.KATANA
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4 params.int_wsc = 0.4
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Cloister_of_Frost/npcs/Cermet_Headstone.lua | 11 | 2584 | -----------------------------------
-- Area: Cloister of Frost
-- NPC: Cermet Headstone
-- Involved in Mission: ZM5 Headstone Pilgrimage (Ice Fragment)
-- !pos 566 0 606 203
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/missions");
local ID = require("scripts/zones/Cloister_of_Frost/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == dsp.mission.id.zilart.HEADSTONE_PILGRIMAGE) then
if (player:hasKeyItem(dsp.ki.ICE_FRAGMENT) == false) then
player:startEvent(200,dsp.ki.ICE_FRAGMENT);
elseif (player:hasKeyItem(dsp.ki.FIRE_FRAGMENT) and player:hasKeyItem(dsp.ki.WATER_FRAGMENT) and player:hasKeyItem(dsp.ki.EARTH_FRAGMENT) and
player:hasKeyItem(dsp.ki.WIND_FRAGMENT) and player:hasKeyItem(dsp.ki.LIGHTNING_FRAGMENT) and player:hasKeyItem(dsp.ki.ICE_FRAGMENT) and
player:hasKeyItem(dsp.ki.LIGHT_FRAGMENT) and player:hasKeyItem(dsp.ki.DARK_FRAGMENT)) then
player:messageSpecial(ID.text.ALREADY_HAVE_ALL_FRAGS);
elseif (player:hasKeyItem(dsp.ki.ICE_FRAGMENT)) then
player:messageSpecial(ID.text.ALREADY_OBTAINED_FRAG,dsp.ki.ICE_FRAGMENT);
end
elseif (player:hasCompletedMission(ZILART,dsp.mission.id.zilart.HEADSTONE_PILGRIMAGE)) then
player:messageSpecial(ID.text.ZILART_MONUMENT);
else
player:messageSpecial(ID.text.CANNOT_REMOVE_FRAG);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 200 and option == 1) then
player:addKeyItem(dsp.ki.ICE_FRAGMENT);
-- Check and see if all fragments have been found (no need to check ice and dark frag)
if (player:hasKeyItem(dsp.ki.FIRE_FRAGMENT) and player:hasKeyItem(dsp.ki.EARTH_FRAGMENT) and player:hasKeyItem(dsp.ki.WATER_FRAGMENT) and
player:hasKeyItem(dsp.ki.WIND_FRAGMENT) and player:hasKeyItem(dsp.ki.LIGHTNING_FRAGMENT) and player:hasKeyItem(dsp.ki.LIGHT_FRAGMENT)) then
player:messageSpecial(ID.text.FOUND_ALL_FRAGS,dsp.ki.ICE_FRAGMENT);
player:addTitle(dsp.title.BEARER_OF_THE_EIGHT_PRAYERS);
player:completeMission(ZILART,dsp.mission.id.zilart.HEADSTONE_PILGRIMAGE);
player:addMission(ZILART,dsp.mission.id.zilart.THROUGH_THE_QUICKSAND_CAVES);
else
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.ICE_FRAGMENT);
end
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/serving_of_flounder_meuniere_+1.lua | 12 | 1659 | -----------------------------------------
-- ID: 4345
-- Item: serving_of_flounder_meuniere_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity 6
-- Vitality 1
-- Mind -1
-- Ranged ACC 15
-- Ranged ATT % 14
-- Ranged ATT Cap 30
-- Enmity -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4345);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 6);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_MND, -1);
target:addMod(MOD_RACC, 15);
target:addMod(MOD_FOOD_RATTP, 14);
target:addMod(MOD_FOOD_RATT_CAP, 30);
target:addMod(MOD_ENMITY, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 6);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_MND, -1);
target:delMod(MOD_RACC, 15);
target:delMod(MOD_FOOD_RATTP, 14);
target:delMod(MOD_FOOD_RATT_CAP, 30);
target:delMod(MOD_ENMITY, -4);
end;
| gpl-3.0 |
Amorph/premake-stable | src/tools/dotnet.lua | 40 | 1857 | --
-- dotnet.lua
-- Interface for the C# compilers, all of which are flag compatible.
-- Copyright (c) 2002-2009 Jason Perkins and the Premake project
--
premake.dotnet = { }
premake.dotnet.namestyle = "windows"
--
-- Translation of Premake flags into CSC flags
--
local flags =
{
FatalWarning = "/warnaserror",
Optimize = "/optimize",
OptimizeSize = "/optimize",
OptimizeSpeed = "/optimize",
Symbols = "/debug",
Unsafe = "/unsafe"
}
--
-- Return the default build action for a given file, based on the file extension.
--
function premake.dotnet.getbuildaction(fcfg)
local ext = path.getextension(fcfg.name):lower()
if fcfg.buildaction == "Compile" or ext == ".cs" then
return "Compile"
elseif fcfg.buildaction == "Embed" or ext == ".resx" then
return "EmbeddedResource"
elseif fcfg.buildaction == "Copy" or ext == ".asax" or ext == ".aspx" then
return "Content"
else
return "None"
end
end
--
-- Returns the compiler filename (they all use the same arguments)
--
function premake.dotnet.getcompilervar(cfg)
if (_OPTIONS.dotnet == "msnet") then
return "csc"
elseif (_OPTIONS.dotnet == "mono") then
if (cfg.framework <= "1.1") then
return "mcs"
elseif (cfg.framework >= "4.0") then
return "dmcs"
else
return "gmcs"
end
else
return "cscc"
end
end
--
-- Returns a list of compiler flags, based on the supplied configuration.
--
function premake.dotnet.getflags(cfg)
local result = table.translate(cfg.flags, flags)
return result
end
--
-- Translates the Premake kind into the CSC kind string.
--
function premake.dotnet.getkind(cfg)
if (cfg.kind == "ConsoleApp") then
return "Exe"
elseif (cfg.kind == "WindowedApp") then
return "WinExe"
elseif (cfg.kind == "SharedLib") then
return "Library"
end
end | bsd-3-clause |
gedads/Neodynamis | scripts/zones/Bastok_Mines/npcs/Rodellieux.lua | 17 | 1433 | -----------------------------------
-- Area: Bastok_Mines
-- NPC: Rodellieux
-- Only sells when Bastok controlls Fauregandi Region
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(FAUREGANDI);
if (RegionOwner ~= NATION_BASTOK) then
player:showText(npc,RODELLIEUX_CLOSED_DIALOG);
else
player:showText(npc,RODELLIEUX_OPEN_DIALOG);
stock = {
0x11db, 90, --Beaugreens
0x110b, 39, --Faerie Apple
0x02b3, 54 --Maple Log
}
showShop(player,BASTOK,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Abyssea-Tahrongi/npcs/qm21.lua | 3 | 1566 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: ???
-- Spawns Lacovie
-- !pos ? ? ? 45
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16961948) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(OVERGROWN_MANDRAGORA_FLOWER) and player:hasKeyItem(CHIPPED_SANDWORM_TOOTH)) then
player:startEvent(1020, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Ask if player wants to use KIs
else
player:startEvent(1021, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16961948):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(OVERGROWN_MANDRAGORA_FLOWER);
player:delKeyItem(CHIPPED_SANDWORM_TOOTH);
end
end;
| gpl-3.0 |
hyee/dbcli | lib/misc.lua | 1 | 17960 | local ffi = require("ffi")
local string,table,math,java,loadstring,tostring,tonumber=string,table,math,java,loadstring,tostring,tonumber
local ipairs,pairs,type=ipairs,pairs,type
function string.initcap(v)
return (' '..v):lower():gsub("([^%w])(%w)",function(a,b) return a..b:upper() end):sub(2)
end
function os.shell(cmd,args)
io.popen('"'..cmd..(args and (" "..args) or "")..'"')
end
function os.find_extension(exe,ignore_errors)
local exes=type(exe)=='string' and {exe} or exe
local err='Cannot find executable "'..exes[1]..'" in the default path, please add it into EXT_PATH of file data'..env.PATH_DEL..(env.IS_WINDOWS and 'init.cfg' or 'init.conf')
for _,exe in ipairs(exes) do
if exe:find('[\\/]') then
local type,file=os.exists(exe)
if not ignore_errors then env.checkerr(type,err) end
return file
end
exe='"'..env.join_path(exe):trim('"')..'"'
local nul=env.IS_WINDOWS and "NUL" or "/dev/null"
local cmd=string.format("%s %s 2>%s", env.IS_WINDOWS and "where " or "which ",exe,nul)
local f=io.popen(cmd)
local path
for file in f:lines() do
path=file
break
end
if path then return path end
end
env.checkerr(ignore_errors,err)
end
--Continus sep would return empty element
function string.split (s, sep, plain,occurrence,case_insensitive)
local r={}
for v in s:gsplit(sep,plain,occurrence,case_insensitive) do
r[#r+1]=v
end
return r
end
function string.replace(s,sep,txt,plain,occurrence,case_insensitive)
if not sep or s=='' then return s end
local r=s:split(sep,plain,occurrence,case_insensitive)
return table.concat(r,txt),#r-1
end
function string.escape(s, mode)
s = s:gsub('([%^%$%(%)%.%[%]%*%+%-%?%%])', '%%%1')
if mode == '*i' then s = s:case_insensitive_pattern() end
return s
end
function string.gsplit(s, sep, plain,occurrence,case_insensitive)
local start = 1
local counter=0
local done = false
local s1=case_insensitive==true and s:lower() or s
local sep1=case_insensitive==true and sep:lower() or sep
local function pass(i, j)
if i and ((not occurrence) or counter<occurrence) then
local seg = i>1 and s:sub(start, i - 1) or ""
start = j + 1
counter=counter+1
return seg, s:sub(i,j),counter,i,j
else
done = true
return s:sub(start),"",counter+1
end
end
return function()
if done then return end
if sep1 == '' then done = true;return s end
return pass(s1:find(sep1, start, plain))
end
end
function string.case_insensitive_pattern(pattern)
-- find an optional '%' (group 1) followed by any character (group 2)
local p = pattern:gsub("(%%?)(.)",
function(percent, letter)
if percent ~= "" or not letter:match("%a") then
-- if the '%' matched, or `letter` is not a letter, return "as is"
return percent .. letter
else
-- else, return a case-insensitive character class of the matched letter
return string.format("[%s%s]", letter:lower(), letter:upper())
end
end)
return p
end
local spaces={}
local s=' \t\n\v\f\r\0'
local allspace={
'\t', --0x9
'\n', --0xa
'\x0b', --0xb
'\x0c', --0xc
'\r', --0xd
' ', --0x20
'\xa3\xa0',--
'\xc2\x85', --0x85
'\xc2\xa0', --0xa0
'\xe1\x9a\x80', --0x1680
'\xe1\xa0\x8e', --0x180e
'\xe2\x80\x80', --0x2000
'\xe2\x80\x81', --0x2001
'\xe2\x80\x82', --0x2002
'\xe2\x80\x83', --0x2003
'\xe2\x80\x84', --0x2004
'\xe2\x80\x85', --0x2005
'\xe2\x80\x86', --0x2006
'\xe2\x80\x87', --0x2007
'\xe2\x80\x88', --0x2008
'\xe2\x80\x89', --0x2009
'\xe2\x80\x8a', --0x200a
'\xe2\x80\x8b', --0x200b
'\xe2\x80\x8c', --0x200c
'\xe2\x80\x8d', --0x200d
'\xe2\x80\xa8', --0x2028
'\xe2\x80\xa9', --0x2029
'\xe2\x80\xaf', --0x202f
'\xe2\x81\x9f', --0x205f
'\xe2\x81\xa0', --0x2060
'\xe3\x80\x80', --0x3000
'\xef\xbb\xbf', --0xfeff
}
for i=1,#s do spaces[s:byte(i)]=true end
local ext_spaces={}
local function exp_pattern(sep)
local ary
if sep then
if not ext_spaces[sep] then
ext_spaces[sep]={}
for i=1,#sep do ext_spaces[sep][sep:byte(i)]=true end
end
ary=ext_spaces[sep]
end
return ary
end
local function rtrim(s,sep)
local ary,f=exp_pattern(sep)
if type(s)=='string' then
local len=#s
for i=len,1,-1 do
local p=s:byte(i)
if f then
f=nil
elseif p==160 and (s:byte(i-1)==194 or s:byte(i-1)==163) then
f=true
elseif not spaces[p] and not (ary and ary[p]) then
return i==len and s or s:sub(1,i)
elseif i==1 then
return ''
end
end
end
return s
end
local function ltrim(s,sep)
local ary,f=exp_pattern(sep)
if type(s)=='string' then
local len=#s
for i=1,len do
local p=s:byte(i)
if f then
f=nil
elseif (p==194 or p==163) and s:byte(i-1)==160 then
f=true
elseif not spaces[p] and not (ary and ary[p]) then
return i==1 and s or s:sub(i)
elseif i==len then
return ''
end
end
end
return s
end
string.ltrim,string.rtrim=ltrim,rtrim
function string.trim(s,sep)
return rtrim(ltrim(s,sep),sep)
end
String=java.require("java.lang.String")
local String=String
--this function only support %s
function string.fmt(base,...)
local args = {...}
for k,v in ipairs(args) do
if type(v)~="string" then
args[k]=tostring(v)
end
end
return String:format(base,table.unpack(args))
end
function string.format_number(base,s,cast)
if not tonumber(s) then return s end
return String:format(base,java.cast(s,cast or 'double'))
end
function string.lpad(str, len, char)
str=tostring(str) or str
return (str and ((char or ' '):rep(len - #str)..str):sub(-len)) or str
end
function string.rpad(str, len, char)
str=tostring(str) or str
return (str and (str..(char or ' '):rep(len - #str)):sub(1,len)) or str
end
function string.cpad(str, len, char,func)
if not str then return str end
str,char=tostring(str) or str,char or ' '
str=str:sub(1,len)
local left=char:rep(math.floor((len-#str)/2))
local right=char:rep(len-#left-#str)
return type(func)~="function" and ("%s%s%s"):format(left,str,right) or func(left,str,right)
end
if not table.unpack then table.unpack=function(tab) return unpack(tab) end end
local system=java.system
local clocker=system.currentTimeMillis
function os.timer()
return clocker()/1000
end
function string.from(v)
local path=_G.WORK_DIR
path=path and #path or 0
if type(v) == "function" then
local d=debug.getinfo(v)
local src=d.source:gsub("^@+","",1):split(path,true)
if src and src~='' then
return 'function('..src[#src]:gsub('%.lua$','#'..d.linedefined)..')'
end
elseif type(v) == "string" then
return ("%q"):format(v:gsub("\t"," "))
end
return tostring(v)
end
local weekmeta={__mode='k'}
local globalweek=setmetatable({},weekmeta)
function table.weak(reuse)
return reuse and globalweek or setmetatable({},weekmeta)
end
function table.append(tab,...)
for i=1,select('#',...) do
tab[#tab+1]=select(i,...)
end
end
local json=json
if json.use_lpeg then json.use_lpeg () end
function table.totable(str)
local txt,err,done=loadstring('return '..str)
if not txt then
done,txt=pcall(json.decode,str)
else
done,txt=pcall(txt)
end
if not done then
local idx=0
str=('\n'..str):gsub('\n',function(s) idx=idx+1;return string.format('\n%4d',idx) end)
env.raise('Error while parsing text into Lua table:' ..(err or tostring(txt) or '')..str)
end
return txt
end
local function compare(a,b)
local t1,t2=type(a[1]),type(b[1])
if t1==t2 and t1~='table' and t1~='function' and t1~='userdata' and t1~='thread' then return a[1]<b[1] end
if t1=="number" then return true end
if t2=="number" then return false end
return tostring(a[1])<tostring(b[1])
end
function math.round(exact, quantum)
if type(exact)~='number' then return exact end
quantum = quantum and 10^quantum or 1
local quant,frac = math.modf(exact*quantum)
return (quant + (frac > 0.5 and 1 or 0))/quantum
end
if not table.clone then
table.clone=function(t,depth) -- deep-copy a table
if type(t) ~= "table" or (depth or 1)<=0 then return t end
local meta = getmetatable(t)
local target = {}
for k, v in pairs(t) do
if type(v) == "table" then
target[k] = table.clone(v,(tonumber(depth) or 99)-1)
else
target[k] = v
end
end
setmetatable(target, meta)
return target
end
end
function table.week(typ,gc)
return setmetatable({},{__mode=typ or 'k'})
end
function table.strong(tab)
return setmetatable(tab or {},{__gc=function(self) print('table is gc.') end})
end
function table.avgsum(t)
local sum = 0
local count= 0
for k,v in pairs(t) do
if type(v) == 'number' then
sum = sum + v
count = count + 1
end
end
return (sum / count),sum,count
end
-- Get the mode of a table. Returns a table of values.
-- Works on anything (not just numbers).
function table.mode( t )
local counts={}
for k, v in pairs( t ) do
if counts[v] == nil then
counts[v] = 1
else
counts[v] = counts[v] + 1
end
end
local biggestCount = 0
for k, v in pairs( counts ) do
if v > biggestCount then
biggestCount = v
end
end
local temp={}
for k,v in pairs( counts ) do
if v == biggestCount then
table.insert( temp, k )
end
end
return temp
end
-- Get the median of a table.
function table.median( t )
local temp={}
-- deep copy table so that when we sort it, the original is unchanged
-- also weed out any non numbers
for k,v in pairs(t) do
if type(v) == 'number' then
table.insert( temp, v )
end
end
table.sort( temp )
-- If we have an even number of table elements or odd.
if math.fmod(#temp,2) == 0 then
-- return mean value of middle two elements
return ( temp[#temp/2] + temp[(#temp/2)+1] ) / 2
else
-- return middle element
return temp[math.ceil(#temp/2)]
end
end
-- Get the standard deviation of a table
function table.stddev( t )
local m
local vm
local sum = 0
local count = 0
local result
m = table.avgsum( t )
for k,v in pairs(t) do
if type(v) == 'number' then
vm = v - m
sum = sum + (vm * vm)
count = count + 1
end
end
result = math.sqrt(sum / (count-1))
return result
end
-- Get the max and min for a table
function table.maxmin( t )
local max = -math.huge
local min = math.huge
for k,v in pairs( t ) do
if type(v) == 'number' then
max = math.max( max, v )
min = math.min( min, v )
end
end
return max, min
end
function table.dump(tbl,indent,maxdep,tabs)
maxdep=tonumber(maxdep) or 9
if maxdep<=1 then
return tostring(tbl)
end
if tabs==nil then
tabs={}
end
if not indent then indent = '' end
indent=string.rep(' ',type(indent)=="number" and indent or #indent)
local ind = 0
local pad=indent..' '
local maxlen=0
local keys={}
local fmtfun=string.format
if type(tbl)=='userdata' then
local t=debug.getmetatable(tbl)
if type(t)~='table' or not t.__pairs then
return indent..tostring(tbl)
end
end
for k,_ in pairs(tbl) do
local k1=k
if type(k)=="string" and not k:match("^[%w_]+$") then k1=string.format("[%q]",k) end
keys[#keys+1]={k,k1}
if maxlen<#tostring(k1) then maxlen=#tostring(k1) end
if maxlen>99 then
fmtfun=string.fmt
end
end
table.sort(keys,compare)
local rs=""
for v, k in ipairs(keys) do
v,k=tbl[k[1]],k[2]
local fmt =(ind==0 and "{ " or pad) .. fmtfun('%-'..maxlen..'s%s' ,tostring(k),'= ')
local margin=(ind==0 and indent or '')..fmt
rs=rs..fmt
local is_javaobj=false
if type(v) =='userdata' then
local t=debug.getmetatable(tbl)
if type(t)=='table' and t.__pairs then
is_javaobj=true
end
end
if type(v) == "table" --[[or is_javaobj]] then
if k=='root' then
rs=rs..'<<Bypass root>>'
elseif tabs then
if not tabs[v] then
local c=tabs.__current_key or ''
local c1=c..(c=='' and '' or '.')..tostring(k)
tabs[v],tabs.__current_key=c1,c1
rs=rs..table.dump(v,margin,maxdep-1,tabs)
tabs.__current_key=c
else
rs=rs..'<<Refer to '..tabs[v]..'>>'
end
else
rs=rs..table.dump(v,margin,maxdep-1,tabs)
end
elseif type(v) == "function" then
rs=rs..'<'..string.from(v)..'>'
elseif type(v) == "userdata" then
rs=rs..'<userdata('..tostring(v)..')>'
elseif type(v) == "string" then
rs=rs..string.format("%q",v:gsub("\n","\n"..string.rep(" ",#margin)))
else
rs=rs..tostring(v)
end
rs=rs..',\n'
ind=ind+1
end
if ind==0 then return '{}' end
rs=rs:sub(1,-3)..'\n'
if ind<2 then return rs:sub(1,-2)..' }' end
return rs..indent..'}'
end
function try(args)
local succ,res,err,final=pcall(args[1])
local catch=args.catch or args[2]
local finally=args.finally or args[3]
final,err=true,not succ
if err and catch then
if(type(res)=="string" and env.ansi) then
res=res:match(env.ansi.pattern.."(.-)"..env.ansi.pattern)
end
succ,res=pcall(catch,res)
end
if finally then
final,err=pcall(finally,err)
if not catch or not final then succ,res=final,err or res end
end
if not succ then env.raise_error(res) end
return res
end
function string.fromhex(str)
return (str:gsub('..', function (cc)
return string.char(tonumber(cc, 16))
end))
end
--[[UTF-8 codepoint:
byte 1 2 3 4
--------------------------------------------
00 - 7F
C2 - DF 80 - BF
E0 A0 - BF 80 - BF
E1 - EC 80 - BF 80 - BF
ED 80 - 9F 80 - BF
EE - EF 80 - BF 80 - BF
F0 90 - BF 80 - BF 80 - BF
F1 - F3 80 - BF 80 - BF 80 - BF
F4 80 - 8F 80 - BF 80 - BF
The first hex character present the bytes of the char:
0-7: 1 byte, e.g.: 57
C-D: 2 bytes,e.g.: ce 9a
E: 3 bytes,e.g.: e6 ad a1
F: 4 bytes
--]]--
function string.chars(s,start)
local i = start or 1
if not s or i>#s then return nil end
local function next()
local c,i1,p,is_multi = s:byte(i),i
if not c then return end
if c >= 0xC2 and c <= 0xDF then
local c2 = s:byte(i + 1)
if c2 and c2 >= 0x80 and c2 <= 0xBF then i=i+1 end
elseif c >= 0xE0 and c <= 0xEF then
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
local flag = c2 and c3 and true or false
if c == 0xE0 then
if flag and c2 >= 0xA0 and c2 <= 0xBF and c3 >= 0x80 and c3 <= 0xBF then i1=i+2 end
elseif c >= 0xE1 and c <= 0xEC then
if flag and c2 >= 0x80 and c2 <= 0xBF and c3 >= 0x80 and c3 <= 0xBF then i1=i+2 end
elseif c == 0xED then
if flag and c2 >= 0x80 and c2 <= 0x9F and c3 >= 0x80 and c3 <= 0xBF then i1=i+2 end
elseif c >= 0xEE and c <= 0xEF then
if flag and
not (c == 0xEF and c2 == 0xBF and (c3 == 0xBE or c3 == 0xBF)) and
c2 >= 0x80 and c2 <= 0xBF and c3 >= 0x80 and c3 <= 0xBF
then i1=i+2 end
end
elseif c >= 0xF0 and c <= 0xF4 then
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
local c4 = s:byte(i + 3)
local flag = c2 and c3 and c4 and true or false
if c == 0xF0 then
if flag and
c2 >= 0x90 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
then i1=i+3 end
elseif c >= 0xF1 and c <= 0xF3 then
if flag and
c2 >= 0x80 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
then i1=i+3 end
elseif c == 0xF4 then
if flag and
c2 >= 0x80 and c2 <= 0x8F and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
then i1=i+3 end
end
end
p,i,is_multi=s:sub(i,i1),i1+1,i1>i
return p,is_multi,i
end
return next
end
function string.wcwidth(s)
if s=="" then return 0,0 end
if not s then return nil end
local len1,len2=0,0
for c,is_multi in s:chars() do
len1,len2=len1+1,len2+(is_multi and 2 or 1)
end
return len1,len2
end | mit |
starlightknight/darkstar | scripts/zones/Lower_Jeuno/npcs/Hasim.lua | 6 | 3566 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Hasim
-- Standard Merchant NPC
-----------------------------------
local ID = require("scripts/zones/Lower_Jeuno/IDs")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local stock =
{
4612, 23400, -- Scroll of Cure IV
4616, 11200, -- Scroll of Curaga II
4617, 19932, -- Scroll of Curaga III
4625, 2330, -- Scroll of Silena
4626, 19200, -- Scroll of Stona
4627, 13300, -- Scroll of Viruna
4628, 8586, -- Scroll of Cursna
4653, 32000, -- Scroll of Protect III
4734, 7074, -- Scroll of Protectra II
4735, 19200, -- Scroll of Protectra III
4658, 26244, -- Scroll of Shell III
4738, 1760, -- Scroll of Shellra
4739, 14080, -- Scroll of Shellra II
4740, 26244, -- Scroll of Shellra III
4668, 1760, -- Scroll of Barfire
4669, 3624, -- Scroll of Barblizzard
4670, 930, -- Scroll of Baraero
4671, 156, -- Scroll of Barstone
4672, 5754, -- Scroll of Barthunder
4673, 360, -- Scroll of Barwater
4674, 1760, -- Scroll of Barfira
4675, 3624, -- Scroll of Barblizzara
4676, 930, -- Scroll of Baraera
4677, 156, -- Scroll of Barstonra
4678, 5754, -- Scroll of Barthundra
4679, 360, -- Scroll of Barwatera
4680, 244, -- Scroll of Barsleep
4681, 400, -- Scroll of Barpoison
4682, 780, -- Scroll of Barparalyze
4683, 2030, -- Scroll of Barblind
4684, 4608, -- Scroll of Barsilence
4694, 244, -- Scroll of Barsleepra
4695, 400, -- Scroll of Barpoisonra
4696, 780, -- Scroll of Barparalyzra
4697, 2030, -- Scroll of Barblindra
4698, 4608, -- Scroll of Barsilencera
4685, 15120, -- Scroll of Barpetrify
4686, 9600, -- Scroll of Barvirus
4699, 15120, -- Scroll of Barpetra
4700, 9600, -- Scroll of Barvira
5089, 73740, -- Scroll of Gain-VIT
5092, 77500, -- Scroll of Gain-MND
5090, 85680, -- Scroll of Gain-AGI
5093, 81900, -- Scroll of Gain-CHR
5087, 89804, -- Scroll of Gain-STR
5091, 94461, -- Scroll of Gain-INT
5088, 99613, -- Scroll of Gain-DEX
5096, 73740, -- Scroll of Boost-VIT
5099, 77500, -- Scroll of Boost-MND
5097, 85680, -- Scroll of Boost-AGI
5100, 81900, -- Scroll of Boost-CHR
5094, 89804, -- Scroll of Boost-STR
5098, 94461, -- Scroll of Boost-INT
5095, 99613, -- Scroll of Boost-DEX
5106, 73500, -- Scroll of Inundation
4849, 130378, -- Scroll of Addle
4629, 35000, -- Scroll of Holy
4647, 20000, -- Scroll of Banishga II
4737, 119240, -- Scroll of Protecra V
4742, 124540, -- Scroll of Shellra V
4633, 139135, -- Scroll of Dia III
6569, 139135, -- Scroll of Slow II
6570, 139135, -- Scroll of Paralyze II
6571, 139135, -- Scroll of Phalanx II
}
player:showText(npc,ID.text.HASIM_SHOP_DIALOG)
dsp.shop.general(player, stock)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Port_Bastok/npcs/Numa.lua | 17 | 1786 | -----------------------------------
-- Area: Port Bastok
-- NPC: Numa
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,NUMA_SHOP_DIALOG);
stock = {
0x30A9, 5079,1, --Cotton Hachimaki
0x3129, 7654,1, --Cotton Dogi
0x31A9, 4212,1, --Cotton Tekko
0x3229, 6133,1, --Cotton Sitabaki
0x32A9, 3924,1, --Cotton Kyahan
0x3395, 3825,1, --Silver Obi
0x30A8, 759,2, --Hachimaki
0x3128, 1145,2, --Kenpogi
0x31A8, 630,2, --Tekko
0x3228, 915,2, --Sitabaki
0x32A8, 584,2, --Kyahan
0x02C0, 132,2, --Bamboo Stick
0x025D, 180,3, --Pickaxe
0x16EB, 13500,3, --Toolbag (Ino)
0x16EC, 18000,3, --Toolbag (Shika)
0x16ED, 18000,3 --Toolbag (Cho)
}
showNationShop(player, NATION_BASTOK, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
blogic/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/ltq-dsl.lua | 17 | 4392 | local function scrape()
local fd = io.popen("/etc/init.d/dsl_control lucistat")
local dsl_func = loadstring(fd:read("*a"))
fd:close()
if not dsl_func then
return
end
local dsl_stat = dsl_func()
local dsl_line_attenuation = metric("dsl_line_attenuation_db", "gauge")
local dsl_signal_attenuation = metric("dsl_signal_attenuation_db", "gauge")
local dsl_snr = metric("dsl_signal_to_noise_margin_db", "gauge")
local dsl_aggregated_transmit_power = metric("dsl_aggregated_transmit_power_db", "gauge")
local dsl_latency = metric("dsl_latency_seconds", "gauge")
local dsl_datarate = metric("dsl_datarate", "gauge")
local dsl_max_datarate = metric("dsl_max_datarate", "gauge")
local dsl_error_seconds_total = metric("dsl_error_seconds_total", "counter")
local dsl_errors_total = metric("dsl_errors_total", "counter")
-- dsl hardware/firmware information
metric("dsl_info", "gauge", {
atuc_vendor_id = dsl_stat.atuc_vendor_id,
atuc_system_vendor_id = dsl_stat.atuc_system_vendor_id,
chipset = dsl_stat.chipset,
firmware_version = dsl_stat.firmware_version,
api_version = dsl_stat.api_version,
}, 1)
-- dsl line settings information
metric("dsl_line_info", "gauge", {
xtse1 = dsl_stat.xtse1,
xtse2 = dsl_stat.xtse2,
xtse3 = dsl_stat.xtse3,
xtse4 = dsl_stat.xtse4,
xtse5 = dsl_stat.xtse5,
xtse6 = dsl_stat.xtse6,
xtse7 = dsl_stat.xtse7,
xtse8 = dsl_stat.xtse8,
annex = dsl_stat.annex_s,
mode = dsl_stat.line_mode_s,
profile = dsl_stat.profile_s,
}, 1)
-- dsl up is 1 if the line is up and running
local dsl_up
if dsl_stat.line_state == "UP" then
dsl_up = 1
else
dsl_up = 0
end
metric("dsl_up", "gauge", {
detail = dsl_stat.line_state_detail,
}, dsl_up)
-- dsl line status data
metric("dsl_uptime_seconds", "gauge", {}, dsl_stat.line_uptime)
-- dsl db measurements
dsl_line_attenuation({direction="down"}, dsl_stat.line_attenuation_down)
dsl_line_attenuation({direction="up"}, dsl_stat.line_attenuation_up)
dsl_signal_attenuation({direction="down"}, dsl_stat.signal_attenuation_down)
dsl_signal_attenuation({direction="up"}, dsl_stat.signal_attenuation_up)
dsl_snr({direction="down"}, dsl_stat.noise_margin_down)
dsl_snr({direction="up"}, dsl_stat.noise_margin_up)
dsl_aggregated_transmit_power({direction="down"}, dsl_stat.actatp_down)
dsl_aggregated_transmit_power({direction="up"}, dsl_stat.actatp_up)
-- dsl performance data
if dsl_stat.latency_down ~= nil then
dsl_latency({direction="down"}, dsl_stat.latency_down / 1000000)
dsl_latency({direction="up"}, dsl_stat.latency_up / 1000000)
end
dsl_datarate({direction="down"}, dsl_stat.data_rate_down)
dsl_datarate({direction="up"}, dsl_stat.data_rate_up)
dsl_max_datarate({direction="down"}, dsl_stat.max_data_rate_down)
dsl_max_datarate({direction="up"}, dsl_stat.max_data_rate_up)
-- dsl errors
dsl_error_seconds_total({err="forward error correction",loc="near"}, dsl_stat.errors_fecs_near)
dsl_error_seconds_total({err="forward error correction",loc="far"}, dsl_stat.errors_fecs_far)
dsl_error_seconds_total({err="errored",loc="near"}, dsl_stat.errors_es_near)
dsl_error_seconds_total({err="errored",loc="far"}, dsl_stat.errors_es_near)
dsl_error_seconds_total({err="severely errored",loc="near"}, dsl_stat.errors_ses_near)
dsl_error_seconds_total({err="severely errored",loc="near"}, dsl_stat.errors_ses_near)
dsl_error_seconds_total({err="loss of signal",loc="near"}, dsl_stat.errors_loss_near)
dsl_error_seconds_total({err="loss of signal",loc="far"}, dsl_stat.errors_loss_far)
dsl_error_seconds_total({err="unavailable",loc="near"}, dsl_stat.errors_uas_near)
dsl_error_seconds_total({err="unavailable",loc="far"}, dsl_stat.errors_uas_far)
dsl_errors_total({err="header error code error",loc="near"}, dsl_stat.errors_hec_near)
dsl_errors_total({err="header error code error",loc="far"}, dsl_stat.errors_hec_far)
dsl_errors_total({err="non pre-emptive crc error",loc="near"}, dsl_stat.errors_crc_p_near)
dsl_errors_total({err="non pre-emptive crc error",loc="far"}, dsl_stat.errors_crc_p_far)
dsl_errors_total({err="pre-emptive crc error",loc="near"}, dsl_stat.errors_crcp_p_near)
dsl_errors_total({err="pre-emptive crc error",loc="far"}, dsl_stat.errors_crcp_p_far)
end
return { scrape = scrape }
| gpl-2.0 |
adbre/google-diff-match-patch | lua/diff_match_patch.lua | 265 | 73869 | --[[
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser.
* Ported to Lua by Duncan Cross.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
--]]
--[[
-- Lua 5.1 and earlier requires the external BitOp library.
-- This library is built-in from Lua 5.2 and later as 'bit32'.
require 'bit' -- <http://bitop.luajit.org/>
local band, bor, lshift
= bit.band, bit.bor, bit.lshift
--]]
local band, bor, lshift
= bit32.band, bit32.bor, bit32.lshift
local type, setmetatable, ipairs, select
= type, setmetatable, ipairs, select
local unpack, tonumber, error
= unpack, tonumber, error
local strsub, strbyte, strchar, gmatch, gsub
= string.sub, string.byte, string.char, string.gmatch, string.gsub
local strmatch, strfind, strformat
= string.match, string.find, string.format
local tinsert, tremove, tconcat
= table.insert, table.remove, table.concat
local max, min, floor, ceil, abs
= math.max, math.min, math.floor, math.ceil, math.abs
local clock = os.clock
-- Utility functions.
local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]'
local function percentEncode_replace(v)
return strformat('%%%02X', strbyte(v))
end
local function tsplice(t, idx, deletions, ...)
local insertions = select('#', ...)
for i = 1, deletions do
tremove(t, idx)
end
for i = insertions, 1, -1 do
-- do not remove parentheses around select
tinsert(t, idx, (select(i, ...)))
end
end
local function strelement(str, i)
return strsub(str, i, i)
end
local function indexOf(a, b, start)
if (#b == 0) then
return nil
end
return strfind(a, b, start, true)
end
local htmlEncode_pattern = '[&<>\n]'
local htmlEncode_replace = {
['&'] = '&', ['<'] = '<', ['>'] = '>', ['\n'] = '¶<br>'
}
-- Public API Functions
-- (Exported at the end of the script)
local diff_main,
diff_cleanupSemantic,
diff_cleanupEfficiency,
diff_levenshtein,
diff_prettyHtml
local match_main
local patch_make,
patch_toText,
patch_fromText,
patch_apply
--[[
* The data structure representing a diff is an array of tuples:
* {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}}
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
--]]
local DIFF_DELETE = -1
local DIFF_INSERT = 1
local DIFF_EQUAL = 0
-- Number of seconds to map a diff before giving up (0 for infinity).
local Diff_Timeout = 1.0
-- Cost of an empty edit operation in terms of edit characters.
local Diff_EditCost = 4
-- At what point is no match declared (0.0 = perfection, 1.0 = very loose).
local Match_Threshold = 0.5
-- How far to search for a match (0 = exact location, 1000+ = broad match).
-- A match this many characters away from the expected location will add
-- 1.0 to the score (0.0 is a perfect match).
local Match_Distance = 1000
-- When deleting a large block of text (over ~64 characters), how close do
-- the contents have to be to match the expected contents. (0.0 = perfection,
-- 1.0 = very loose). Note that Match_Threshold controls how closely the
-- end points of a delete need to match.
local Patch_DeleteThreshold = 0.5
-- Chunk size for context length.
local Patch_Margin = 4
-- The number of bits in an int.
local Match_MaxBits = 32
function settings(new)
if new then
Diff_Timeout = new.Diff_Timeout or Diff_Timeout
Diff_EditCost = new.Diff_EditCost or Diff_EditCost
Match_Threshold = new.Match_Threshold or Match_Threshold
Match_Distance = new.Match_Distance or Match_Distance
Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold
Patch_Margin = new.Patch_Margin or Patch_Margin
Match_MaxBits = new.Match_MaxBits or Match_MaxBits
else
return {
Diff_Timeout = Diff_Timeout;
Diff_EditCost = Diff_EditCost;
Match_Threshold = Match_Threshold;
Match_Distance = Match_Distance;
Patch_DeleteThreshold = Patch_DeleteThreshold;
Patch_Margin = Patch_Margin;
Match_MaxBits = Match_MaxBits;
}
end
end
-- ---------------------------------------------------------------------------
-- DIFF API
-- ---------------------------------------------------------------------------
-- The private diff functions
local _diff_compute,
_diff_bisect,
_diff_halfMatchI,
_diff_halfMatch,
_diff_cleanupSemanticScore,
_diff_cleanupSemanticLossless,
_diff_cleanupMerge,
_diff_commonPrefix,
_diff_commonSuffix,
_diff_commonOverlap,
_diff_xIndex,
_diff_text1,
_diff_text2,
_diff_toDelta,
_diff_fromDelta
--[[
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} opt_checklines Has no effect in Lua.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
--]]
function diff_main(text1, text2, opt_checklines, opt_deadline)
-- Set a deadline by which time the diff must be complete.
if opt_deadline == nil then
if Diff_Timeout <= 0 then
opt_deadline = 2 ^ 31
else
opt_deadline = clock() + Diff_Timeout
end
end
local deadline = opt_deadline
-- Check for null inputs.
if text1 == nil or text1 == nil then
error('Null inputs. (diff_main)')
end
-- Check for equality (speedup).
if text1 == text2 then
if #text1 > 0 then
return {{DIFF_EQUAL, text1}}
end
return {}
end
-- LUANOTE: Due to the lack of Unicode support, Lua is incapable of
-- implementing the line-mode speedup.
local checklines = false
-- Trim off common prefix (speedup).
local commonlength = _diff_commonPrefix(text1, text2)
local commonprefix
if commonlength > 0 then
commonprefix = strsub(text1, 1, commonlength)
text1 = strsub(text1, commonlength + 1)
text2 = strsub(text2, commonlength + 1)
end
-- Trim off common suffix (speedup).
commonlength = _diff_commonSuffix(text1, text2)
local commonsuffix
if commonlength > 0 then
commonsuffix = strsub(text1, -commonlength)
text1 = strsub(text1, 1, -commonlength - 1)
text2 = strsub(text2, 1, -commonlength - 1)
end
-- Compute the diff on the middle block.
local diffs = _diff_compute(text1, text2, checklines, deadline)
-- Restore the prefix and suffix.
if commonprefix then
tinsert(diffs, 1, {DIFF_EQUAL, commonprefix})
end
if commonsuffix then
diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix}
end
_diff_cleanupMerge(diffs)
return diffs
end
--[[
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupSemantic(diffs)
local changes = false
local equalities = {} -- Stack of indices where equalities are found.
local equalitiesLength = 0 -- Keeping our own length var is faster.
local lastequality = nil
-- Always equal to diffs[equalities[equalitiesLength]][2]
local pointer = 1 -- Index of current position.
-- Number of characters that changed prior to the equality.
local length_insertions1 = 0
local length_deletions1 = 0
-- Number of characters that changed after the equality.
local length_insertions2 = 0
local length_deletions2 = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
length_insertions1 = length_insertions2
length_deletions1 = length_deletions2
length_insertions2 = 0
length_deletions2 = 0
lastequality = diffs[pointer][2]
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_INSERT then
length_insertions2 = length_insertions2 + #(diffs[pointer][2])
else
length_deletions2 = length_deletions2 + #(diffs[pointer][2])
end
-- Eliminate an equality that is smaller or equal to the edits on both
-- sides of it.
if lastequality
and (#lastequality <= max(length_insertions1, length_deletions1))
and (#lastequality <= max(length_insertions2, length_deletions2)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
-- Throw away the previous equality (it needs to be reevaluated).
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
length_insertions1, length_deletions1 = 0, 0 -- Reset the counters.
length_insertions2, length_deletions2 = 0, 0
lastequality = nil
changes = true
end
end
pointer = pointer + 1
end
-- Normalize the diff.
if changes then
_diff_cleanupMerge(diffs)
end
_diff_cleanupSemanticLossless(diffs)
-- Find any overlaps between deletions and insertions.
-- e.g: <del>abcxxx</del><ins>xxxdef</ins>
-- -> <del>abc</del>xxx<ins>def</ins>
-- e.g: <del>xxxabc</del><ins>defxxx</ins>
-- -> <ins>def</ins>xxx<del>abc</del>
-- Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 2
while diffs[pointer] do
if (diffs[pointer - 1][1] == DIFF_DELETE and
diffs[pointer][1] == DIFF_INSERT) then
local deletion = diffs[pointer - 1][2]
local insertion = diffs[pointer][2]
local overlap_length1 = _diff_commonOverlap(deletion, insertion)
local overlap_length2 = _diff_commonOverlap(insertion, deletion)
if (overlap_length1 >= overlap_length2) then
if (overlap_length1 >= #deletion / 2 or
overlap_length1 >= #insertion / 2) then
-- Overlap found. Insert an equality and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(insertion, 1, overlap_length1)})
diffs[pointer - 1][2] =
strsub(deletion, 1, #deletion - overlap_length1)
diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1)
pointer = pointer + 1
end
else
if (overlap_length2 >= #deletion / 2 or
overlap_length2 >= #insertion / 2) then
-- Reverse overlap found.
-- Insert an equality and swap and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(deletion, 1, overlap_length2)})
diffs[pointer - 1] = {DIFF_INSERT,
strsub(insertion, 1, #insertion - overlap_length2)}
diffs[pointer + 1] = {DIFF_DELETE,
strsub(deletion, overlap_length2 + 1)}
pointer = pointer + 1
end
end
pointer = pointer + 1
end
pointer = pointer + 1
end
end
--[[
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupEfficiency(diffs)
local changes = false
-- Stack of indices where equalities are found.
local equalities = {}
-- Keeping our own length var is faster.
local equalitiesLength = 0
-- Always equal to diffs[equalities[equalitiesLength]][2]
local lastequality = nil
-- Index of current position.
local pointer = 1
-- The following four are really booleans but are stored as numbers because
-- they are used at one point like this:
--
-- (pre_ins + pre_del + post_ins + post_del) == 3
--
-- ...i.e. checking that 3 of them are true and 1 of them is false.
-- Is there an insertion operation before the last equality.
local pre_ins = 0
-- Is there a deletion operation before the last equality.
local pre_del = 0
-- Is there an insertion operation after the last equality.
local post_ins = 0
-- Is there a deletion operation after the last equality.
local post_del = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
local diffText = diffs[pointer][2]
if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then
-- Candidate found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
pre_ins, pre_del = post_ins, post_del
lastequality = diffText
else
-- Not a candidate, and can never become one.
equalitiesLength = 0
lastequality = nil
end
post_ins, post_del = 0, 0
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_DELETE then
post_del = 1
else
post_ins = 1
end
--[[
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
--]]
if lastequality and (
(pre_ins+pre_del+post_ins+post_del == 4)
or
(
(#lastequality < Diff_EditCost / 2)
and
(pre_ins+pre_del+post_ins+post_del == 3)
)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
lastequality = nil
if (pre_ins == 1) and (pre_del == 1) then
-- No changes made which could affect previous entry, keep going.
post_ins, post_del = 1, 1
equalitiesLength = 0
else
-- Throw away the previous equality.
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
post_ins, post_del = 0, 0
end
changes = true
end
end
pointer = pointer + 1
end
if changes then
_diff_cleanupMerge(diffs)
end
end
--[[
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {number} Number of changes.
--]]
function diff_levenshtein(diffs)
local levenshtein = 0
local insertions, deletions = 0, 0
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op == DIFF_INSERT) then
insertions = insertions + #data
elseif (op == DIFF_DELETE) then
deletions = deletions + #data
elseif (op == DIFF_EQUAL) then
-- A deletion and an insertion is one substitution.
levenshtein = levenshtein + max(insertions, deletions)
insertions = 0
deletions = 0
end
end
levenshtein = levenshtein + max(insertions, deletions)
return levenshtein
end
--[[
* Convert a diff array into a pretty HTML report.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} HTML representation.
--]]
function diff_prettyHtml(diffs)
local html = {}
for x, diff in ipairs(diffs) do
local op = diff[1] -- Operation (insert, delete, equal)
local data = diff[2] -- Text of change.
local text = gsub(data, htmlEncode_pattern, htmlEncode_replace)
if op == DIFF_INSERT then
html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>'
elseif op == DIFF_DELETE then
html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>'
elseif op == DIFF_EQUAL then
html[x] = '<span>' .. text .. '</span>'
end
end
return tconcat(html)
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE DIFF FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Has no effect in Lua.
* @param {number} deadline Time when the diff should be complete by.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_compute(text1, text2, checklines, deadline)
if #text1 == 0 then
-- Just add some text (speedup).
return {{DIFF_INSERT, text2}}
end
if #text2 == 0 then
-- Just delete some text (speedup).
return {{DIFF_DELETE, text1}}
end
local diffs
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
local i = indexOf(longtext, shorttext)
if i ~= nil then
-- Shorter text is inside the longer text (speedup).
diffs = {
{DIFF_INSERT, strsub(longtext, 1, i - 1)},
{DIFF_EQUAL, shorttext},
{DIFF_INSERT, strsub(longtext, i + #shorttext)}
}
-- Swap insertions for deletions if diff is reversed.
if #text1 > #text2 then
diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE
end
return diffs
end
if #shorttext == 1 then
-- Single character string.
-- After the previous speedup, the character can't be an equality.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
-- Check to see if the problem can be split in two.
do
local
text1_a, text1_b,
text2_a, text2_b,
mid_common = _diff_halfMatch(text1, text2)
if text1_a then
-- A half-match was found, sort out the return data.
-- Send both pairs off for separate processing.
local diffs_a = diff_main(text1_a, text2_a, checklines, deadline)
local diffs_b = diff_main(text1_b, text2_b, checklines, deadline)
-- Merge the results.
local diffs_a_len = #diffs_a
diffs = diffs_a
diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common}
for i, b_diff in ipairs(diffs_b) do
diffs[diffs_a_len + 1 + i] = b_diff
end
return diffs
end
end
return _diff_bisect(text1, text2, deadline)
end
--[[
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisect(text1, text2, deadline)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
local _sub, _element
local max_d = ceil((text1_length + text2_length) / 2)
local v_offset = max_d
local v_length = 2 * max_d
local v1 = {}
local v2 = {}
-- Setting all elements to -1 is faster in Lua than mixing integers and nil.
for x = 0, v_length - 1 do
v1[x] = -1
v2[x] = -1
end
v1[v_offset + 1] = 0
v2[v_offset + 1] = 0
local delta = text1_length - text2_length
-- If the total number of characters is odd, then
-- the front path will collide with the reverse path.
local front = (delta % 2 ~= 0)
-- Offsets for start and end of k loop.
-- Prevents mapping of space beyond the grid.
local k1start = 0
local k1end = 0
local k2start = 0
local k2end = 0
for d = 0, max_d - 1 do
-- Bail out if deadline is reached.
if clock() > deadline then
break
end
-- Walk the front path one step.
for k1 = -d + k1start, d - k1end, 2 do
local k1_offset = v_offset + k1
local x1
if (k1 == -d) or ((k1 ~= d) and
(v1[k1_offset - 1] < v1[k1_offset + 1])) then
x1 = v1[k1_offset + 1]
else
x1 = v1[k1_offset - 1] + 1
end
local y1 = x1 - k1
while (x1 <= text1_length) and (y1 <= text2_length)
and (strelement(text1, x1) == strelement(text2, y1)) do
x1 = x1 + 1
y1 = y1 + 1
end
v1[k1_offset] = x1
if x1 > text1_length + 1 then
-- Ran off the right of the graph.
k1end = k1end + 2
elseif y1 > text2_length + 1 then
-- Ran off the bottom of the graph.
k1start = k1start + 2
elseif front then
local k2_offset = v_offset + delta - k1
if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then
-- Mirror x2 onto top-left coordinate system.
local x2 = text1_length - v2[k2_offset] + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
-- Walk the reverse path one step.
for k2 = -d + k2start, d - k2end, 2 do
local k2_offset = v_offset + k2
local x2
if (k2 == -d) or ((k2 ~= d) and
(v2[k2_offset - 1] < v2[k2_offset + 1])) then
x2 = v2[k2_offset + 1]
else
x2 = v2[k2_offset - 1] + 1
end
local y2 = x2 - k2
while (x2 <= text1_length) and (y2 <= text2_length)
and (strelement(text1, -x2) == strelement(text2, -y2)) do
x2 = x2 + 1
y2 = y2 + 1
end
v2[k2_offset] = x2
if x2 > text1_length + 1 then
-- Ran off the left of the graph.
k2end = k2end + 2
elseif y2 > text2_length + 1 then
-- Ran off the top of the graph.
k2start = k2start + 2
elseif not front then
local k1_offset = v_offset + delta - k2
if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then
local x1 = v1[k1_offset]
local y1 = v_offset + x1 - k1_offset
-- Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2 + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
end
-- Diff took too long and hit the deadline or
-- number of diffs equals number of characters, no commonality at all.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
--[[
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisectSplit(text1, text2, x, y, deadline)
local text1a = strsub(text1, 1, x - 1)
local text2a = strsub(text2, 1, y - 1)
local text1b = strsub(text1, x)
local text2b = strsub(text2, y)
-- Compute both diffs serially.
local diffs = diff_main(text1a, text2a, false, deadline)
local diffsb = diff_main(text1b, text2b, false, deadline)
local diffs_len = #diffs
for i, v in ipairs(diffsb) do
diffs[diffs_len + i] = v
end
return diffs
end
--[[
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
--]]
function _diff_commonPrefix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1))
then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerstart = 1
while (pointermin < pointermid) do
if (strsub(text1, pointerstart, pointermid)
== strsub(text2, pointerstart, pointermid)) then
pointermin = pointermid
pointerstart = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
--]]
function _diff_commonSuffix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0)
or (strbyte(text1, -1) ~= strbyte(text2, -1)) then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerend = 1
while (pointermin < pointermid) do
if (strsub(text1, -pointermid, -pointerend)
== strsub(text2, -pointermid, -pointerend)) then
pointermin = pointermid
pointerend = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
--]]
function _diff_commonOverlap(text1, text2)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
-- Eliminate the null case.
if text1_length == 0 or text2_length == 0 then
return 0
end
-- Truncate the longer string.
if text1_length > text2_length then
text1 = strsub(text1, text1_length - text2_length + 1)
elseif text1_length < text2_length then
text2 = strsub(text2, 1, text1_length)
end
local text_length = min(text1_length, text2_length)
-- Quick check for the worst case.
if text1 == text2 then
return text_length
end
-- Start by looking for a single character match
-- and increase length until no match is found.
-- Performance analysis: http://neil.fraser.name/news/2010/11/04/
local best = 0
local length = 1
while true do
local pattern = strsub(text1, text_length - length + 1)
local found = strfind(text2, pattern, 1, true)
if found == nil then
return best
end
length = length + found - 1
if found == 1 or strsub(text1, text_length - length + 1) ==
strsub(text2, 1, length) then
best = length
length = length + 1
end
end
end
--[[
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* This speedup can produce non-minimal diffs.
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {?Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatchI(longtext, shorttext, i)
-- Start with a 1/4 length substring at position i as a seed.
local seed = strsub(longtext, i, i + floor(#longtext / 4))
local j = 0 -- LUANOTE: do not change to 1, was originally -1
local best_common = ''
local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b
while true do
j = indexOf(shorttext, seed, j + 1)
if (j == nil) then
break
end
local prefixLength = _diff_commonPrefix(strsub(longtext, i),
strsub(shorttext, j))
local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1),
strsub(shorttext, 1, j - 1))
if #best_common < suffixLength + prefixLength then
best_common = strsub(shorttext, j - suffixLength, j - 1)
.. strsub(shorttext, j, j + prefixLength - 1)
best_longtext_a = strsub(longtext, 1, i - suffixLength - 1)
best_longtext_b = strsub(longtext, i + prefixLength)
best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1)
best_shorttext_b = strsub(shorttext, j + prefixLength)
end
end
if #best_common * 2 >= #longtext then
return {best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common}
else
return nil
end
end
--[[
* Do the two texts share a substring which is at least half the length of the
* longer text?
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {?Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatch(text1, text2)
if Diff_Timeout <= 0 then
-- Don't risk returning a non-optimal diff if we have unlimited time.
return nil
end
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
if (#longtext < 4) or (#shorttext * 2 < #longtext) then
return nil -- Pointless.
end
-- First check if the second quarter is the seed for a half-match.
local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4))
-- Check again based on the third quarter.
local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2))
local hm
if not hm1 and not hm2 then
return nil
elseif not hm2 then
hm = hm1
elseif not hm1 then
hm = hm2
else
-- Both matched. Select the longest.
hm = (#hm1[5] > #hm2[5]) and hm1 or hm2
end
-- A half-match was found, sort out the return data.
local text1_a, text1_b, text2_a, text2_b
if (#text1 > #text2) then
text1_a, text1_b = hm[1], hm[2]
text2_a, text2_b = hm[3], hm[4]
else
text2_a, text2_b = hm[1], hm[2]
text1_a, text1_b = hm[3], hm[4]
end
local mid_common = hm[5]
return text1_a, text1_b, text2_a, text2_b, mid_common
end
--[[
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
--]]
function _diff_cleanupSemanticScore(one, two)
if (#one == 0) or (#two == 0) then
-- Edges are the best.
return 6
end
-- Each port of this function behaves slightly differently due to
-- subtle differences in each language's definition of things like
-- 'whitespace'. Since this function's purpose is largely cosmetic,
-- the choice has been made to use each language's native features
-- rather than force total conformity.
local char1 = strsub(one, -1)
local char2 = strsub(two, 1, 1)
local nonAlphaNumeric1 = strmatch(char1, '%W')
local nonAlphaNumeric2 = strmatch(char2, '%W')
local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s')
local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s')
local lineBreak1 = whitespace1 and strmatch(char1, '%c')
local lineBreak2 = whitespace2 and strmatch(char2, '%c')
local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$')
local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n')
if blankLine1 or blankLine2 then
-- Five points for blank lines.
return 5
elseif lineBreak1 or lineBreak2 then
-- Four points for line breaks.
return 4
elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then
-- Three points for end of sentences.
return 3
elseif whitespace1 or whitespace2 then
-- Two points for whitespace.
return 2
elseif nonAlphaNumeric1 or nonAlphaNumeric2 then
-- One point for non-alphanumeric.
return 1
end
return 0
end
--[[
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupSemanticLossless(diffs)
local pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while diffs[pointer + 1] do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local equality1 = prevDiff[2]
local edit = diff[2]
local equality2 = nextDiff[2]
-- First, shift the edit as far left as possible.
local commonOffset = _diff_commonSuffix(equality1, edit)
if commonOffset > 0 then
local commonString = strsub(edit, -commonOffset)
equality1 = strsub(equality1, 1, -commonOffset - 1)
edit = commonString .. strsub(edit, 1, -commonOffset - 1)
equality2 = commonString .. equality2
end
-- Second, step character by character right, looking for the best fit.
local bestEquality1 = equality1
local bestEdit = edit
local bestEquality2 = equality2
local bestScore = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
while strbyte(edit, 1) == strbyte(equality2, 1) do
equality1 = equality1 .. strsub(edit, 1, 1)
edit = strsub(edit, 2) .. strsub(equality2, 1, 1)
equality2 = strsub(equality2, 2)
local score = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
-- The >= encourages trailing rather than leading whitespace on edits.
if score >= bestScore then
bestScore = score
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
end
end
if prevDiff[2] ~= bestEquality1 then
-- We have an improvement, save it back to the diff.
if #bestEquality1 > 0 then
diffs[pointer - 1][2] = bestEquality1
else
tremove(diffs, pointer - 1)
pointer = pointer - 1
end
diffs[pointer][2] = bestEdit
if #bestEquality2 > 0 then
diffs[pointer + 1][2] = bestEquality2
else
tremove(diffs, pointer + 1, 1)
pointer = pointer - 1
end
end
end
pointer = pointer + 1
end
end
--[[
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupMerge(diffs)
diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end.
local pointer = 1
local count_delete, count_insert = 0, 0
local text_delete, text_insert = '', ''
local commonlength
while diffs[pointer] do
local diff_type = diffs[pointer][1]
if diff_type == DIFF_INSERT then
count_insert = count_insert + 1
text_insert = text_insert .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_DELETE then
count_delete = count_delete + 1
text_delete = text_delete .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_EQUAL then
-- Upon reaching an equality, check for prior redundancies.
if count_delete + count_insert > 1 then
if (count_delete > 0) and (count_insert > 0) then
-- Factor out any common prefixies.
commonlength = _diff_commonPrefix(text_insert, text_delete)
if commonlength > 0 then
local back_pointer = pointer - count_delete - count_insert
if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL)
then
diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2]
.. strsub(text_insert, 1, commonlength)
else
tinsert(diffs, 1,
{DIFF_EQUAL, strsub(text_insert, 1, commonlength)})
pointer = pointer + 1
end
text_insert = strsub(text_insert, commonlength + 1)
text_delete = strsub(text_delete, commonlength + 1)
end
-- Factor out any common suffixies.
commonlength = _diff_commonSuffix(text_insert, text_delete)
if commonlength ~= 0 then
diffs[pointer][2] =
strsub(text_insert, -commonlength) .. diffs[pointer][2]
text_insert = strsub(text_insert, 1, -commonlength - 1)
text_delete = strsub(text_delete, 1, -commonlength - 1)
end
end
-- Delete the offending records and add the merged ones.
if count_delete == 0 then
tsplice(diffs, pointer - count_insert,
count_insert, {DIFF_INSERT, text_insert})
elseif count_insert == 0 then
tsplice(diffs, pointer - count_delete,
count_delete, {DIFF_DELETE, text_delete})
else
tsplice(diffs, pointer - count_delete - count_insert,
count_delete + count_insert,
{DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert})
end
pointer = pointer - count_delete - count_insert
+ (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1
elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then
-- Merge this equality with the previous one.
diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2]
tremove(diffs, pointer)
else
pointer = pointer + 1
end
count_insert, count_delete = 0, 0
text_delete, text_insert = '', ''
end
end
if diffs[#diffs][2] == '' then
diffs[#diffs] = nil -- Remove the dummy entry at the end.
end
-- Second pass: look for single edits surrounded on both sides by equalities
-- which can be shifted sideways to eliminate an equality.
-- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
local changes = false
pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while pointer < #diffs do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local currentText = diff[2]
local prevText = prevDiff[2]
local nextText = nextDiff[2]
if strsub(currentText, -#prevText) == prevText then
-- Shift the edit over the previous equality.
diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1)
nextDiff[2] = prevText .. nextDiff[2]
tremove(diffs, pointer - 1)
changes = true
elseif strsub(currentText, 1, #nextText) == nextText then
-- Shift the edit over the next equality.
prevDiff[2] = prevText .. nextText
diff[2] = strsub(currentText, #nextText + 1) .. nextText
tremove(diffs, pointer + 1)
changes = true
end
end
pointer = pointer + 1
end
-- If shifts were made, the diff needs reordering and another shift sweep.
if changes then
-- LUANOTE: no return value, but necessary to use 'return' to get
-- tail calls.
return _diff_cleanupMerge(diffs)
end
end
--[[
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
--]]
function _diff_xIndex(diffs, loc)
local chars1 = 1
local chars2 = 1
local last_chars1 = 1
local last_chars2 = 1
local x
for _x, diff in ipairs(diffs) do
x = _x
if diff[1] ~= DIFF_INSERT then -- Equality or deletion.
chars1 = chars1 + #diff[2]
end
if diff[1] ~= DIFF_DELETE then -- Equality or insertion.
chars2 = chars2 + #diff[2]
end
if chars1 > loc then -- Overshot the location.
break
end
last_chars1 = chars1
last_chars2 = chars2
end
-- Was the location deleted?
if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then
return last_chars2
end
-- Add the remaining character length.
return last_chars2 + (loc - last_chars1)
end
--[[
* Compute and return the source text (all equalities and deletions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Source text.
--]]
function _diff_text1(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_INSERT then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Compute and return the destination text (all equalities and insertions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Destination text.
--]]
function _diff_text2(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_DELETE then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Delta text.
--]]
function _diff_toDelta(diffs)
local text = {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if op == DIFF_INSERT then
text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace)
elseif op == DIFF_DELETE then
text[x] = '-' .. #data
elseif op == DIFF_EQUAL then
text[x] = '=' .. #data
end
end
return tconcat(text, '\t')
end
--[[
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @throws {Errorend If invalid input.
--]]
function _diff_fromDelta(text1, delta)
local diffs = {}
local diffsLength = 0 -- Keeping our own length var is faster
local pointer = 1 -- Cursor in text1
for token in gmatch(delta, '[^\t]+') do
-- Each token begins with a one character parameter which specifies the
-- operation of this token (delete, insert, equality).
local tokenchar, param = strsub(token, 1, 1), strsub(token, 2)
if (tokenchar == '+') then
local invalidDecode = false
local decoded = gsub(param, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in _diff_fromDelta: ' .. param)
end
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_INSERT, decoded}
elseif (tokenchar == '-') or (tokenchar == '=') then
local n = tonumber(param)
if (n == nil) or (n < 0) then
error('Invalid number in _diff_fromDelta: ' .. param)
end
local text = strsub(text1, pointer, pointer + n - 1)
pointer = pointer + n
if (tokenchar == '=') then
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_EQUAL, text}
else
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_DELETE, text}
end
else
error('Invalid diff operation in _diff_fromDelta: ' .. token)
end
end
if (pointer ~= #text1 + 1) then
error('Delta length (' .. (pointer - 1)
.. ') does not equal source text length (' .. #text1 .. ').')
end
return diffs
end
-- ---------------------------------------------------------------------------
-- MATCH API
-- ---------------------------------------------------------------------------
local _match_bitap, _match_alphabet
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
--]]
function match_main(text, pattern, loc)
-- Check for null inputs.
if text == nil or pattern == nil or loc == nil then
error('Null inputs. (match_main)')
end
if text == pattern then
-- Shortcut (potentially not guaranteed by the algorithm)
return 1
elseif #text == 0 then
-- Nothing to match.
return -1
end
loc = max(1, min(loc, #text))
if strsub(text, loc, loc + #pattern - 1) == pattern then
-- Perfect match at the perfect spot! (Includes case of null pattern)
return loc
else
-- Do a fuzzy compare.
return _match_bitap(text, pattern, loc)
end
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE MATCH FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {Object} Hash of character locations.
* @private
--]]
function _match_alphabet(pattern)
local s = {}
local i = 0
for c in gmatch(pattern, '.') do
s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1))
i = i + 1
end
return s
end
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
--]]
function _match_bitap(text, pattern, loc)
if #pattern > Match_MaxBits then
error('Pattern too long.')
end
-- Initialise the alphabet.
local s = _match_alphabet(pattern)
--[[
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
--]]
local function _match_bitapScore(e, x)
local accuracy = e / #pattern
local proximity = abs(loc - x)
if (Match_Distance == 0) then
-- Dodge divide by zero error.
return (proximity == 0) and 1 or accuracy
end
return accuracy + (proximity / Match_Distance)
end
-- Highest score beyond which we give up.
local score_threshold = Match_Threshold
-- Is there a nearby exact match? (speedup)
local best_loc = indexOf(text, pattern, loc)
if best_loc then
score_threshold = min(_match_bitapScore(0, best_loc), score_threshold)
-- LUANOTE: Ideally we'd also check from the other direction, but Lua
-- doesn't have an efficent lastIndexOf function.
end
-- Initialise the bit arrays.
local matchmask = lshift(1, #pattern - 1)
best_loc = -1
local bin_min, bin_mid
local bin_max = #pattern + #text
local last_rd
for d = 0, #pattern - 1, 1 do
-- Scan for the best match; each iteration allows for one more error.
-- Run a binary search to determine how far from 'loc' we can stray at this
-- error level.
bin_min = 0
bin_mid = bin_max
while (bin_min < bin_mid) do
if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then
bin_min = bin_mid
else
bin_max = bin_mid
end
bin_mid = floor(bin_min + (bin_max - bin_min) / 2)
end
-- Use the result from this iteration as the maximum for the next.
bin_max = bin_mid
local start = max(1, loc - bin_mid + 1)
local finish = min(loc + bin_mid, #text) + #pattern
local rd = {}
for j = start, finish do
rd[j] = 0
end
rd[finish + 1] = lshift(1, d) - 1
for j = finish, start, -1 do
local charMatch = s[strsub(text, j - 1, j - 1)] or 0
if (d == 0) then -- First pass: exact match.
rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch)
else
-- Subsequent passes: fuzzy match.
-- Functions instead of operators make this hella messy.
rd[j] = bor(
band(
bor(
lshift(rd[j + 1], 1),
1
),
charMatch
),
bor(
bor(
lshift(bor(last_rd[j + 1], last_rd[j]), 1),
1
),
last_rd[j + 1]
)
)
end
if (band(rd[j], matchmask) ~= 0) then
local score = _match_bitapScore(d, j - 1)
-- This match will almost certainly be better than any existing match.
-- But check anyway.
if (score <= score_threshold) then
-- Told you so.
score_threshold = score
best_loc = j - 1
if (best_loc > loc) then
-- When passing loc, don't exceed our current distance from loc.
start = max(1, loc * 2 - best_loc)
else
-- Already passed loc, downhill from here on in.
break
end
end
end
end
-- No hope for a (better) match at greater error levels.
if (_match_bitapScore(d + 1, loc) > score_threshold) then
break
end
last_rd = rd
end
return best_loc
end
-- -----------------------------------------------------------------------------
-- PATCH API
-- -----------------------------------------------------------------------------
local _patch_addContext,
_patch_deepCopy,
_patch_addPadding,
_patch_splitMax,
_patch_appendText,
_new_patch_obj
--[[
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for
* text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function patch_make(a, opt_b, opt_c)
local text1, diffs
local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c)
if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then
-- Method 1: text1, text2
-- Compute diffs from text1 and text2.
text1 = a
diffs = diff_main(text1, opt_b, true)
if (#diffs > 2) then
diff_cleanupSemantic(diffs)
diff_cleanupEfficiency(diffs)
end
elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then
-- Method 2: diffs
-- Compute text1 from diffs.
diffs = a
text1 = _diff_text1(diffs)
elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then
-- Method 3: text1, diffs
text1 = a
diffs = opt_b
elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table')
then
-- Method 4: text1, text2, diffs
-- text2 is not used.
text1 = a
diffs = opt_c
else
error('Unknown call format to patch_make.')
end
if (diffs[1] == nil) then
return {} -- Get rid of the null case.
end
local patches = {}
local patch = _new_patch_obj()
local patchDiffLength = 0 -- Keeping our own length var is faster.
local char_count1 = 0 -- Number of characters into the text1 string.
local char_count2 = 0 -- Number of characters into the text2 string.
-- Start with text1 (prepatch_text) and apply the diffs until we arrive at
-- text2 (postpatch_text). We recreate the patches one by one to determine
-- context info.
local prepatch_text, postpatch_text = text1, text1
for x, diff in ipairs(diffs) do
local diff_type, diff_text = diff[1], diff[2]
if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then
-- A new patch starts here.
patch.start1 = char_count1 + 1
patch.start2 = char_count2 + 1
end
if (diff_type == DIFF_INSERT) then
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length2 = patch.length2 + #diff_text
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. diff_text .. strsub(postpatch_text, char_count2 + 1)
elseif (diff_type == DIFF_DELETE) then
patch.length1 = patch.length1 + #diff_text
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. strsub(postpatch_text, char_count2 + #diff_text + 1)
elseif (diff_type == DIFF_EQUAL) then
if (#diff_text <= Patch_Margin * 2)
and (patchDiffLength ~= 0) and (#diffs ~= x) then
-- Small equality inside a patch.
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length1 = patch.length1 + #diff_text
patch.length2 = patch.length2 + #diff_text
elseif (#diff_text >= Patch_Margin * 2) then
-- Time for a new patch.
if (patchDiffLength ~= 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
patch = _new_patch_obj()
patchDiffLength = 0
-- Unlike Unidiff, our patch lists have a rolling context.
-- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
-- Update prepatch text & pos to reflect the application of the
-- just completed patch.
prepatch_text = postpatch_text
char_count1 = char_count2
end
end
end
-- Update the current character count.
if (diff_type ~= DIFF_INSERT) then
char_count1 = char_count1 + #diff_text
end
if (diff_type ~= DIFF_DELETE) then
char_count2 = char_count2 + #diff_text
end
end
-- Pick up the leftover patch if not empty.
if (patchDiffLength > 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
end
return patches
end
--[[
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @param {string} text Old text.
* @return {Array.<string|Array.<boolean>>} Two return values, the
* new text and an array of boolean values.
--]]
function patch_apply(patches, text)
if patches[1] == nil then
return text, {}
end
-- Deep copy the patches so that no changes are made to originals.
patches = _patch_deepCopy(patches)
local nullPadding = _patch_addPadding(patches)
text = nullPadding .. text .. nullPadding
_patch_splitMax(patches)
-- delta keeps track of the offset between the expected and actual location
-- of the previous patch. If there are patches expected at positions 10 and
-- 20, but the first patch was found at 12, delta is 2 and the second patch
-- has an effective expected position of 22.
local delta = 0
local results = {}
for x, patch in ipairs(patches) do
local expected_loc = patch.start2 + delta
local text1 = _diff_text1(patch.diffs)
local start_loc
local end_loc = -1
if #text1 > Match_MaxBits then
-- _patch_splitMax will only provide an oversized pattern in
-- the case of a monster delete.
start_loc = match_main(text,
strsub(text1, 1, Match_MaxBits), expected_loc)
if start_loc ~= -1 then
end_loc = match_main(text, strsub(text1, -Match_MaxBits),
expected_loc + #text1 - Match_MaxBits)
if end_loc == -1 or start_loc >= end_loc then
-- Can't find valid trailing context. Drop this patch.
start_loc = -1
end
end
else
start_loc = match_main(text, text1, expected_loc)
end
if start_loc == -1 then
-- No match found. :(
results[x] = false
-- Subtract the delta for this failed patch from subsequent patches.
delta = delta - patch.length2 - patch.length1
else
-- Found a match. :)
results[x] = true
delta = start_loc - expected_loc
local text2
if end_loc == -1 then
text2 = strsub(text, start_loc, start_loc + #text1 - 1)
else
text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1)
end
if text1 == text2 then
-- Perfect match, just shove the replacement text in.
text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs)
.. strsub(text, start_loc + #text1)
else
-- Imperfect match. Run a diff to get a framework of equivalent
-- indices.
local diffs = diff_main(text1, text2, false)
if (#text1 > Match_MaxBits)
and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then
-- The end points match, but the content is unacceptably bad.
results[x] = false
else
_diff_cleanupSemanticLossless(diffs)
local index1 = 1
local index2
for y, mod in ipairs(patch.diffs) do
if mod[1] ~= DIFF_EQUAL then
index2 = _diff_xIndex(diffs, index1)
end
if mod[1] == DIFF_INSERT then
text = strsub(text, 1, start_loc + index2 - 2)
.. mod[2] .. strsub(text, start_loc + index2 - 1)
elseif mod[1] == DIFF_DELETE then
text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text,
start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1))
end
if mod[1] ~= DIFF_DELETE then
index1 = index1 + #mod[2]
end
end
end
end
end
end
-- Strip the padding off.
text = strsub(text, #nullPadding + 1, -#nullPadding - 1)
return text, results
end
--[[
* Take a list of patches and return a textual representation.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} Text representation of patches.
--]]
function patch_toText(patches)
local text = {}
for x, patch in ipairs(patches) do
_patch_appendText(patch, text)
end
return tconcat(text)
end
--[[
* Parse a textual representation of patches and return a list of patch objects.
* @param {string} textline Text representation of patches.
* @return {Array.<_new_patch_obj>} Array of patch objects.
* @throws {Error} If invalid input.
--]]
function patch_fromText(textline)
local patches = {}
if (#textline == 0) then
return patches
end
local text = {}
for line in gmatch(textline, '([^\n]*)') do
text[#text + 1] = line
end
local textPointer = 1
while (textPointer <= #text) do
local start1, length1, start2, length2
= strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$')
if (start1 == nil) then
error('Invalid patch string: "' .. text[textPointer] .. '"')
end
local patch = _new_patch_obj()
patches[#patches + 1] = patch
start1 = tonumber(start1)
length1 = tonumber(length1) or 1
if (length1 == 0) then
start1 = start1 + 1
end
patch.start1 = start1
patch.length1 = length1
start2 = tonumber(start2)
length2 = tonumber(length2) or 1
if (length2 == 0) then
start2 = start2 + 1
end
patch.start2 = start2
patch.length2 = length2
textPointer = textPointer + 1
while true do
local line = text[textPointer]
if (line == nil) then
break
end
local sign; sign, line = strsub(line, 1, 1), strsub(line, 2)
local invalidDecode = false
local decoded = gsub(line, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in patch_fromText: ' .. line)
end
line = decoded
if (sign == '-') then
-- Deletion.
patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line}
elseif (sign == '+') then
-- Insertion.
patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line}
elseif (sign == ' ') then
-- Minor equality.
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line}
elseif (sign == '@') then
-- Start of next patch.
break
elseif (sign == '') then
-- Blank line? Whatever.
else
-- WTF?
error('Invalid patch mode "' .. sign .. '" in: ' .. line)
end
textPointer = textPointer + 1
end
end
return patches
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE PATCH FUNCTIONS
-- ---------------------------------------------------------------------------
local patch_meta = {
__tostring = function(patch)
local buf = {}
_patch_appendText(patch, buf)
return tconcat(buf)
end
}
--[[
* Class representing one patch operation.
* @constructor
--]]
function _new_patch_obj()
return setmetatable({
--[[ @type {Array.<Array.<number|string>>} ]]
diffs = {};
--[[ @type {?number} ]]
start1 = 1; -- nil;
--[[ @type {?number} ]]
start2 = 1; -- nil;
--[[ @type {number} ]]
length1 = 0;
--[[ @type {number} ]]
length2 = 0;
}, patch_meta)
end
--[[
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {_new_patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
--]]
function _patch_addContext(patch, text)
if (#text == 0) then
return
end
local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1)
local padding = 0
-- LUANOTE: Lua's lack of a lastIndexOf function results in slightly
-- different logic here than in other language ports.
-- Look for the first two matches of pattern in text. If two are found,
-- increase the pattern length.
local firstMatch = indexOf(text, pattern)
local secondMatch = nil
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
end
while (#pattern == 0 or secondMatch ~= nil)
and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do
padding = padding + Patch_Margin
pattern = strsub(text, max(1, patch.start2 - padding),
patch.start2 + patch.length1 - 1 + padding)
firstMatch = indexOf(text, pattern)
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
else
secondMatch = nil
end
end
-- Add one chunk for good luck.
padding = padding + Patch_Margin
-- Add the prefix.
local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1)
if (#prefix > 0) then
tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix})
end
-- Add the suffix.
local suffix = strsub(text, patch.start2 + patch.length1,
patch.start2 + patch.length1 - 1 + padding)
if (#suffix > 0) then
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix}
end
-- Roll back the start points.
patch.start1 = patch.start1 - #prefix
patch.start2 = patch.start2 - #prefix
-- Extend the lengths.
patch.length1 = patch.length1 + #prefix + #suffix
patch.length2 = patch.length2 + #prefix + #suffix
end
--[[
* Given an array of patches, return another array that is identical.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function _patch_deepCopy(patches)
local patchesCopy = {}
for x, patch in ipairs(patches) do
local patchCopy = _new_patch_obj()
local diffsCopy = {}
for i, diff in ipairs(patch.diffs) do
diffsCopy[i] = {diff[1], diff[2]}
end
patchCopy.diffs = diffsCopy
patchCopy.start1 = patch.start1
patchCopy.start2 = patch.start2
patchCopy.length1 = patch.length1
patchCopy.length2 = patch.length2
patchesCopy[x] = patchCopy
end
return patchesCopy
end
--[[
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} The padding string added to each side.
--]]
function _patch_addPadding(patches)
local paddingLength = Patch_Margin
local nullPadding = ''
for x = 1, paddingLength do
nullPadding = nullPadding .. strchar(x)
end
-- Bump all the patches forward.
for x, patch in ipairs(patches) do
patch.start1 = patch.start1 + paddingLength
patch.start2 = patch.start2 + paddingLength
end
-- Add some padding on start of first diff.
local patch = patches[1]
local diffs = patch.diffs
local firstDiff = diffs[1]
if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
tinsert(diffs, 1, {DIFF_EQUAL, nullPadding})
patch.start1 = patch.start1 - paddingLength -- Should be 0.
patch.start2 = patch.start2 - paddingLength -- Should be 0.
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #firstDiff[2]) then
-- Grow first equality.
local extraLength = paddingLength - #firstDiff[2]
firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2]
patch.start1 = patch.start1 - extraLength
patch.start2 = patch.start2 - extraLength
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
-- Add some padding on end of last diff.
patch = patches[#patches]
diffs = patch.diffs
local lastDiff = diffs[#diffs]
if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding}
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #lastDiff[2]) then
-- Grow last equality.
local extraLength = paddingLength - #lastDiff[2]
lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength)
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
return nullPadding
end
--[[
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
--]]
function _patch_splitMax(patches)
local patch_size = Match_MaxBits
local x = 1
while true do
local patch = patches[x]
if patch == nil then
return
end
if patch.length1 > patch_size then
local bigpatch = patch
-- Remove the big old patch.
tremove(patches, x)
x = x - 1
local start1 = bigpatch.start1
local start2 = bigpatch.start2
local precontext = ''
while bigpatch.diffs[1] do
-- Create one of several smaller patches.
local patch = _new_patch_obj()
local empty = true
patch.start1 = start1 - #precontext
patch.start2 = start2 - #precontext
if precontext ~= '' then
patch.length1, patch.length2 = #precontext, #precontext
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext}
end
while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do
local diff_type = bigpatch.diffs[1][1]
local diff_text = bigpatch.diffs[1][2]
if (diff_type == DIFF_INSERT) then
-- Insertions are harmless.
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1]
tremove(bigpatch.diffs, 1)
empty = false
elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1)
and (patch.diffs[1][1] == DIFF_EQUAL)
and (#diff_text > 2 * patch_size) then
-- This is a large deletion. Let it pass in one chunk.
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
empty = false
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
tremove(bigpatch.diffs, 1)
else
-- Deletion or equality.
-- Only take as much as we can stomach.
diff_text = strsub(diff_text, 1,
patch_size - patch.length1 - Patch_Margin)
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
if (diff_type == DIFF_EQUAL) then
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
else
empty = false
end
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
if (diff_text == bigpatch.diffs[1][2]) then
tremove(bigpatch.diffs, 1)
else
bigpatch.diffs[1][2]
= strsub(bigpatch.diffs[1][2], #diff_text + 1)
end
end
end
-- Compute the head context for the next patch.
precontext = _diff_text2(patch.diffs)
precontext = strsub(precontext, -Patch_Margin)
-- Append the end context for this patch.
local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin)
if postcontext ~= '' then
patch.length1 = patch.length1 + #postcontext
patch.length2 = patch.length2 + #postcontext
if patch.diffs[1]
and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then
patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2]
.. postcontext
else
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext}
end
end
if not empty then
x = x + 1
tinsert(patches, x, patch)
end
end
end
x = x + 1
end
end
--[[
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* @return {string} The GNU diff string.
--]]
function _patch_appendText(patch, text)
local coords1, coords2
local length1, length2 = patch.length1, patch.length2
local start1, start2 = patch.start1, patch.start2
local diffs = patch.diffs
if length1 == 1 then
coords1 = start1
else
coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1
end
if length2 == 1 then
coords2 = start2
else
coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2
end
text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n'
local op
-- Escape the body of the patch with %xx notation.
for x, diff in ipairs(patch.diffs) do
local diff_type = diff[1]
if diff_type == DIFF_INSERT then
op = '+'
elseif diff_type == DIFF_DELETE then
op = '-'
elseif diff_type == DIFF_EQUAL then
op = ' '
end
text[#text + 1] = op
.. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace)
.. '\n'
end
return text
end
-- Expose the API
local _M = {}
_M.DIFF_DELETE = DIFF_DELETE
_M.DIFF_INSERT = DIFF_INSERT
_M.DIFF_EQUAL = DIFF_EQUAL
_M.diff_main = diff_main
_M.diff_cleanupSemantic = diff_cleanupSemantic
_M.diff_cleanupEfficiency = diff_cleanupEfficiency
_M.diff_levenshtein = diff_levenshtein
_M.diff_prettyHtml = diff_prettyHtml
_M.match_main = match_main
_M.patch_make = patch_make
_M.patch_toText = patch_toText
_M.patch_fromText = patch_fromText
_M.patch_apply = patch_apply
-- Expose some non-API functions as well, for testing purposes etc.
_M.diff_commonPrefix = _diff_commonPrefix
_M.diff_commonSuffix = _diff_commonSuffix
_M.diff_commonOverlap = _diff_commonOverlap
_M.diff_halfMatch = _diff_halfMatch
_M.diff_bisect = _diff_bisect
_M.diff_cleanupMerge = _diff_cleanupMerge
_M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless
_M.diff_text1 = _diff_text1
_M.diff_text2 = _diff_text2
_M.diff_toDelta = _diff_toDelta
_M.diff_fromDelta = _diff_fromDelta
_M.diff_xIndex = _diff_xIndex
_M.match_alphabet = _match_alphabet
_M.match_bitap = _match_bitap
_M.new_patch_obj = _new_patch_obj
_M.patch_addContext = _patch_addContext
_M.patch_splitMax = _patch_splitMax
_M.patch_addPadding = _patch_addPadding
_M.settings = settings
return _M
| apache-2.0 |
starlightknight/darkstar | scripts/globals/mobskills/deadeye.lua | 12 | 1270 | ---------------------------------------------
-- Deadeye
-- Family: Qiqurn
-- Description: Lowers the defense and magical defense of enemies within range.
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown
-- Notes: Used only by certain Notorious Monsters. Strong dsp.effect.
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local defDown = false
local mDefDown = false
defDown = MobStatusEffectMove(mob, target, dsp.effect.DEFENSE_DOWN, 50, 0, 120)
mDefDown = MobStatusEffectMove(mob, target, dsp.effect.MAGIC_DEF_DOWN, 50, 0, 120)
skill:setMsg(dsp.msg.basic.SKILL_ENFEEB_IS)
-- display defense down first, else magic defense down
if (defDown == dsp.msg.basic.SKILL_ENFEEB_IS) then
typeEffect = dsp.effect.DEFENSE_DOWN
elseif (mDefDown == dsp.msg.basic.NFEEB_IS) then
typeEffect = dsp.effect.MAGIC_DEF_DOWN
else
skill:setMsg(dsp.msg.basic.SKILL_MISS)
end
return typeEffect
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Windurst_Woods/npcs/Gioh_Ajihri.lua | 28 | 2994 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Gioh Ajihri
-- Starts & Finishes Repeatable Quest: Twinstone Bonding
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
GiohAijhriSpokenTo = player:getVar("GiohAijhriSpokenTo");
NeedToZone = player:needToZone();
if (GiohAijhriSpokenTo == 1 and NeedToZone == false) then
count = trade:getItemCount();
TwinstoneEarring = trade:hasItemQty(13360,1);
if (TwinstoneEarring == true and count == 1) then
player:startEvent(0x01ea);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING);
Fame = player:getFameLevel(WINDURST);
if (TwinstoneBonding == QUEST_COMPLETED) then
if (player:needToZone()) then
player:startEvent(0x01eb,0,13360);
else
player:startEvent(0x01e8,0,13360);
end
elseif (TwinstoneBonding == QUEST_ACCEPTED) then
player:startEvent(0x01e8,0,13360);
elseif (TwinstoneBonding == QUEST_AVAILABLE and Fame >= 2) then
player:startEvent(0x01e7,0,13360);
else
player:startEvent(0x01a8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x01e7) then
player:addQuest(WINDURST,TWINSTONE_BONDING);
player:setVar("GiohAijhriSpokenTo",1);
elseif (csid == 0x01ea) then
TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING);
player:tradeComplete();
player:needToZone(true);
player:setVar("GiohAijhriSpokenTo",0);
if (TwinstoneBonding == QUEST_ACCEPTED) then
player:completeQuest(WINDURST,TWINSTONE_BONDING);
player:addFame(WINDURST,80);
player:addItem(17154);
player:messageSpecial(ITEM_OBTAINED,17154);
player:addTitle(BOND_FIXER);
else
player:addFame(WINDURST,10);
player:addGil(GIL_RATE*900);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*900);
end
elseif (csid == 0x01e8) then
player:setVar("GiohAijhriSpokenTo",1);
end
end;
| gpl-3.0 |
scutwukai/heka_sandbox_lua | ntes_nginx_access_filter.lua | 1 | 2557 | --[[
:Timestamp: 2015-09-08 03:21:09 +0000 UTC
:Type: nginx.access
:Hostname: gsdev
:Pid: 0
:Uuid: 60a57596-fbaf-49e4-af2b-ec53224895cb
:Logger: nginx_access_input
:Payload:
:EnvVersion:
:Severity: 7
:Fields:
| name:"user_agent_browser" type:string value:"Firefox"
| name:"cookie_sid" type:string value:"TqweuNGI1uYUWlSWHNBOivMC4R5wwJY0sfVcdxNP"
| name:"user_agent_version" type:double value:40
| name:"upstream_response_time" type:double value:0.005 representation:"s"
| name:"remote_user" type:string value:"-"
| name:"http_x_forwarded_for" type:string value:"-"
| name:"http_referer" type:string value:"http://gs3.wk.dev.webapp.163.com:8201/404.html"
| name:"body_bytes_sent" type:double value:375 representation:"B"
| name:"remote_addr" type:string value:"10.120.173.207" representation:"ipv4"
| name:"user_agent_os" type:string value:"Macintosh"
| name:"request" type:string value:"GET /app/center HTTP/1.1"
| name:"status" type:double value:302
| name:"uri" type:string value:"/app/center"
| name:"request_time" type:double value:0.005 representation:"s"
]]--
require "os"
require "math"
require "string"
local startup = os.time() * 1e9
local ready = false
local total = 0
local n50x = 0
local up = 0
local sum_uptime = 0 -- ms
function process_message ()
if not ready and read_message("Timestamp") < startup then
return 0
else
ready = true
end
local status = read_message("Fields[status]")
local uptime = read_message("Fields[upstream_response_time]")
total = total + 1
if uptime > 0 then
up = up + 1
sum_uptime = sum_uptime + uptime * 1000
end
--if status >= 500 and status < 600 then
if status == 302 then
n50x = n50x + 1
end
return 0
end
function timer_event(ns)
if not ready then
return
end
local avg_uptime = 0
if up > 0 then
avg_uptime = math.ceil(sum_uptime / up)
end
local msg = {
Type = "nginx.access.stat",
Payload = "",
Fields = {
{name="nginx_all", value=total, value_type=2, representation="ts"},
{name="nginx_50x", value=n50x, value_type=2, representation="ts"},
{name="nginx_up", value=up, value_type=2, representation="ts"},
{name="nginx_avg_uptime", value=avg_uptime, value_type=2, representation="ms"}
}
}
inject_message(msg)
total = 0
n50x = 0
up = 0
sum_uptime = 0
end
| mit |
gedads/Neodynamis | scripts/globals/items/cheval_salmon.lua | 12 | 1344 | -----------------------------------------
-- ID: 4379
-- Item: cheval_salmon
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Charisma -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4379);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_CHA, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_CHA, -4);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Castle_Zvahl_Baileys_[S]/Zone.lua | 32 | 1301 | -----------------------------------
--
-- Zone: Castle_Zvahl_Baileys_[S] (138)
--
-----------------------------------
package.loaded["scripts/zones/Castle_Zvahl_Baileys_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Castle_Zvahl_Baileys_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-181.969,-35.542,19.995,254);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Meriphataud_Mountains/npcs/Stone_Monument.lua | 3 | 1312 | -----------------------------------
-- Area: Meriphataud Mountains
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-- !pos 450.741 2.110 -290.736 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Meriphataud_Mountains/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:messageSpecial(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x04000);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
gedads/Neodynamis | scripts/globals/spells/drown.lua | 5 | 2061 | -----------------------------------------
-- Spell: Drown
-- Deals water damage that lowers an enemy's strength and gradually reduces its HP.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:getStatusEffect(EFFECT_SHOCK) ~= nil) then
spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect
else
local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT);
local params = {};
params.diff = nil;
params.attribute = MOD_INT;
params.skillType = 36;
params.bonus = 0;
params.effect = nil;
local resist = applyResistance(caster, target, spell, params);
if (resist <= 0.125) then
spell:setMsg(msgBasic.MAGIC_RESIST);
else
if (target:getStatusEffect(EFFECT_BURN) ~= nil) then
target:delStatusEffect(EFFECT_BURN);
end;
local sINT = caster:getStat(MOD_INT);
local DOT = getElementalDebuffDOT(sINT);
local effect = target:getStatusEffect(EFFECT_DROWN);
local noeffect = false;
if (effect ~= nil) then
if (effect:getPower() >= DOT) then
noeffect = true;
end;
end;
if (noeffect) then
spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect
else
if (effect ~= nil) then
target:delStatusEffect(EFFECT_DROWN);
end;
spell:setMsg(msgBasic.MAGIC_ENFEEB);
local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist);
target:addStatusEffect(EFFECT_DROWN,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASABLE);
end;
end;
end;
return EFFECT_DROWN;
end;
| gpl-3.0 |
dimitarcl/premake-dev | tests/actions/vstudio/vc2010/test_build_events.lua | 5 | 2318 | --
-- tests/actions/vstudio/vc2010/test_build_events.lua
-- Check generation of pre- and post-build commands for C++ projects.
-- Copyright (c) 2012-2013 Jason Perkins and the Premake project
--
local suite = test.declare("vstudio_vc2010_build_events")
local vc2010 = premake.vstudio.vc2010
--
-- Setup
--
local sln, prj, cfg
function suite.setup()
premake.escaper(premake.vstudio.vs2010.esc)
sln = test.createsolution()
end
local function prepare(platform)
prj = premake.solution.getproject(sln, 1)
vc2010.buildEvents(prj)
end
--
-- If no build steps are specified, nothing should be written.
--
function suite.noOutput_onNoEvents()
prepare()
test.isemptycapture()
end
--
-- If one command set is used and not the other, only the one should be written.
--
function suite.onlyOne_onPreBuildOnly()
prebuildcommands { "command1" }
prepare()
test.capture [[
<PreBuildEvent>
<Command>command1</Command>
</PreBuildEvent>
]]
end
function suite.onlyOne_onPostBuildOnly()
postbuildcommands { "command1" }
prepare()
test.capture [[
<PostBuildEvent>
<Command>command1</Command>
</PostBuildEvent>
]]
end
function suite.both_onBoth()
prebuildcommands { "command1" }
postbuildcommands { "command2" }
prepare()
test.capture [[
<PreBuildEvent>
<Command>command1</Command>
</PreBuildEvent>
<PostBuildEvent>
<Command>command2</Command>
</PostBuildEvent>
]]
end
--
-- Multiple commands should be separated with un-escaped EOLs.
--
function suite.splits_onMultipleCommands()
postbuildcommands { "command1", "command2" }
prepare()
test.capture ("\t\t<PostBuildEvent>\n\t\t\t<Command>command1\r\ncommand2</Command>\n\t\t</PostBuildEvent>\n")
end
--
-- Quotes should not be escaped, other special characters should.
--
function suite.onSpecialChars()
postbuildcommands { '\' " < > &' }
prepare()
test.capture [[
<PostBuildEvent>
<Command>' " < > &</Command>
</PostBuildEvent>
]]
end
--
-- If a message is specified, it should be included.
--
function suite.onMessageProvided()
postbuildcommands { "command1" }
postbuildmessage "Post-building..."
prepare()
test.capture [[
<PostBuildEvent>
<Command>command1</Command>
<Message>Post-building...</Message>
</PostBuildEvent>
]]
end
| bsd-3-clause |
gedads/Neodynamis | scripts/zones/Riverne-Site_B01/npcs/Unstable_Displacement.lua | 3 | 2160 | -----------------------------------
-- Area: Riverne Site #B01
-- NPC: Unstable Displacement
-- ENM Battlefield
-- !pos -612 4 693
-----------------------------------
package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Riverne-Site_B01/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/status");
require("scripts/globals/bcnm");
-- events:
-- 7D00 : BC menu
-- Param 4 is a bitmask for the choice of battlefields in the menu:
-- 0:
-- 1:
-- 2:
-- 3:
-- 4:
-- 5:
-- Param 8 is a flag: 0 : menu, >0 : automatically enter and exit
-- 7D01 : final BC event.
-- param 2: #time record for this mission
-- param 3: #clear time in seconds
-- param 6: #which mission (linear numbering as above)
-- 7D03 : stay/run away
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_ACCEPTED and player:getVar('StormsOfFate') == 1) then
player:startEvent(0x0001);
elseif (EventTriggerBCNM(player,npc)) then
return 1;
else
player:messageSpecial(SPACE_SEEMS_DISTORTED);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0001) then
player:setVar('StormsOfFate',2);
elseif (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/zones/RoMaeve/IDs.lua | 6 | 3051 | -----------------------------------
-- Area: RoMaeve
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.ROMAEVE] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
FISHING_MESSAGE_OFFSET = 7208, -- You can't fish here.
SENSE_OMINOUS_PRESENCE = 7394, -- You sense an ominous presence...
ITEMS_ITEMS_LA_LA = 7397, -- You can hear a strange voice...“Items, items, la la la la la~♪”
GOBLIN_SLIPPED_AWAY = 7403, -- The Goblin slipped away when you were not looking...
PLAYER_OBTAINS_ITEM = 7426, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 7427, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 7428, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 7429, -- You already possess that temporary item.
NO_COMBINATION = 7434, -- You were unable to enter a combination.
REGIME_REGISTERED = 9612, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 11622, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
NIGHTMARE_VASE_PH =
{
[17276981] = 17276982, -- -101.575 -6.099 -1.520 (west)
[17276987] = 17276992, -- 59.825 -5.760 25.123 (east)
},
ROGUE_RECEPTACLE_PH =
{
[17277075] = 17277079,
[17277078] = 17277079,
},
MOKKURKALFI_I = 17276929,
MOKKURKALFI_II = 17276930,
ELDHRIMNIR = 17277126,
},
npc =
{
BASTOK_7_1_QM_POS =
{
[1] = { 162.000, -8.000, 21.000}, -- L-7
[2] = { 160.000, -6.000, -110.000}, -- L-10
[3] = { 105.000, -4.000, -112.000}, -- K-11
[4] = { 126.000, -3.000, -75.000}, -- K-10
[5] = { 60.000, -6.000, 2.000}, -- I-8/J-8
[6] = { -48.000, -4.000, -32.000}, -- G-9
[7] = { -109.000, -4.000, -114.000}, -- E-11
[8] = { -137.000, 1.000, -90.000}, -- E-10
[9] = { -105.000, -3.000, -36.000}, -- E-9
[10] = { -160.000, -6.000, -107.000} -- D-10
},
CASKET_BASE = 17277171,
MOONGATE_OFFSET = 17277195,
BASTOK_7_1_QM = 17277207,
},
}
return zones[dsp.zone.ROMAEVE] | gpl-3.0 |
O-P-E-N/CC-ROUTER | feeds/luci/modules/luci-mod-rpc/luasrc/controller/rpc.lua | 37 | 4466 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local require = require
local pairs = pairs
local print = print
local pcall = pcall
local table = table
module "luci.controller.rpc"
function index()
local function authenticator(validator, accs)
local auth = luci.http.formvalue("auth", true)
if auth then -- if authentication token was given
local sdat = (luci.util.ubus("session", "get", { ubus_rpc_session = auth }) or { }).values
if sdat then -- if given token is valid
if sdat.user and luci.util.contains(accs, sdat.user) then
return sdat.user, auth
end
end
end
luci.http.status(403, "Forbidden")
end
local rpc = node("rpc")
rpc.sysauth = "root"
rpc.sysauth_authenticator = authenticator
rpc.notemplate = true
entry({"rpc", "uci"}, call("rpc_uci"))
entry({"rpc", "fs"}, call("rpc_fs"))
entry({"rpc", "sys"}, call("rpc_sys"))
entry({"rpc", "ipkg"}, call("rpc_ipkg"))
entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false
end
function rpc_auth()
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local sys = require "luci.sys"
local ltn12 = require "luci.ltn12"
local util = require "luci.util"
local loginstat
local server = {}
server.challenge = function(user, pass)
local sid, token, secret
local config = require "luci.config"
if sys.user.checkpasswd(user, pass) then
local sdat = util.ubus("session", "create", { timeout = config.sauth.sessiontime })
if sdat then
sid = sdat.ubus_rpc_session
token = sys.uniqueid(16)
secret = sys.uniqueid(16)
http.header("Set-Cookie", "sysauth="..sid.."; path=/")
util.ubus("session", "set", {
ubus_rpc_session = sid,
values = {
user = user,
token = token,
secret = secret
}
})
end
end
return sid and {sid=sid, token=token, secret=secret}
end
server.login = function(...)
local challenge = server.challenge(...)
return challenge and challenge.sid
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write)
end
function rpc_uci()
if not pcall(require, "luci.model.uci") then
luci.http.status(404, "Not Found")
return nil
end
local uci = require "luci.jsonrpcbind.uci"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write)
end
function rpc_fs()
local util = require "luci.util"
local io = require "io"
local fs2 = util.clone(require "nixio.fs")
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
function fs2.readfile(filename)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local fp = io.open(filename)
if not fp then
return nil
end
local output = {}
local sink = ltn12.sink.table(output)
local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64"))
return ltn12.pump.all(source, sink) and table.concat(output)
end
function fs2.writefile(filename, data)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local file = io.open(filename, "w")
local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file))
return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write)
end
function rpc_sys()
local sys = require "luci.sys"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write)
end
function rpc_ipkg()
if not pcall(require, "luci.model.ipkg") then
luci.http.status(404, "Not Found")
return nil
end
local ipkg = require "luci.model.ipkg"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write)
end
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Port_Windurst/npcs/Kumama.lua | 17 | 1712 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kumama
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,KUMAMA_SHOP_DIALOG);
stock = {
0x3239, 2268,1, --Linen Slops
0x32b9, 1462,1, --Holly Clogs
0x3004, 4482,1, --Mahogany Shield
0x3218, 482,2, --Leather Trousers
0x3231, 9936,2, --Cotton Brais
0x3298, 309,2, --Leather Highboots
0x32c0, 544,2, --Solea
0x32b1, 6633,2, --Cotton Gaiters
0x3002, 556,2, --Maple Shield
0x3230, 1899,3, --Brais
0x3238, 172,3, --Slops
0x32b0, 1269,3, --Gaiters
0x32b8, 111,3, --Ash Clogs
0x3001, 110,3 --Lauan Shield
}
showNationShop(player, NATION_WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/chocolate_cake.lua | 11 | 1127 | -----------------------------------------
-- ID: 5633
-- Item: Chocolate Cake
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- MP +3% (cap 90)
-- HP Recovered while healing +1
-- MP Recovered while healing +6
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5633)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_MPP, 3)
target:addMod(dsp.mod.FOOD_MP_CAP, 90)
target:addMod(dsp.mod.HPHEAL, 1)
target:addMod(dsp.mod.MPHEAL, 6)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_MPP, 3)
target:delMod(dsp.mod.FOOD_MP_CAP, 90)
target:delMod(dsp.mod.HPHEAL, 1)
target:delMod(dsp.mod.MPHEAL, 6)
end
| gpl-3.0 |
Amorph/premake-stable | src/_manifest.lua | 1 | 2001 | --
-- _manifest.lua
-- Manage the list of built-in Premake scripts.
-- Copyright (c) 2002-2011 Jason Perkins and the Premake project
--
-- The master list of built-in scripts. Order is important! If you want to
-- build a new script into Premake, add it to this list.
return
{
-- core files
"base/os.lua",
"base/path.lua",
"base/string.lua",
"base/table.lua",
"base/io.lua",
"base/globals.lua",
"base/action.lua",
"base/option.lua",
"base/tree.lua",
"base/solution.lua",
"base/project.lua",
"base/config.lua",
"base/bake.lua",
"base/api.lua",
"base/cmdline.lua",
"tools/dotnet.lua",
"tools/gcc.lua",
"tools/msc.lua",
"tools/ow.lua",
"tools/snc.lua",
"base/validate.lua",
"base/help.lua",
"base/premake.lua",
-- CodeBlocks action
"actions/codeblocks/_codeblocks.lua",
"actions/codeblocks/codeblocks_workspace.lua",
"actions/codeblocks/codeblocks_cbp.lua",
-- CodeLite action
"actions/codelite/_codelite.lua",
"actions/codelite/codelite_workspace.lua",
"actions/codelite/codelite_project.lua",
-- GNU make action
"actions/make/_make.lua",
"actions/make/make_solution.lua",
"actions/make/make_cpp.lua",
"actions/make/make_csharp.lua",
-- Visual Studio actions
"actions/vstudio/_vstudio.lua",
"actions/vstudio/vs2002_solution.lua",
"actions/vstudio/vs2002_csproj.lua",
"actions/vstudio/vs2002_csproj_user.lua",
"actions/vstudio/vs200x_vcproj.lua",
"actions/vstudio/vs200x_vcproj_user.lua",
"actions/vstudio/vs2003_solution.lua",
"actions/vstudio/vs2005_solution.lua",
"actions/vstudio/vs2005_csproj.lua",
"actions/vstudio/vs2005_csproj_user.lua",
"actions/vstudio/vs2010_vcxproj.lua",
"actions/vstudio/vs2010_vcxproj_filters.lua",
"actions/vstudio/vs2012.lua",
-- Xcode action
"actions/xcode/_xcode.lua",
"actions/xcode/xcode_common.lua",
"actions/xcode/xcode_project.lua",
-- Xcode4 action
"actions/xcode/xcode4_workspace.lua",
-- Clean action
"actions/clean/_clean.lua",
}
| bsd-3-clause |
starlightknight/darkstar | scripts/globals/spells/tornado.lua | 12 | 1030 | -----------------------------------------
-- Spell: Tornado
-- Deals wind damage to an enemy and lowers its resistance against ice.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local spellParams = {}
spellParams.hasMultipleTargetReduction = false
spellParams.resistBonus = 1.0
spellParams.V = 552
spellParams.V0 = 700
spellParams.V50 = 800
spellParams.V100 = 900
spellParams.V200 = 1100
spellParams.M = 2
spellParams.M0 = 2
spellParams.M50 = 2
spellParams.M100 = 2
spellParams.M200 = 2
spellParams.I = 577
-- no point in making a separate function for this if the only thing they won't have in common is the name
handleNinjutsuDebuff(caster,target,spell,30,10,dsp.mod.ICERES)
return doElementalNuke(caster, spell, target, spellParams)
end
| gpl-3.0 |
hwhw/kindlevncviewer | rfbkeys.lua | 2 | 36641 | --[[**********************************************************
Copyright (c) 1987, 1994 X Consortium
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 X CONSORTIUM 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.
Except as contained in this notice, the name of the X Consortium shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the X Consortium.
Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
*****************************************************************]]--
XK_VoidSymbol = 0xFFFFFF --[[ void symbol ]]--
XK_BackSpace = 0xFF08 --[[ back space, back char ]]--
XK_Tab = 0xFF09
XK_Linefeed = 0xFF0A --[[ Linefeed, LF ]]--
XK_Clear = 0xFF0B
XK_Return = 0xFF0D --[[ Return, enter ]]--
XK_Pause = 0xFF13 --[[ Pause, hold ]]--
XK_Scroll_Lock = 0xFF14
XK_Sys_Req = 0xFF15
XK_Escape = 0xFF1B
XK_Delete = 0xFFFF --[[ Delete, rubout ]]--
--[[ International & multi-key character composition ]]--
XK_Multi_key = 0xFF20 --[[ Multi-key character compose ]]--
XK_SingleCandidate = 0xFF3C
XK_MultipleCandidate = 0xFF3D
XK_PreviousCandidate = 0xFF3E
--[[ Japanese keyboard support ]]--
XK_Kanji = 0xFF21 --[[ Kanji, Kanji convert ]]--
XK_Muhenkan = 0xFF22 --[[ Cancel Conversion ]]--
XK_Henkan_Mode = 0xFF23 --[[ Start/Stop Conversion ]]--
XK_Henkan = 0xFF23 --[[ Alias for Henkan_Mode ]]--
XK_Romaji = 0xFF24 --[[ to Romaji ]]--
XK_Hiragana = 0xFF25 --[[ to Hiragana ]]--
XK_Katakana = 0xFF26 --[[ to Katakana ]]--
XK_Hiragana_Katakana = 0xFF27 --[[ Hiragana/Katakana toggle ]]--
XK_Zenkaku = 0xFF28 --[[ to Zenkaku ]]--
XK_Hankaku = 0xFF29 --[[ to Hankaku ]]--
XK_Zenkaku_Hankaku = 0xFF2A --[[ Zenkaku/Hankaku toggle ]]--
XK_Touroku = 0xFF2B --[[ Add to Dictionary ]]--
XK_Massyo = 0xFF2C --[[ Delete from Dictionary ]]--
XK_Kana_Lock = 0xFF2D --[[ Kana Lock ]]--
XK_Kana_Shift = 0xFF2E --[[ Kana Shift ]]--
XK_Eisu_Shift = 0xFF2F --[[ Alphanumeric Shift ]]--
XK_Eisu_toggle = 0xFF30 --[[ Alphanumeric toggle ]]--
XK_Zen_Koho = 0xFF3D --[[ Multiple/All Candidate(s) ]]--
XK_Mae_Koho = 0xFF3E --[[ Previous Candidate ]]--
--[[ 0xFF31 thru 0xFF3F are under XK_KOREAN = ]]--
--[[ Cursor control & motion ]]--
XK_Home = 0xFF50
XK_Left = 0xFF51 --[[ Move left, left arrow ]]--
XK_Up = 0xFF52 --[[ Move up, up arrow ]]--
XK_Right = 0xFF53 --[[ Move right, right arrow ]]--
XK_Down = 0xFF54 --[[ Move down, down arrow ]]--
XK_Prior = 0xFF55 --[[ Prior, previous ]]--
XK_Page_Up = 0xFF55
XK_Next = 0xFF56 --[[ Next ]]--
XK_Page_Down = 0xFF56
XK_End = 0xFF57 --[[ EOL ]]--
XK_Begin = 0xFF58 --[[ BOL ]]--
--[[ Misc Functions ]]--
XK_Select = 0xFF60 --[[ Select, mark ]]--
XK_Print = 0xFF61
XK_Execute = 0xFF62 --[[ Execute, run, do ]]--
XK_Insert = 0xFF63 --[[ Insert, insert here ]]--
XK_Undo = 0xFF65 --[[ Undo, oops ]]--
XK_Redo = 0xFF66 --[[ redo, again ]]--
XK_Menu = 0xFF67
XK_Find = 0xFF68 --[[ Find, search ]]--
XK_Cancel = 0xFF69 --[[ Cancel, stop, abort, exit ]]--
XK_Help = 0xFF6A --[[ Help ]]--
XK_Break = 0xFF6B
XK_Mode_switch = 0xFF7E --[[ Character set switch ]]--
XK_script_switch = 0xFF7E --[[ Alias for mode_switch ]]--
XK_Num_Lock = 0xFF7F
--[[ Keypad Functions, keypad numbers cleverly chosen to map to ascii ]]--
XK_KP_Space = 0xFF80 --[[ space ]]--
XK_KP_Tab = 0xFF89
XK_KP_Enter = 0xFF8D --[[ enter ]]--
XK_KP_F1 = 0xFF91 --[[ PF1, KP_A, ... ]]--
XK_KP_F2 = 0xFF92
XK_KP_F3 = 0xFF93
XK_KP_F4 = 0xFF94
XK_KP_Home = 0xFF95
XK_KP_Left = 0xFF96
XK_KP_Up = 0xFF97
XK_KP_Right = 0xFF98
XK_KP_Down = 0xFF99
XK_KP_Prior = 0xFF9A
XK_KP_Page_Up = 0xFF9A
XK_KP_Next = 0xFF9B
XK_KP_Page_Down = 0xFF9B
XK_KP_End = 0xFF9C
XK_KP_Begin = 0xFF9D
XK_KP_Insert = 0xFF9E
XK_KP_Delete = 0xFF9F
XK_KP_Equal = 0xFFBD --[[ equals ]]--
XK_KP_Multiply = 0xFFAA
XK_KP_Add = 0xFFAB
XK_KP_Separator = 0xFFAC --[[ separator, often comma ]]--
XK_KP_Subtract = 0xFFAD
XK_KP_Decimal = 0xFFAE
XK_KP_Divide = 0xFFAF
XK_KP_0 = 0xFFB0
XK_KP_1 = 0xFFB1
XK_KP_2 = 0xFFB2
XK_KP_3 = 0xFFB3
XK_KP_4 = 0xFFB4
XK_KP_5 = 0xFFB5
XK_KP_6 = 0xFFB6
XK_KP_7 = 0xFFB7
XK_KP_8 = 0xFFB8
XK_KP_9 = 0xFFB9
--[[
* Auxilliary Functions; note the duplicate definitions for left and right
* function keys; Sun keyboards and a few other manufactures have such
* function key groups on the left and/or right sides of the keyboard.
* We've not found a keyboard with more than 35 function keys total.
]]--
XK_F1 = 0xFFBE
XK_F2 = 0xFFBF
XK_F3 = 0xFFC0
XK_F4 = 0xFFC1
XK_F5 = 0xFFC2
XK_F6 = 0xFFC3
XK_F7 = 0xFFC4
XK_F8 = 0xFFC5
XK_F9 = 0xFFC6
XK_F10 = 0xFFC7
XK_F11 = 0xFFC8
XK_L1 = 0xFFC8
XK_F12 = 0xFFC9
XK_L2 = 0xFFC9
XK_F13 = 0xFFCA
XK_L3 = 0xFFCA
XK_F14 = 0xFFCB
XK_L4 = 0xFFCB
XK_F15 = 0xFFCC
XK_L5 = 0xFFCC
XK_F16 = 0xFFCD
XK_L6 = 0xFFCD
XK_F17 = 0xFFCE
XK_L7 = 0xFFCE
XK_F18 = 0xFFCF
XK_L8 = 0xFFCF
XK_F19 = 0xFFD0
XK_L9 = 0xFFD0
XK_F20 = 0xFFD1
XK_L10 = 0xFFD1
XK_F21 = 0xFFD2
XK_R1 = 0xFFD2
XK_F22 = 0xFFD3
XK_R2 = 0xFFD3
XK_F23 = 0xFFD4
XK_R3 = 0xFFD4
XK_F24 = 0xFFD5
XK_R4 = 0xFFD5
XK_F25 = 0xFFD6
XK_R5 = 0xFFD6
XK_F26 = 0xFFD7
XK_R6 = 0xFFD7
XK_F27 = 0xFFD8
XK_R7 = 0xFFD8
XK_F28 = 0xFFD9
XK_R8 = 0xFFD9
XK_F29 = 0xFFDA
XK_R9 = 0xFFDA
XK_F30 = 0xFFDB
XK_R10 = 0xFFDB
XK_F31 = 0xFFDC
XK_R11 = 0xFFDC
XK_F32 = 0xFFDD
XK_R12 = 0xFFDD
XK_F33 = 0xFFDE
XK_R13 = 0xFFDE
XK_F34 = 0xFFDF
XK_R14 = 0xFFDF
XK_F35 = 0xFFE0
XK_R15 = 0xFFE0
--[[ Modifiers ]]--
XK_Shift_L = 0xFFE1 --[[ Left shift ]]--
XK_Shift_R = 0xFFE2 --[[ Right shift ]]--
XK_Control_L = 0xFFE3 --[[ Left control ]]--
XK_Control_R = 0xFFE4 --[[ Right control ]]--
XK_Caps_Lock = 0xFFE5 --[[ Caps lock ]]--
XK_Shift_Lock = 0xFFE6 --[[ Shift lock ]]--
XK_Meta_L = 0xFFE7 --[[ Left meta ]]--
XK_Meta_R = 0xFFE8 --[[ Right meta ]]--
XK_Alt_L = 0xFFE9 --[[ Left alt ]]--
XK_Alt_R = 0xFFEA --[[ Right alt ]]--
XK_Super_L = 0xFFEB --[[ Left super ]]--
XK_Super_R = 0xFFEC --[[ Right super ]]--
XK_Hyper_L = 0xFFED --[[ Left hyper ]]--
XK_Hyper_R = 0xFFEE --[[ Right hyper ]]--
--[[
* ISO 9995 Function and Modifier Keys
* Byte 3 = 0xFE
]]--
XK_ISO_Lock = 0xFE01
XK_ISO_Level2_Latch = 0xFE02
XK_ISO_Level3_Shift = 0xFE03
XK_ISO_Level3_Latch = 0xFE04
XK_ISO_Level3_Lock = 0xFE05
XK_ISO_Group_Shift = 0xFF7E --[[ Alias for mode_switch ]]--
XK_ISO_Group_Latch = 0xFE06
XK_ISO_Group_Lock = 0xFE07
XK_ISO_Next_Group = 0xFE08
XK_ISO_Next_Group_Lock = 0xFE09
XK_ISO_Prev_Group = 0xFE0A
XK_ISO_Prev_Group_Lock = 0xFE0B
XK_ISO_First_Group = 0xFE0C
XK_ISO_First_Group_Lock = 0xFE0D
XK_ISO_Last_Group = 0xFE0E
XK_ISO_Last_Group_Lock = 0xFE0F
XK_ISO_Left_Tab = 0xFE20
XK_ISO_Move_Line_Up = 0xFE21
XK_ISO_Move_Line_Down = 0xFE22
XK_ISO_Partial_Line_Up = 0xFE23
XK_ISO_Partial_Line_Down = 0xFE24
XK_ISO_Partial_Space_Left = 0xFE25
XK_ISO_Partial_Space_Right = 0xFE26
XK_ISO_Set_Margin_Left = 0xFE27
XK_ISO_Set_Margin_Right = 0xFE28
XK_ISO_Release_Margin_Left = 0xFE29
XK_ISO_Release_Margin_Right = 0xFE2A
XK_ISO_Release_Both_Margins = 0xFE2B
XK_ISO_Fast_Cursor_Left = 0xFE2C
XK_ISO_Fast_Cursor_Right = 0xFE2D
XK_ISO_Fast_Cursor_Up = 0xFE2E
XK_ISO_Fast_Cursor_Down = 0xFE2F
XK_ISO_Continuous_Underline = 0xFE30
XK_ISO_Discontinuous_Underline = 0xFE31
XK_ISO_Emphasize = 0xFE32
XK_ISO_Center_Object = 0xFE33
XK_ISO_Enter = 0xFE34
XK_dead_grave = 0xFE50
XK_dead_acute = 0xFE51
XK_dead_circumflex = 0xFE52
XK_dead_tilde = 0xFE53
XK_dead_macron = 0xFE54
XK_dead_breve = 0xFE55
XK_dead_abovedot = 0xFE56
XK_dead_diaeresis = 0xFE57
XK_dead_abovering = 0xFE58
XK_dead_doubleacute = 0xFE59
XK_dead_caron = 0xFE5A
XK_dead_cedilla = 0xFE5B
XK_dead_ogonek = 0xFE5C
XK_dead_iota = 0xFE5D
XK_dead_voiced_sound = 0xFE5E
XK_dead_semivoiced_sound = 0xFE5F
XK_dead_belowdot = 0xFE60
XK_First_Virtual_Screen = 0xFED0
XK_Prev_Virtual_Screen = 0xFED1
XK_Next_Virtual_Screen = 0xFED2
XK_Last_Virtual_Screen = 0xFED4
XK_Terminate_Server = 0xFED5
XK_AccessX_Enable = 0xFE70
XK_AccessX_Feedback_Enable = 0xFE71
XK_RepeatKeys_Enable = 0xFE72
XK_SlowKeys_Enable = 0xFE73
XK_BounceKeys_Enable = 0xFE74
XK_StickyKeys_Enable = 0xFE75
XK_MouseKeys_Enable = 0xFE76
XK_MouseKeys_Accel_Enable = 0xFE77
XK_Overlay1_Enable = 0xFE78
XK_Overlay2_Enable = 0xFE79
XK_AudibleBell_Enable = 0xFE7A
XK_Pointer_Left = 0xFEE0
XK_Pointer_Right = 0xFEE1
XK_Pointer_Up = 0xFEE2
XK_Pointer_Down = 0xFEE3
XK_Pointer_UpLeft = 0xFEE4
XK_Pointer_UpRight = 0xFEE5
XK_Pointer_DownLeft = 0xFEE6
XK_Pointer_DownRight = 0xFEE7
XK_Pointer_Button_Dflt = 0xFEE8
XK_Pointer_Button1 = 0xFEE9
XK_Pointer_Button2 = 0xFEEA
XK_Pointer_Button3 = 0xFEEB
XK_Pointer_Button4 = 0xFEEC
XK_Pointer_Button5 = 0xFEED
XK_Pointer_DblClick_Dflt = 0xFEEE
XK_Pointer_DblClick1 = 0xFEEF
XK_Pointer_DblClick2 = 0xFEF0
XK_Pointer_DblClick3 = 0xFEF1
XK_Pointer_DblClick4 = 0xFEF2
XK_Pointer_DblClick5 = 0xFEF3
XK_Pointer_Drag_Dflt = 0xFEF4
XK_Pointer_Drag1 = 0xFEF5
XK_Pointer_Drag2 = 0xFEF6
XK_Pointer_Drag3 = 0xFEF7
XK_Pointer_Drag4 = 0xFEF8
XK_Pointer_Drag5 = 0xFEFD
XK_Pointer_EnableKeys = 0xFEF9
XK_Pointer_Accelerate = 0xFEFA
XK_Pointer_DfltBtnNext = 0xFEFB
XK_Pointer_DfltBtnPrev = 0xFEFC
--[[
* 3270 Terminal Keys
* Byte 3 = 0xFD
]]--
XK_3270_Duplicate = 0xFD01
XK_3270_FieldMark = 0xFD02
XK_3270_Right2 = 0xFD03
XK_3270_Left2 = 0xFD04
XK_3270_BackTab = 0xFD05
XK_3270_EraseEOF = 0xFD06
XK_3270_EraseInput = 0xFD07
XK_3270_Reset = 0xFD08
XK_3270_Quit = 0xFD09
XK_3270_PA1 = 0xFD0A
XK_3270_PA2 = 0xFD0B
XK_3270_PA3 = 0xFD0C
XK_3270_Test = 0xFD0D
XK_3270_Attn = 0xFD0E
XK_3270_CursorBlink = 0xFD0F
XK_3270_AltCursor = 0xFD10
XK_3270_KeyClick = 0xFD11
XK_3270_Jump = 0xFD12
XK_3270_Ident = 0xFD13
XK_3270_Rule = 0xFD14
XK_3270_Copy = 0xFD15
XK_3270_Play = 0xFD16
XK_3270_Setup = 0xFD17
XK_3270_Record = 0xFD18
XK_3270_ChangeScreen = 0xFD19
XK_3270_DeleteWord = 0xFD1A
XK_3270_ExSelect = 0xFD1B
XK_3270_CursorSelect = 0xFD1C
XK_3270_PrintScreen = 0xFD1D
XK_3270_Enter = 0xFD1E
--[[
* Latin 1
* Byte 3 = 0
]]--
XK_space = 0x020
XK_exclam = 0x021
XK_quotedbl = 0x022
XK_numbersign = 0x023
XK_dollar = 0x024
XK_percent = 0x025
XK_ampersand = 0x026
XK_apostrophe = 0x027
XK_quoteright = 0x027 --[[ deprecated ]]--
XK_parenleft = 0x028
XK_parenright = 0x029
XK_asterisk = 0x02a
XK_plus = 0x02b
XK_comma = 0x02c
XK_minus = 0x02d
XK_period = 0x02e
XK_slash = 0x02f
XK_0 = 0x030
XK_1 = 0x031
XK_2 = 0x032
XK_3 = 0x033
XK_4 = 0x034
XK_5 = 0x035
XK_6 = 0x036
XK_7 = 0x037
XK_8 = 0x038
XK_9 = 0x039
XK_colon = 0x03a
XK_semicolon = 0x03b
XK_less = 0x03c
XK_equal = 0x03d
XK_greater = 0x03e
XK_question = 0x03f
XK_at = 0x040
XK_A = 0x041
XK_B = 0x042
XK_C = 0x043
XK_D = 0x044
XK_E = 0x045
XK_F = 0x046
XK_G = 0x047
XK_H = 0x048
XK_I = 0x049
XK_J = 0x04a
XK_K = 0x04b
XK_L = 0x04c
XK_M = 0x04d
XK_N = 0x04e
XK_O = 0x04f
XK_P = 0x050
XK_Q = 0x051
XK_R = 0x052
XK_S = 0x053
XK_T = 0x054
XK_U = 0x055
XK_V = 0x056
XK_W = 0x057
XK_X = 0x058
XK_Y = 0x059
XK_Z = 0x05a
XK_bracketleft = 0x05b
XK_backslash = 0x05c
XK_bracketright = 0x05d
XK_asciicircum = 0x05e
XK_underscore = 0x05f
XK_grave = 0x060
XK_quoteleft = 0x060 --[[ deprecated ]]--
XK_a = 0x061
XK_b = 0x062
XK_c = 0x063
XK_d = 0x064
XK_e = 0x065
XK_f = 0x066
XK_g = 0x067
XK_h = 0x068
XK_i = 0x069
XK_j = 0x06a
XK_k = 0x06b
XK_l = 0x06c
XK_m = 0x06d
XK_n = 0x06e
XK_o = 0x06f
XK_p = 0x070
XK_q = 0x071
XK_r = 0x072
XK_s = 0x073
XK_t = 0x074
XK_u = 0x075
XK_v = 0x076
XK_w = 0x077
XK_x = 0x078
XK_y = 0x079
XK_z = 0x07a
XK_braceleft = 0x07b
XK_bar = 0x07c
XK_braceright = 0x07d
XK_asciitilde = 0x07e
XK_nobreakspace = 0x0a0
XK_exclamdown = 0x0a1
XK_cent = 0x0a2
XK_sterling = 0x0a3
XK_currency = 0x0a4
XK_yen = 0x0a5
XK_brokenbar = 0x0a6
XK_section = 0x0a7
XK_diaeresis = 0x0a8
XK_copyright = 0x0a9
XK_ordfeminine = 0x0aa
XK_guillemotleft = 0x0ab --[[ left angle quotation mark ]]--
XK_notsign = 0x0ac
XK_hyphen = 0x0ad
XK_registered = 0x0ae
XK_macron = 0x0af
XK_degree = 0x0b0
XK_plusminus = 0x0b1
XK_twosuperior = 0x0b2
XK_threesuperior = 0x0b3
XK_acute = 0x0b4
XK_mu = 0x0b5
XK_paragraph = 0x0b6
XK_periodcentered = 0x0b7
XK_cedilla = 0x0b8
XK_onesuperior = 0x0b9
XK_masculine = 0x0ba
XK_guillemotright = 0x0bb --[[ right angle quotation mark ]]--
XK_onequarter = 0x0bc
XK_onehalf = 0x0bd
XK_threequarters = 0x0be
XK_questiondown = 0x0bf
XK_Agrave = 0x0c0
XK_Aacute = 0x0c1
XK_Acircumflex = 0x0c2
XK_Atilde = 0x0c3
XK_Adiaeresis = 0x0c4
XK_Aring = 0x0c5
XK_AE = 0x0c6
XK_Ccedilla = 0x0c7
XK_Egrave = 0x0c8
XK_Eacute = 0x0c9
XK_Ecircumflex = 0x0ca
XK_Ediaeresis = 0x0cb
XK_Igrave = 0x0cc
XK_Iacute = 0x0cd
XK_Icircumflex = 0x0ce
XK_Idiaeresis = 0x0cf
XK_ETH = 0x0d0
XK_Eth = 0x0d0 --[[ deprecated ]]--
XK_Ntilde = 0x0d1
XK_Ograve = 0x0d2
XK_Oacute = 0x0d3
XK_Ocircumflex = 0x0d4
XK_Otilde = 0x0d5
XK_Odiaeresis = 0x0d6
XK_multiply = 0x0d7
XK_Ooblique = 0x0d8
XK_Ugrave = 0x0d9
XK_Uacute = 0x0da
XK_Ucircumflex = 0x0db
XK_Udiaeresis = 0x0dc
XK_Yacute = 0x0dd
XK_THORN = 0x0de
XK_Thorn = 0x0de --[[ deprecated ]]--
XK_ssharp = 0x0df
XK_agrave = 0x0e0
XK_aacute = 0x0e1
XK_acircumflex = 0x0e2
XK_atilde = 0x0e3
XK_adiaeresis = 0x0e4
XK_aring = 0x0e5
XK_ae = 0x0e6
XK_ccedilla = 0x0e7
XK_egrave = 0x0e8
XK_eacute = 0x0e9
XK_ecircumflex = 0x0ea
XK_ediaeresis = 0x0eb
XK_igrave = 0x0ec
XK_iacute = 0x0ed
XK_icircumflex = 0x0ee
XK_idiaeresis = 0x0ef
XK_eth = 0x0f0
XK_ntilde = 0x0f1
XK_ograve = 0x0f2
XK_oacute = 0x0f3
XK_ocircumflex = 0x0f4
XK_otilde = 0x0f5
XK_odiaeresis = 0x0f6
XK_division = 0x0f7
XK_oslash = 0x0f8
XK_ugrave = 0x0f9
XK_uacute = 0x0fa
XK_ucircumflex = 0x0fb
XK_udiaeresis = 0x0fc
XK_yacute = 0x0fd
XK_thorn = 0x0fe
XK_ydiaeresis = 0x0ff
--[[
* Latin 2
* Byte 3 = 1
]]--
XK_Aogonek = 0x1a1
XK_breve = 0x1a2
XK_Lstroke = 0x1a3
XK_Lcaron = 0x1a5
XK_Sacute = 0x1a6
XK_Scaron = 0x1a9
XK_Scedilla = 0x1aa
XK_Tcaron = 0x1ab
XK_Zacute = 0x1ac
XK_Zcaron = 0x1ae
XK_Zabovedot = 0x1af
XK_aogonek = 0x1b1
XK_ogonek = 0x1b2
XK_lstroke = 0x1b3
XK_lcaron = 0x1b5
XK_sacute = 0x1b6
XK_caron = 0x1b7
XK_scaron = 0x1b9
XK_scedilla = 0x1ba
XK_tcaron = 0x1bb
XK_zacute = 0x1bc
XK_doubleacute = 0x1bd
XK_zcaron = 0x1be
XK_zabovedot = 0x1bf
XK_Racute = 0x1c0
XK_Abreve = 0x1c3
XK_Lacute = 0x1c5
XK_Cacute = 0x1c6
XK_Ccaron = 0x1c8
XK_Eogonek = 0x1ca
XK_Ecaron = 0x1cc
XK_Dcaron = 0x1cf
XK_Dstroke = 0x1d0
XK_Nacute = 0x1d1
XK_Ncaron = 0x1d2
XK_Odoubleacute = 0x1d5
XK_Rcaron = 0x1d8
XK_Uring = 0x1d9
XK_Udoubleacute = 0x1db
XK_Tcedilla = 0x1de
XK_racute = 0x1e0
XK_abreve = 0x1e3
XK_lacute = 0x1e5
XK_cacute = 0x1e6
XK_ccaron = 0x1e8
XK_eogonek = 0x1ea
XK_ecaron = 0x1ec
XK_dcaron = 0x1ef
XK_dstroke = 0x1f0
XK_nacute = 0x1f1
XK_ncaron = 0x1f2
XK_odoubleacute = 0x1f5
XK_udoubleacute = 0x1fb
XK_rcaron = 0x1f8
XK_uring = 0x1f9
XK_tcedilla = 0x1fe
XK_abovedot = 0x1ff
--[[
* Latin 3
* Byte 3 = 2
]]--
XK_Hstroke = 0x2a1
XK_Hcircumflex = 0x2a6
XK_Iabovedot = 0x2a9
XK_Gbreve = 0x2ab
XK_Jcircumflex = 0x2ac
XK_hstroke = 0x2b1
XK_hcircumflex = 0x2b6
XK_idotless = 0x2b9
XK_gbreve = 0x2bb
XK_jcircumflex = 0x2bc
XK_Cabovedot = 0x2c5
XK_Ccircumflex = 0x2c6
XK_Gabovedot = 0x2d5
XK_Gcircumflex = 0x2d8
XK_Ubreve = 0x2dd
XK_Scircumflex = 0x2de
XK_cabovedot = 0x2e5
XK_ccircumflex = 0x2e6
XK_gabovedot = 0x2f5
XK_gcircumflex = 0x2f8
XK_ubreve = 0x2fd
XK_scircumflex = 0x2fe
--[[
* Latin 4
* Byte 3 = 3
]]--
XK_kra = 0x3a2
XK_kappa = 0x3a2 --[[ deprecated ]]--
XK_Rcedilla = 0x3a3
XK_Itilde = 0x3a5
XK_Lcedilla = 0x3a6
XK_Emacron = 0x3aa
XK_Gcedilla = 0x3ab
XK_Tslash = 0x3ac
XK_rcedilla = 0x3b3
XK_itilde = 0x3b5
XK_lcedilla = 0x3b6
XK_emacron = 0x3ba
XK_gcedilla = 0x3bb
XK_tslash = 0x3bc
XK_ENG = 0x3bd
XK_eng = 0x3bf
XK_Amacron = 0x3c0
XK_Iogonek = 0x3c7
XK_Eabovedot = 0x3cc
XK_Imacron = 0x3cf
XK_Ncedilla = 0x3d1
XK_Omacron = 0x3d2
XK_Kcedilla = 0x3d3
XK_Uogonek = 0x3d9
XK_Utilde = 0x3dd
XK_Umacron = 0x3de
XK_amacron = 0x3e0
XK_iogonek = 0x3e7
XK_eabovedot = 0x3ec
XK_imacron = 0x3ef
XK_ncedilla = 0x3f1
XK_omacron = 0x3f2
XK_kcedilla = 0x3f3
XK_uogonek = 0x3f9
XK_utilde = 0x3fd
XK_umacron = 0x3fe
--[[
* Katakana
* Byte 3 = 4
]]--
XK_overline = 0x47e
XK_kana_fullstop = 0x4a1
XK_kana_openingbracket = 0x4a2
XK_kana_closingbracket = 0x4a3
XK_kana_comma = 0x4a4
XK_kana_conjunctive = 0x4a5
XK_kana_middledot = 0x4a5 --[[ deprecated ]]--
XK_kana_WO = 0x4a6
XK_kana_a = 0x4a7
XK_kana_i = 0x4a8
XK_kana_u = 0x4a9
XK_kana_e = 0x4aa
XK_kana_o = 0x4ab
XK_kana_ya = 0x4ac
XK_kana_yu = 0x4ad
XK_kana_yo = 0x4ae
XK_kana_tsu = 0x4af
XK_kana_tu = 0x4af --[[ deprecated ]]--
XK_prolongedsound = 0x4b0
XK_kana_A = 0x4b1
XK_kana_I = 0x4b2
XK_kana_U = 0x4b3
XK_kana_E = 0x4b4
XK_kana_O = 0x4b5
XK_kana_KA = 0x4b6
XK_kana_KI = 0x4b7
XK_kana_KU = 0x4b8
XK_kana_KE = 0x4b9
XK_kana_KO = 0x4ba
XK_kana_SA = 0x4bb
XK_kana_SHI = 0x4bc
XK_kana_SU = 0x4bd
XK_kana_SE = 0x4be
XK_kana_SO = 0x4bf
XK_kana_TA = 0x4c0
XK_kana_CHI = 0x4c1
XK_kana_TI = 0x4c1 --[[ deprecated ]]--
XK_kana_TSU = 0x4c2
XK_kana_TU = 0x4c2 --[[ deprecated ]]--
XK_kana_TE = 0x4c3
XK_kana_TO = 0x4c4
XK_kana_NA = 0x4c5
XK_kana_NI = 0x4c6
XK_kana_NU = 0x4c7
XK_kana_NE = 0x4c8
XK_kana_NO = 0x4c9
XK_kana_HA = 0x4ca
XK_kana_HI = 0x4cb
XK_kana_FU = 0x4cc
XK_kana_HU = 0x4cc --[[ deprecated ]]--
XK_kana_HE = 0x4cd
XK_kana_HO = 0x4ce
XK_kana_MA = 0x4cf
XK_kana_MI = 0x4d0
XK_kana_MU = 0x4d1
XK_kana_ME = 0x4d2
XK_kana_MO = 0x4d3
XK_kana_YA = 0x4d4
XK_kana_YU = 0x4d5
XK_kana_YO = 0x4d6
XK_kana_RA = 0x4d7
XK_kana_RI = 0x4d8
XK_kana_RU = 0x4d9
XK_kana_RE = 0x4da
XK_kana_RO = 0x4db
XK_kana_WA = 0x4dc
XK_kana_N = 0x4dd
XK_voicedsound = 0x4de
XK_semivoicedsound = 0x4df
XK_kana_switch = 0xFF7E --[[ Alias for mode_switch ]]--
--[[
* Arabic
* Byte 3 = 5
]]--
XK_Arabic_comma = 0x5ac
XK_Arabic_semicolon = 0x5bb
XK_Arabic_question_mark = 0x5bf
XK_Arabic_hamza = 0x5c1
XK_Arabic_maddaonalef = 0x5c2
XK_Arabic_hamzaonalef = 0x5c3
XK_Arabic_hamzaonwaw = 0x5c4
XK_Arabic_hamzaunderalef = 0x5c5
XK_Arabic_hamzaonyeh = 0x5c6
XK_Arabic_alef = 0x5c7
XK_Arabic_beh = 0x5c8
XK_Arabic_tehmarbuta = 0x5c9
XK_Arabic_teh = 0x5ca
XK_Arabic_theh = 0x5cb
XK_Arabic_jeem = 0x5cc
XK_Arabic_hah = 0x5cd
XK_Arabic_khah = 0x5ce
XK_Arabic_dal = 0x5cf
XK_Arabic_thal = 0x5d0
XK_Arabic_ra = 0x5d1
XK_Arabic_zain = 0x5d2
XK_Arabic_seen = 0x5d3
XK_Arabic_sheen = 0x5d4
XK_Arabic_sad = 0x5d5
XK_Arabic_dad = 0x5d6
XK_Arabic_tah = 0x5d7
XK_Arabic_zah = 0x5d8
XK_Arabic_ain = 0x5d9
XK_Arabic_ghain = 0x5da
XK_Arabic_tatweel = 0x5e0
XK_Arabic_feh = 0x5e1
XK_Arabic_qaf = 0x5e2
XK_Arabic_kaf = 0x5e3
XK_Arabic_lam = 0x5e4
XK_Arabic_meem = 0x5e5
XK_Arabic_noon = 0x5e6
XK_Arabic_ha = 0x5e7
XK_Arabic_heh = 0x5e7 --[[ deprecated ]]--
XK_Arabic_waw = 0x5e8
XK_Arabic_alefmaksura = 0x5e9
XK_Arabic_yeh = 0x5ea
XK_Arabic_fathatan = 0x5eb
XK_Arabic_dammatan = 0x5ec
XK_Arabic_kasratan = 0x5ed
XK_Arabic_fatha = 0x5ee
XK_Arabic_damma = 0x5ef
XK_Arabic_kasra = 0x5f0
XK_Arabic_shadda = 0x5f1
XK_Arabic_sukun = 0x5f2
XK_Arabic_switch = 0xFF7E --[[ Alias for mode_switch ]]--
--[[
* Cyrillic
* Byte 3 = 6
]]--
XK_Serbian_dje = 0x6a1
XK_Macedonia_gje = 0x6a2
XK_Cyrillic_io = 0x6a3
XK_Ukrainian_ie = 0x6a4
XK_Ukranian_je = 0x6a4 --[[ deprecated ]]--
XK_Macedonia_dse = 0x6a5
XK_Ukrainian_i = 0x6a6
XK_Ukranian_i = 0x6a6 --[[ deprecated ]]--
XK_Ukrainian_yi = 0x6a7
XK_Ukranian_yi = 0x6a7 --[[ deprecated ]]--
XK_Cyrillic_je = 0x6a8
XK_Serbian_je = 0x6a8 --[[ deprecated ]]--
XK_Cyrillic_lje = 0x6a9
XK_Serbian_lje = 0x6a9 --[[ deprecated ]]--
XK_Cyrillic_nje = 0x6aa
XK_Serbian_nje = 0x6aa --[[ deprecated ]]--
XK_Serbian_tshe = 0x6ab
XK_Macedonia_kje = 0x6ac
XK_Byelorussian_shortu = 0x6ae
XK_Cyrillic_dzhe = 0x6af
XK_Serbian_dze = 0x6af --[[ deprecated ]]--
XK_numerosign = 0x6b0
XK_Serbian_DJE = 0x6b1
XK_Macedonia_GJE = 0x6b2
XK_Cyrillic_IO = 0x6b3
XK_Ukrainian_IE = 0x6b4
XK_Ukranian_JE = 0x6b4 --[[ deprecated ]]--
XK_Macedonia_DSE = 0x6b5
XK_Ukrainian_I = 0x6b6
XK_Ukranian_I = 0x6b6 --[[ deprecated ]]--
XK_Ukrainian_YI = 0x6b7
XK_Ukranian_YI = 0x6b7 --[[ deprecated ]]--
XK_Cyrillic_JE = 0x6b8
XK_Serbian_JE = 0x6b8 --[[ deprecated ]]--
XK_Cyrillic_LJE = 0x6b9
XK_Serbian_LJE = 0x6b9 --[[ deprecated ]]--
XK_Cyrillic_NJE = 0x6ba
XK_Serbian_NJE = 0x6ba --[[ deprecated ]]--
XK_Serbian_TSHE = 0x6bb
XK_Macedonia_KJE = 0x6bc
XK_Byelorussian_SHORTU = 0x6be
XK_Cyrillic_DZHE = 0x6bf
XK_Serbian_DZE = 0x6bf --[[ deprecated ]]--
XK_Cyrillic_yu = 0x6c0
XK_Cyrillic_a = 0x6c1
XK_Cyrillic_be = 0x6c2
XK_Cyrillic_tse = 0x6c3
XK_Cyrillic_de = 0x6c4
XK_Cyrillic_ie = 0x6c5
XK_Cyrillic_ef = 0x6c6
XK_Cyrillic_ghe = 0x6c7
XK_Cyrillic_ha = 0x6c8
XK_Cyrillic_i = 0x6c9
XK_Cyrillic_shorti = 0x6ca
XK_Cyrillic_ka = 0x6cb
XK_Cyrillic_el = 0x6cc
XK_Cyrillic_em = 0x6cd
XK_Cyrillic_en = 0x6ce
XK_Cyrillic_o = 0x6cf
XK_Cyrillic_pe = 0x6d0
XK_Cyrillic_ya = 0x6d1
XK_Cyrillic_er = 0x6d2
XK_Cyrillic_es = 0x6d3
XK_Cyrillic_te = 0x6d4
XK_Cyrillic_u = 0x6d5
XK_Cyrillic_zhe = 0x6d6
XK_Cyrillic_ve = 0x6d7
XK_Cyrillic_softsign = 0x6d8
XK_Cyrillic_yeru = 0x6d9
XK_Cyrillic_ze = 0x6da
XK_Cyrillic_sha = 0x6db
XK_Cyrillic_e = 0x6dc
XK_Cyrillic_shcha = 0x6dd
XK_Cyrillic_che = 0x6de
XK_Cyrillic_hardsign = 0x6df
XK_Cyrillic_YU = 0x6e0
XK_Cyrillic_A = 0x6e1
XK_Cyrillic_BE = 0x6e2
XK_Cyrillic_TSE = 0x6e3
XK_Cyrillic_DE = 0x6e4
XK_Cyrillic_IE = 0x6e5
XK_Cyrillic_EF = 0x6e6
XK_Cyrillic_GHE = 0x6e7
XK_Cyrillic_HA = 0x6e8
XK_Cyrillic_I = 0x6e9
XK_Cyrillic_SHORTI = 0x6ea
XK_Cyrillic_KA = 0x6eb
XK_Cyrillic_EL = 0x6ec
XK_Cyrillic_EM = 0x6ed
XK_Cyrillic_EN = 0x6ee
XK_Cyrillic_O = 0x6ef
XK_Cyrillic_PE = 0x6f0
XK_Cyrillic_YA = 0x6f1
XK_Cyrillic_ER = 0x6f2
XK_Cyrillic_ES = 0x6f3
XK_Cyrillic_TE = 0x6f4
XK_Cyrillic_U = 0x6f5
XK_Cyrillic_ZHE = 0x6f6
XK_Cyrillic_VE = 0x6f7
XK_Cyrillic_SOFTSIGN = 0x6f8
XK_Cyrillic_YERU = 0x6f9
XK_Cyrillic_ZE = 0x6fa
XK_Cyrillic_SHA = 0x6fb
XK_Cyrillic_E = 0x6fc
XK_Cyrillic_SHCHA = 0x6fd
XK_Cyrillic_CHE = 0x6fe
XK_Cyrillic_HARDSIGN = 0x6ff
--[[
* Greek
* Byte 3 = 7
]]--
XK_Greek_ALPHAaccent = 0x7a1
XK_Greek_EPSILONaccent = 0x7a2
XK_Greek_ETAaccent = 0x7a3
XK_Greek_IOTAaccent = 0x7a4
XK_Greek_IOTAdieresis = 0x7a5
XK_Greek_OMICRONaccent = 0x7a7
XK_Greek_UPSILONaccent = 0x7a8
XK_Greek_UPSILONdieresis = 0x7a9
XK_Greek_OMEGAaccent = 0x7ab
XK_Greek_accentdieresis = 0x7ae
XK_Greek_horizbar = 0x7af
XK_Greek_alphaaccent = 0x7b1
XK_Greek_epsilonaccent = 0x7b2
XK_Greek_etaaccent = 0x7b3
XK_Greek_iotaaccent = 0x7b4
XK_Greek_iotadieresis = 0x7b5
XK_Greek_iotaaccentdieresis = 0x7b6
XK_Greek_omicronaccent = 0x7b7
XK_Greek_upsilonaccent = 0x7b8
XK_Greek_upsilondieresis = 0x7b9
XK_Greek_upsilonaccentdieresis = 0x7ba
XK_Greek_omegaaccent = 0x7bb
XK_Greek_ALPHA = 0x7c1
XK_Greek_BETA = 0x7c2
XK_Greek_GAMMA = 0x7c3
XK_Greek_DELTA = 0x7c4
XK_Greek_EPSILON = 0x7c5
XK_Greek_ZETA = 0x7c6
XK_Greek_ETA = 0x7c7
XK_Greek_THETA = 0x7c8
XK_Greek_IOTA = 0x7c9
XK_Greek_KAPPA = 0x7ca
XK_Greek_LAMDA = 0x7cb
XK_Greek_LAMBDA = 0x7cb
XK_Greek_MU = 0x7cc
XK_Greek_NU = 0x7cd
XK_Greek_XI = 0x7ce
XK_Greek_OMICRON = 0x7cf
XK_Greek_PI = 0x7d0
XK_Greek_RHO = 0x7d1
XK_Greek_SIGMA = 0x7d2
XK_Greek_TAU = 0x7d4
XK_Greek_UPSILON = 0x7d5
XK_Greek_PHI = 0x7d6
XK_Greek_CHI = 0x7d7
XK_Greek_PSI = 0x7d8
XK_Greek_OMEGA = 0x7d9
XK_Greek_alpha = 0x7e1
XK_Greek_beta = 0x7e2
XK_Greek_gamma = 0x7e3
XK_Greek_delta = 0x7e4
XK_Greek_epsilon = 0x7e5
XK_Greek_zeta = 0x7e6
XK_Greek_eta = 0x7e7
XK_Greek_theta = 0x7e8
XK_Greek_iota = 0x7e9
XK_Greek_kappa = 0x7ea
XK_Greek_lamda = 0x7eb
XK_Greek_lambda = 0x7eb
XK_Greek_mu = 0x7ec
XK_Greek_nu = 0x7ed
XK_Greek_xi = 0x7ee
XK_Greek_omicron = 0x7ef
XK_Greek_pi = 0x7f0
XK_Greek_rho = 0x7f1
XK_Greek_sigma = 0x7f2
XK_Greek_finalsmallsigma = 0x7f3
XK_Greek_tau = 0x7f4
XK_Greek_upsilon = 0x7f5
XK_Greek_phi = 0x7f6
XK_Greek_chi = 0x7f7
XK_Greek_psi = 0x7f8
XK_Greek_omega = 0x7f9
XK_Greek_switch = 0xFF7E --[[ Alias for mode_switch ]]--
--[[
* Technical
* Byte 3 = 8
]]--
XK_leftradical = 0x8a1
XK_topleftradical = 0x8a2
XK_horizconnector = 0x8a3
XK_topintegral = 0x8a4
XK_botintegral = 0x8a5
XK_vertconnector = 0x8a6
XK_topleftsqbracket = 0x8a7
XK_botleftsqbracket = 0x8a8
XK_toprightsqbracket = 0x8a9
XK_botrightsqbracket = 0x8aa
XK_topleftparens = 0x8ab
XK_botleftparens = 0x8ac
XK_toprightparens = 0x8ad
XK_botrightparens = 0x8ae
XK_leftmiddlecurlybrace = 0x8af
XK_rightmiddlecurlybrace = 0x8b0
XK_topleftsummation = 0x8b1
XK_botleftsummation = 0x8b2
XK_topvertsummationconnector = 0x8b3
XK_botvertsummationconnector = 0x8b4
XK_toprightsummation = 0x8b5
XK_botrightsummation = 0x8b6
XK_rightmiddlesummation = 0x8b7
XK_lessthanequal = 0x8bc
XK_notequal = 0x8bd
XK_greaterthanequal = 0x8be
XK_integral = 0x8bf
XK_therefore = 0x8c0
XK_variation = 0x8c1
XK_infinity = 0x8c2
XK_nabla = 0x8c5
XK_approximate = 0x8c8
XK_similarequal = 0x8c9
XK_ifonlyif = 0x8cd
XK_implies = 0x8ce
XK_identical = 0x8cf
XK_radical = 0x8d6
XK_includedin = 0x8da
XK_includes = 0x8db
XK_intersection = 0x8dc
XK_union = 0x8dd
XK_logicaland = 0x8de
XK_logicalor = 0x8df
XK_partialderivative = 0x8ef
XK_function = 0x8f6
XK_leftarrow = 0x8fb
XK_uparrow = 0x8fc
XK_rightarrow = 0x8fd
XK_downarrow = 0x8fe
--[[
* Special
* Byte 3 = 9
]]--
XK_blank = 0x9df
XK_soliddiamond = 0x9e0
XK_checkerboard = 0x9e1
XK_ht = 0x9e2
XK_ff = 0x9e3
XK_cr = 0x9e4
XK_lf = 0x9e5
XK_nl = 0x9e8
XK_vt = 0x9e9
XK_lowrightcorner = 0x9ea
XK_uprightcorner = 0x9eb
XK_upleftcorner = 0x9ec
XK_lowleftcorner = 0x9ed
XK_crossinglines = 0x9ee
XK_horizlinescan1 = 0x9ef
XK_horizlinescan3 = 0x9f0
XK_horizlinescan5 = 0x9f1
XK_horizlinescan7 = 0x9f2
XK_horizlinescan9 = 0x9f3
XK_leftt = 0x9f4
XK_rightt = 0x9f5
XK_bott = 0x9f6
XK_topt = 0x9f7
XK_vertbar = 0x9f8
--[[
* Publishing
* Byte 3 = a
]]--
XK_emspace = 0xaa1
XK_enspace = 0xaa2
XK_em3space = 0xaa3
XK_em4space = 0xaa4
XK_digitspace = 0xaa5
XK_punctspace = 0xaa6
XK_thinspace = 0xaa7
XK_hairspace = 0xaa8
XK_emdash = 0xaa9
XK_endash = 0xaaa
XK_signifblank = 0xaac
XK_ellipsis = 0xaae
XK_doubbaselinedot = 0xaaf
XK_onethird = 0xab0
XK_twothirds = 0xab1
XK_onefifth = 0xab2
XK_twofifths = 0xab3
XK_threefifths = 0xab4
XK_fourfifths = 0xab5
XK_onesixth = 0xab6
XK_fivesixths = 0xab7
XK_careof = 0xab8
XK_figdash = 0xabb
XK_leftanglebracket = 0xabc
XK_decimalpoint = 0xabd
XK_rightanglebracket = 0xabe
XK_marker = 0xabf
XK_oneeighth = 0xac3
XK_threeeighths = 0xac4
XK_fiveeighths = 0xac5
XK_seveneighths = 0xac6
XK_trademark = 0xac9
XK_signaturemark = 0xaca
XK_trademarkincircle = 0xacb
XK_leftopentriangle = 0xacc
XK_rightopentriangle = 0xacd
XK_emopencircle = 0xace
XK_emopenrectangle = 0xacf
XK_leftsinglequotemark = 0xad0
XK_rightsinglequotemark = 0xad1
XK_leftdoublequotemark = 0xad2
XK_rightdoublequotemark = 0xad3
XK_prescription = 0xad4
XK_minutes = 0xad6
XK_seconds = 0xad7
XK_latincross = 0xad9
XK_hexagram = 0xada
XK_filledrectbullet = 0xadb
XK_filledlefttribullet = 0xadc
XK_filledrighttribullet = 0xadd
XK_emfilledcircle = 0xade
XK_emfilledrect = 0xadf
XK_enopencircbullet = 0xae0
XK_enopensquarebullet = 0xae1
XK_openrectbullet = 0xae2
XK_opentribulletup = 0xae3
XK_opentribulletdown = 0xae4
XK_openstar = 0xae5
XK_enfilledcircbullet = 0xae6
XK_enfilledsqbullet = 0xae7
XK_filledtribulletup = 0xae8
XK_filledtribulletdown = 0xae9
XK_leftpointer = 0xaea
XK_rightpointer = 0xaeb
XK_club = 0xaec
XK_diamond = 0xaed
XK_heart = 0xaee
XK_maltesecross = 0xaf0
XK_dagger = 0xaf1
XK_doubledagger = 0xaf2
XK_checkmark = 0xaf3
XK_ballotcross = 0xaf4
XK_musicalsharp = 0xaf5
XK_musicalflat = 0xaf6
XK_malesymbol = 0xaf7
XK_femalesymbol = 0xaf8
XK_telephone = 0xaf9
XK_telephonerecorder = 0xafa
XK_phonographcopyright = 0xafb
XK_caret = 0xafc
XK_singlelowquotemark = 0xafd
XK_doublelowquotemark = 0xafe
XK_cursor = 0xaff
--[[
* APL
* Byte 3 = b
]]--
XK_leftcaret = 0xba3
XK_rightcaret = 0xba6
XK_downcaret = 0xba8
XK_upcaret = 0xba9
XK_overbar = 0xbc0
XK_downtack = 0xbc2
XK_upshoe = 0xbc3
XK_downstile = 0xbc4
XK_underbar = 0xbc6
XK_jot = 0xbca
XK_quad = 0xbcc
XK_uptack = 0xbce
XK_circle = 0xbcf
XK_upstile = 0xbd3
XK_downshoe = 0xbd6
XK_rightshoe = 0xbd8
XK_leftshoe = 0xbda
XK_lefttack = 0xbdc
XK_righttack = 0xbfc
--[[
* Hebrew
* Byte 3 = c
]]--
XK_hebrew_doublelowline = 0xcdf
XK_hebrew_aleph = 0xce0
XK_hebrew_bet = 0xce1
XK_hebrew_beth = 0xce1 --[[ deprecated ]]--
XK_hebrew_gimel = 0xce2
XK_hebrew_gimmel = 0xce2 --[[ deprecated ]]--
XK_hebrew_dalet = 0xce3
XK_hebrew_daleth = 0xce3 --[[ deprecated ]]--
XK_hebrew_he = 0xce4
XK_hebrew_waw = 0xce5
XK_hebrew_zain = 0xce6
XK_hebrew_zayin = 0xce6 --[[ deprecated ]]--
XK_hebrew_chet = 0xce7
XK_hebrew_het = 0xce7 --[[ deprecated ]]--
XK_hebrew_tet = 0xce8
XK_hebrew_teth = 0xce8 --[[ deprecated ]]--
XK_hebrew_yod = 0xce9
XK_hebrew_finalkaph = 0xcea
XK_hebrew_kaph = 0xceb
XK_hebrew_lamed = 0xcec
XK_hebrew_finalmem = 0xced
XK_hebrew_mem = 0xcee
XK_hebrew_finalnun = 0xcef
XK_hebrew_nun = 0xcf0
XK_hebrew_samech = 0xcf1
XK_hebrew_samekh = 0xcf1 --[[ deprecated ]]--
XK_hebrew_ayin = 0xcf2
XK_hebrew_finalpe = 0xcf3
XK_hebrew_pe = 0xcf4
XK_hebrew_finalzade = 0xcf5
XK_hebrew_finalzadi = 0xcf5 --[[ deprecated ]]--
XK_hebrew_zade = 0xcf6
XK_hebrew_zadi = 0xcf6 --[[ deprecated ]]--
XK_hebrew_qoph = 0xcf7
XK_hebrew_kuf = 0xcf7 --[[ deprecated ]]--
XK_hebrew_resh = 0xcf8
XK_hebrew_shin = 0xcf9
XK_hebrew_taw = 0xcfa
XK_hebrew_taf = 0xcfa --[[ deprecated ]]--
XK_Hebrew_switch = 0xFF7E --[[ Alias for mode_switch ]]--
--[[
* Thai
* Byte 3 = d
]]--
XK_Thai_kokai = 0xda1
XK_Thai_khokhai = 0xda2
XK_Thai_khokhuat = 0xda3
XK_Thai_khokhwai = 0xda4
XK_Thai_khokhon = 0xda5
XK_Thai_khorakhang = 0xda6
XK_Thai_ngongu = 0xda7
XK_Thai_chochan = 0xda8
XK_Thai_choching = 0xda9
XK_Thai_chochang = 0xdaa
XK_Thai_soso = 0xdab
XK_Thai_chochoe = 0xdac
XK_Thai_yoying = 0xdad
XK_Thai_dochada = 0xdae
XK_Thai_topatak = 0xdaf
XK_Thai_thothan = 0xdb0
XK_Thai_thonangmontho = 0xdb1
XK_Thai_thophuthao = 0xdb2
XK_Thai_nonen = 0xdb3
XK_Thai_dodek = 0xdb4
XK_Thai_totao = 0xdb5
XK_Thai_thothung = 0xdb6
XK_Thai_thothahan = 0xdb7
XK_Thai_thothong = 0xdb8
XK_Thai_nonu = 0xdb9
XK_Thai_bobaimai = 0xdba
XK_Thai_popla = 0xdbb
XK_Thai_phophung = 0xdbc
XK_Thai_fofa = 0xdbd
XK_Thai_phophan = 0xdbe
XK_Thai_fofan = 0xdbf
XK_Thai_phosamphao = 0xdc0
XK_Thai_moma = 0xdc1
XK_Thai_yoyak = 0xdc2
XK_Thai_rorua = 0xdc3
XK_Thai_ru = 0xdc4
XK_Thai_loling = 0xdc5
XK_Thai_lu = 0xdc6
XK_Thai_wowaen = 0xdc7
XK_Thai_sosala = 0xdc8
XK_Thai_sorusi = 0xdc9
XK_Thai_sosua = 0xdca
XK_Thai_hohip = 0xdcb
XK_Thai_lochula = 0xdcc
XK_Thai_oang = 0xdcd
XK_Thai_honokhuk = 0xdce
XK_Thai_paiyannoi = 0xdcf
XK_Thai_saraa = 0xdd0
XK_Thai_maihanakat = 0xdd1
XK_Thai_saraaa = 0xdd2
XK_Thai_saraam = 0xdd3
XK_Thai_sarai = 0xdd4
XK_Thai_saraii = 0xdd5
XK_Thai_saraue = 0xdd6
XK_Thai_sarauee = 0xdd7
XK_Thai_sarau = 0xdd8
XK_Thai_sarauu = 0xdd9
XK_Thai_phinthu = 0xdda
XK_Thai_maihanakat_maitho = 0xdde
XK_Thai_baht = 0xddf
XK_Thai_sarae = 0xde0
XK_Thai_saraae = 0xde1
XK_Thai_sarao = 0xde2
XK_Thai_saraaimaimuan = 0xde3
XK_Thai_saraaimaimalai = 0xde4
XK_Thai_lakkhangyao = 0xde5
XK_Thai_maiyamok = 0xde6
XK_Thai_maitaikhu = 0xde7
XK_Thai_maiek = 0xde8
XK_Thai_maitho = 0xde9
XK_Thai_maitri = 0xdea
XK_Thai_maichattawa = 0xdeb
XK_Thai_thanthakhat = 0xdec
XK_Thai_nikhahit = 0xded
XK_Thai_leksun = 0xdf0
XK_Thai_leknung = 0xdf1
XK_Thai_leksong = 0xdf2
XK_Thai_leksam = 0xdf3
XK_Thai_leksi = 0xdf4
XK_Thai_lekha = 0xdf5
XK_Thai_lekhok = 0xdf6
XK_Thai_lekchet = 0xdf7
XK_Thai_lekpaet = 0xdf8
XK_Thai_lekkao = 0xdf9
--[[
* Korean
* Byte 3 = e
]]--
XK_Hangul = 0xff31 --[[ Hangul start/stop(toggle) ]]--
XK_Hangul_Start = 0xff32 --[[ Hangul start ]]--
XK_Hangul_End = 0xff33 --[[ Hangul end, English start ]]--
XK_Hangul_Hanja = 0xff34 --[[ Start Hangul->Hanja Conversion ]]--
XK_Hangul_Jamo = 0xff35 --[[ Hangul Jamo mode ]]--
XK_Hangul_Romaja = 0xff36 --[[ Hangul Romaja mode ]]--
XK_Hangul_Codeinput = 0xff37 --[[ Hangul code input mode ]]--
XK_Hangul_Jeonja = 0xff38 --[[ Jeonja mode ]]--
XK_Hangul_Banja = 0xff39 --[[ Banja mode ]]--
XK_Hangul_PreHanja = 0xff3a --[[ Pre Hanja conversion ]]--
XK_Hangul_PostHanja = 0xff3b --[[ Post Hanja conversion ]]--
XK_Hangul_SingleCandidate = 0xff3c --[[ Single candidate ]]--
XK_Hangul_MultipleCandidate = 0xff3d --[[ Multiple candidate ]]--
XK_Hangul_PreviousCandidate = 0xff3e --[[ Previous candidate ]]--
XK_Hangul_Special = 0xff3f --[[ Special symbols ]]--
XK_Hangul_switch = 0xFF7E --[[ Alias for mode_switch ]]--
--[[ Hangul Consonant Characters ]]--
XK_Hangul_Kiyeog = 0xea1
XK_Hangul_SsangKiyeog = 0xea2
XK_Hangul_KiyeogSios = 0xea3
XK_Hangul_Nieun = 0xea4
XK_Hangul_NieunJieuj = 0xea5
XK_Hangul_NieunHieuh = 0xea6
XK_Hangul_Dikeud = 0xea7
XK_Hangul_SsangDikeud = 0xea8
XK_Hangul_Rieul = 0xea9
XK_Hangul_RieulKiyeog = 0xeaa
XK_Hangul_RieulMieum = 0xeab
XK_Hangul_RieulPieub = 0xeac
XK_Hangul_RieulSios = 0xead
XK_Hangul_RieulTieut = 0xeae
XK_Hangul_RieulPhieuf = 0xeaf
XK_Hangul_RieulHieuh = 0xeb0
XK_Hangul_Mieum = 0xeb1
XK_Hangul_Pieub = 0xeb2
XK_Hangul_SsangPieub = 0xeb3
XK_Hangul_PieubSios = 0xeb4
XK_Hangul_Sios = 0xeb5
XK_Hangul_SsangSios = 0xeb6
XK_Hangul_Ieung = 0xeb7
XK_Hangul_Jieuj = 0xeb8
XK_Hangul_SsangJieuj = 0xeb9
XK_Hangul_Cieuc = 0xeba
XK_Hangul_Khieuq = 0xebb
XK_Hangul_Tieut = 0xebc
XK_Hangul_Phieuf = 0xebd
XK_Hangul_Hieuh = 0xebe
--[[ Hangul Vowel Characters ]]--
XK_Hangul_A = 0xebf
XK_Hangul_AE = 0xec0
XK_Hangul_YA = 0xec1
XK_Hangul_YAE = 0xec2
XK_Hangul_EO = 0xec3
XK_Hangul_E = 0xec4
XK_Hangul_YEO = 0xec5
XK_Hangul_YE = 0xec6
XK_Hangul_O = 0xec7
XK_Hangul_WA = 0xec8
XK_Hangul_WAE = 0xec9
XK_Hangul_OE = 0xeca
XK_Hangul_YO = 0xecb
XK_Hangul_U = 0xecc
XK_Hangul_WEO = 0xecd
XK_Hangul_WE = 0xece
XK_Hangul_WI = 0xecf
XK_Hangul_YU = 0xed0
XK_Hangul_EU = 0xed1
XK_Hangul_YI = 0xed2
XK_Hangul_I = 0xed3
--[[ Hangul syllable-final (JongSeong) Characters ]]--
XK_Hangul_J_Kiyeog = 0xed4
XK_Hangul_J_SsangKiyeog = 0xed5
XK_Hangul_J_KiyeogSios = 0xed6
XK_Hangul_J_Nieun = 0xed7
XK_Hangul_J_NieunJieuj = 0xed8
XK_Hangul_J_NieunHieuh = 0xed9
XK_Hangul_J_Dikeud = 0xeda
XK_Hangul_J_Rieul = 0xedb
XK_Hangul_J_RieulKiyeog = 0xedc
XK_Hangul_J_RieulMieum = 0xedd
XK_Hangul_J_RieulPieub = 0xede
XK_Hangul_J_RieulSios = 0xedf
XK_Hangul_J_RieulTieut = 0xee0
XK_Hangul_J_RieulPhieuf = 0xee1
XK_Hangul_J_RieulHieuh = 0xee2
XK_Hangul_J_Mieum = 0xee3
XK_Hangul_J_Pieub = 0xee4
XK_Hangul_J_PieubSios = 0xee5
XK_Hangul_J_Sios = 0xee6
XK_Hangul_J_SsangSios = 0xee7
XK_Hangul_J_Ieung = 0xee8
XK_Hangul_J_Jieuj = 0xee9
XK_Hangul_J_Cieuc = 0xeea
XK_Hangul_J_Khieuq = 0xeeb
XK_Hangul_J_Tieut = 0xeec
XK_Hangul_J_Phieuf = 0xeed
XK_Hangul_J_Hieuh = 0xeee
--[[ Ancient Hangul Consonant Characters ]]--
XK_Hangul_RieulYeorinHieuh = 0xeef
XK_Hangul_SunkyeongeumMieum = 0xef0
XK_Hangul_SunkyeongeumPieub = 0xef1
XK_Hangul_PanSios = 0xef2
XK_Hangul_KkogjiDalrinIeung = 0xef3
XK_Hangul_SunkyeongeumPhieuf = 0xef4
XK_Hangul_YeorinHieuh = 0xef5
--[[ Ancient Hangul Vowel Characters ]]--
XK_Hangul_AraeA = 0xef6
XK_Hangul_AraeAE = 0xef7
--[[ Ancient Hangul syllable-final (JongSeong) Characters ]]--
XK_Hangul_J_PanSios = 0xef8
XK_Hangul_J_KkogjiDalrinIeung = 0xef9
XK_Hangul_J_YeorinHieuh = 0xefa
--[[ Korean currency symbol ]]--
XK_Korean_Won = 0xeff
--[[ Euro currency symbol ]]--
XK_EuroSign = 0x20ac
| gpl-2.0 |
O-P-E-N/CC-ROUTER | feeds/luci/modules/luci-base/luasrc/model/uci.lua | 49 | 4995 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local os = require "os"
local uci = require "uci"
local util = require "luci.util"
local table = require "table"
local setmetatable, rawget, rawset = setmetatable, rawget, rawset
local require, getmetatable = require, getmetatable
local error, pairs, ipairs = error, pairs, ipairs
local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack
-- The typical workflow for UCI is: Get a cursor instance from the
-- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.),
-- save the changes to the staging area via Cursor.save and finally
-- Cursor.commit the data to the actual config files.
-- LuCI then needs to Cursor.apply the changes so deamons etc. are
-- reloaded.
module "luci.model.uci"
cursor = uci.cursor
APIVERSION = uci.APIVERSION
function cursor_state()
return cursor(nil, "/var/state")
end
inst = cursor()
inst_state = cursor_state()
local Cursor = getmetatable(inst)
function Cursor.apply(self, configlist, command)
configlist = self:_affected(configlist)
if command then
return { "/sbin/luci-reload", unpack(configlist) }
else
return os.execute("/sbin/luci-reload %s >/dev/null 2>&1"
% table.concat(configlist, " "))
end
end
-- returns a boolean whether to delete the current section (optional)
function Cursor.delete_all(self, config, stype, comparator)
local del = {}
if type(comparator) == "table" then
local tbl = comparator
comparator = function(section)
for k, v in pairs(tbl) do
if section[k] ~= v then
return false
end
end
return true
end
end
local function helper (section)
if not comparator or comparator(section) then
del[#del+1] = section[".name"]
end
end
self:foreach(config, stype, helper)
for i, j in ipairs(del) do
self:delete(config, j)
end
end
function Cursor.section(self, config, type, name, values)
local stat = true
if name then
stat = self:set(config, name, type)
else
name = self:add(config, type)
stat = name and true
end
if stat and values then
stat = self:tset(config, name, values)
end
return stat and name
end
function Cursor.tset(self, config, section, values)
local stat = true
for k, v in pairs(values) do
if k:sub(1, 1) ~= "." then
stat = stat and self:set(config, section, k, v)
end
end
return stat
end
function Cursor.get_bool(self, ...)
local val = self:get(...)
return ( val == "1" or val == "true" or val == "yes" or val == "on" )
end
function Cursor.get_list(self, config, section, option)
if config and section and option then
local val = self:get(config, section, option)
return ( type(val) == "table" and val or { val } )
end
return nil
end
function Cursor.get_first(self, conf, stype, opt, def)
local rv = def
self:foreach(conf, stype,
function(s)
local val = not opt and s['.name'] or s[opt]
if type(def) == "number" then
val = tonumber(val)
elseif type(def) == "boolean" then
val = (val == "1" or val == "true" or
val == "yes" or val == "on")
end
if val ~= nil then
rv = val
return false
end
end)
return rv
end
function Cursor.set_list(self, config, section, option, value)
if config and section and option then
return self:set(
config, section, option,
( type(value) == "table" and value or { value } )
)
end
return false
end
-- Return a list of initscripts affected by configuration changes.
function Cursor._affected(self, configlist)
configlist = type(configlist) == "table" and configlist or {configlist}
local c = cursor()
c:load("ucitrack")
-- Resolve dependencies
local reloadlist = {}
local function _resolve_deps(name)
local reload = {name}
local deps = {}
c:foreach("ucitrack", name,
function(section)
if section.affects then
for i, aff in ipairs(section.affects) do
deps[#deps+1] = aff
end
end
end)
for i, dep in ipairs(deps) do
for j, add in ipairs(_resolve_deps(dep)) do
reload[#reload+1] = add
end
end
return reload
end
-- Collect initscripts
for j, config in ipairs(configlist) do
for i, e in ipairs(_resolve_deps(config)) do
if not util.contains(reloadlist, e) then
reloadlist[#reloadlist+1] = e
end
end
end
return reloadlist
end
-- curser, means it the parent unloads or loads configs, the sub state will
-- do so as well.
function Cursor.substate(self)
Cursor._substates = Cursor._substates or { }
Cursor._substates[self] = Cursor._substates[self] or cursor_state()
return Cursor._substates[self]
end
local _load = Cursor.load
function Cursor.load(self, ...)
if Cursor._substates and Cursor._substates[self] then
_load(Cursor._substates[self], ...)
end
return _load(self, ...)
end
local _unload = Cursor.unload
function Cursor.unload(self, ...)
if Cursor._substates and Cursor._substates[self] then
_unload(Cursor._substates[self], ...)
end
return _unload(self, ...)
end
| gpl-2.0 |
starlightknight/darkstar | scripts/globals/mobskills/pw_groundburst.lua | 11 | 1089 | ---------------------------------------------
-- Groundburst
--
-- Description: Expels a fireball on targets in an area of effect.
-- Type: Physical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: Unknown radial
-- Notes: Only used by notorious monsters, and from any Mamool Ja in besieged.
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobSkin = mob:getModelId()
if (mobSkin == 1863) then
return 0
else
return 1
end
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local accmod = 1
local dmgmod = 3
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT)
return dmg
end | gpl-3.0 |
starlightknight/darkstar | scripts/commands/getmod.lua | 12 | 1470 | ---------------------------------------------------------------------------------------------------
-- func: getmod <modID>
-- desc: gets a mod by ID on the player or cursor target
---------------------------------------------------------------------------------------------------
require("scripts/globals/status")
cmdprops =
{
permission = 3,
parameters = "s"
}
function error(player, msg)
player:PrintToPlayer(msg)
player:PrintToPlayer("!getmod <modID>")
end
function onTrigger(player, id)
-- invert dsp.mod table
local modNameByNum = {}
for k,v in pairs(dsp.mod) do
modNameByNum[v]=k
end
-- validate modID
id = string.upper(id)
local modId = tonumber(id)
local modName = nil
if modId ~= nil then
if modNameByNum[modId] ~= nil then
modName = modNameByNum[modId]
end
elseif dsp.mod[id] ~= nil then
modId = dsp.mod[id]
modName = id
end
if modName == nil or modId == nil then
error(player, "Invalid modID.")
return
end
-- validate target
local effectTarget = player:getCursorTarget()
if effectTarget == nil then
effectTarget = player
elseif effectTarget:isNPC() then
error(player, "Current target is an NPC, which can not have mods.")
return
end
player:PrintToPlayer(string.format("%s's Mod %i (%s) is %i", effectTarget:getName(), modId, modName, effectTarget:getMod(modId)))
end
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Beaucedine_Glacier/npcs/Torino-Samarino.lua | 9 | 2648 | -----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Torino-Samarino
-- Type: Quest NPC
-- Involved in Quests: Curses, Foiled A-Golem!?, Tuning Out
-- !pos 105 -20 140 111
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
local ID = require("scripts/zones/Beaucedine_Glacier/IDs");
require("scripts/globals/keyitems");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local FoiledAGolem = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.CURSES_FOILED_A_GOLEM);
-- Curses, Foiled A_Golem!?
if (player:hasKeyItem(dsp.ki.SHANTOTTOS_EXSPELL) and FoiledAGolem == QUEST_ACCEPTED) then
player:startEvent(108); -- key item taken, wait one game day for new spell
elseif (player:getCharVar("golemwait") == 1 and FoiledAGolem == QUEST_ACCEPTED) then
local gDay = VanadielDayOfTheYear();
local gYear = VanadielYear();
local dFinished = player:getCharVar("golemday");
local yFinished = player:getCharVar("golemyear");
if (gDay == dFinished and gYear == yFinished) then
player:startEvent(113); -- re-write reminder
elseif (gDay == dFinished + 1 and gYear == yFinished) then
player:startEvent(109); -- re-write done
end
elseif (player:getCharVar("foiledagolemdeliverycomplete") == 1) then
player:startEvent(110); -- talk to Shantotto reminder
elseif (FoiledAGolem == QUEST_ACCEPTED) then
player:startEvent(104); -- receive key item
else
player:startEvent(101); -- standard dialog
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
-- Curses, Foiled A_Golem!?
if (csid == 104 and option == 1) then
player:addKeyItem(dsp.ki.SHANTOTTOS_NEW_SPELL);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SHANTOTTOS_NEW_SPELL); -- add new spell key item
elseif (csid == 108) then -- start wait for new scroll
player:delKeyItem(dsp.ki.SHANTOTTOS_EXSPELL);
player:setCharVar("golemday",VanadielDayOfTheYear());
player:setCharVar("golemyear",VanadielYear());
player:setCharVar("golemwait",1);
elseif (csid == 109) then
player:addKeyItem(dsp.ki.SHANTOTTOS_NEW_SPELL);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SHANTOTTOS_NEW_SPELL); -- add new spell key item
player:setCharVar("golemday",0);
player:setCharVar("golemyear",0);
player:setCharVar("golemwait",0);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/RuLude_Gardens/npcs/Magian_Moogle_Blue.lua | 3 | 1857 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Magian Moogle (Blue Bobble)
-- Type: Magian Trials NPC (Relic Armor)
-- !pos -6.843 2.459 121.9 64
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
package.loaded["scripts/globals/magiantrials"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/RuLude_Gardens/TextIDs");
require("scripts/globals/magiantrials");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1) then
local ItemID = trade:getItemId();
local TrialInfo = getRelicTrialInfo(ItemID);
local invalid = 0;
if (TrialInfo.t1 == 0 and TrialInfo.t2 == 0 and TrialInfo.t3 == 0 and TrialInfo.t4 == 0) then
invalid = 1;
end
player:startEvent(10143, TrialInfo.t1, TrialInfo.t2, TrialInfo.t3, TrialInfo.t4, 0, ItemID, 0, invalid);
else
-- placeholder for multi item trades such as "Forgotten Hope" etc.
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(MAGIAN_TRIAL_LOG) == false) then
player:startEvent(10141);
else
player:startEvent(10142); -- parameters unknown
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
printf("CSID: %u",csid);
printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
printf("CSID: %u",csid);
printf("RESULT: %u",option);
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Southern_San_dOria/npcs/Raimbroy.lua | 3 | 3549 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Raimbroy
-- Starts and Finishes Quest: The Sweetest Things
-- @zone 230
-- !pos
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
-- "The Sweetest Things" quest status var
local theSweetestThings = player:getQuestStatus(SANDORIA,THE_SWEETEST_THINGS);
if (theSweetestThings ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(4370,5) and trade:getItemCount() == 5) then
player:startEvent(0x0217,GIL_RATE*400);
else
player:startEvent(0x020a);
end
end
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local theSweetestThings = player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS);
-- "The Sweetest Things" Quest Dialogs
if (player:getFameLevel(SANDORIA) >= 2 and theSweetestThings == QUEST_AVAILABLE) then
theSweetestThingsVar = player:getVar("theSweetestThings");
if (theSweetestThingsVar == 1) then
player:startEvent(0x0215);
elseif (theSweetestThingsVar == 2) then
player:startEvent(0x0216);
else
player:startEvent(0x0214);
end
elseif (theSweetestThings == QUEST_ACCEPTED) then
player:startEvent(0x0218);
elseif (theSweetestThings == QUEST_COMPLETED) then
player:startEvent(0x0219);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
-- "The Sweetest Things" ACCEPTED
if (csid == 0x0214) then
player:setVar("theSweetestThings", 1);
elseif (csid == 0x0215) then
if (option == 0) then
player:addQuest(SANDORIA,THE_SWEETEST_THINGS);
player:setVar("theSweetestThings", 0);
else
player:setVar("theSweetestThings", 2);
end
elseif (csid == 0x0216 and option == 0) then
player:addQuest(SANDORIA, THE_SWEETEST_THINGS);
player:setVar("theSweetestThings", 0);
elseif (csid == 0x0217) then
player:tradeComplete();
player:addTitle(APIARIST);
player:addGil(GIL_RATE*400);
if (player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA, THE_SWEETEST_THINGS);
else
player:addFame(SANDORIA, 5);
end
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Temple_of_Uggalepih/npcs/_4fz.lua | 3 | 1501 | -----------------------------------
-- Area: Temple of Uggalepih
-- NPC: Granite Door
-- Leads to painbrush room @ F-7
-- !pos 60 0.1 8 159
-----------------------------------
package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Temple_of_Uggalepih/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1136,1) and trade:getItemCount() == 1 and player:getZPos() < 11) then -- trade Uggalepih key
player:startEvent(0x002E);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() < 11) then
player:messageSpecial(THE_DOOR_IS_LOCKED,1136);
else
player:startEvent(0x002F);
end
return 0;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x002E) then
player:tradeComplete();
player:messageSpecial(YOUR_KEY_BREAKS,0000,1136);
end
end;
| gpl-3.0 |
RememberTheAir/GroupButler | lua/groupbutler/plugins/banhammer.lua | 1 | 8117 | local config = require "groupbutler.config"
local ChatMember = require("groupbutler.chatmember")
local User = require("groupbutler.user")
local _M = {}
function _M:new(update_obj)
local plugin_obj = {}
setmetatable(plugin_obj, {__index = self})
for k, v in pairs(update_obj) do
plugin_obj[k] = v
end
return plugin_obj
end
local function markup_tempban(self, chat_id, user_id, time_value)
local red = self.red
local key = ('chat:%s:%s:tbanvalue'):format(chat_id, user_id)
time_value = time_value or tonumber(red:get(key)) or 3
local markup = {inline_keyboard={
{--first line
{text = '-', callback_data = ('tempban:val:m:%s:%s'):format(user_id, chat_id)},
{text = "🕑 "..time_value, callback_data = "tempban:nil"},
{text = '+', callback_data = ('tempban:val:p:%s:%s'):format(user_id, chat_id)}
},
{--second line
{text = 'minutes', callback_data = ('tempban:ban:m:%s:%s'):format(user_id, chat_id)},
{text = 'hours', callback_data = ('tempban:ban:h:%s:%s'):format(user_id, chat_id)},
{text = 'days', callback_data = ('tempban:ban:d:%s:%s'):format(user_id, chat_id)},
}
}}
return markup
end
local function get_motivation(msg)
if msg.reply then
return msg.text:match(("%sban (.+)"):format(config.cmd))
or msg.text:match(("%skick (.+)"):format(config.cmd))
or msg.text:match(("%stempban .+\n(.+)"):format(config.cmd))
else
if msg.text:find(config.cmd.."ban @%w[%w_]+ ") or msg.text:find(config.cmd.."kick @%w[%w_]+ ") then
return msg.text:match(config.cmd.."ban @%w[%w_]+ (.+)") or msg.text:match(config.cmd.."kick @%w[%w_]+ (.+)")
elseif msg.text:find(config.cmd.."ban %d+ ") or msg.text:find(config.cmd.."kick %d+ ") then
return msg.text:match(config.cmd.."ban %d+ (.+)") or msg.text:match(config.cmd.."kick %d+ (.+)")
elseif msg.entities then
return msg.text:match(config.cmd.."ban .+\n(.+)") or msg.text:match(config.cmd.."kick .+\n(.+)")
end
end
end
function _M:onTextMessage(blocks)
local api = self.api
local msg = self.message
local bot = self.bot
local red = self.red
local i18n = self.i18n
local api_err = self.api_err
local u = self.u
if msg.from.chat.type == "private"
or not msg.from:can("can_restrict_members") then
return
end
local admin = msg.from
local target
do
local err
target, err = msg:getTargetMember(blocks)
if not target and blocks[1] ~= "fwdban" then
msg:send_reply(err, "Markdown")
return
end
end
if tonumber(target.user.id) == bot.id then return end
--print(get_motivation(msg))
if blocks[1] == 'tempban' then
local time_value = msg.text:match(("%stempban.*\n"):format(config.cmd).."(%d+)")
if time_value then --save the time value passed by the user
if tonumber(time_value) > 100 then
time_value = 100
end
local key = ('chat:%s:%s:tbanvalue'):format(msg.from.chat.id, target.user.id)
red:setex(key, 3600, time_value)
end
local markup = markup_tempban(self, msg.from.chat.id, target.user.id)
msg:send_reply(i18n("Use -/+ to edit the value, then select a timeframe to temporary ban the user"),
"Markdown", nil, nil, markup)
end
local text
if blocks[1] == 'kick' then
local ok, err = target:kick()
if not ok then
msg:send_reply(err, "Markdown")
return
end
u:logEvent("kick", msg, {
motivation = get_motivation(msg),
admin = admin.user,
user = target.user,
user_id = target.user.id
})
text = i18n("%s kicked %s!"):format(admin.user:getLink(), target.user:getLink())
api:sendMessage(msg.from.chat.id, text, "html", true)
end
if blocks[1] == 'ban' then
local ok, err = target:ban()
if not ok then
msg:send_reply(err, "Markdown")
end
u:logEvent("ban", msg, {
motivation = get_motivation(msg),
admin = admin.user,
user = target.user,
user_id = target.user.id
})
text = i18n("%s banned %s!"):format(admin.user:getLink(), target.user:getLink())
api:sendMessage(msg.from.chat.id, text, "html", true)
end
if blocks[1] == 'fwdban' then
if not msg.reply or not msg.reply.forward_from then
msg:send_reply(i18n("_Use this command in reply to a forwarded message_"), "Markdown")
return
end
target = msg.reply.forward_from
local ok, err = target:ban()
if not ok then
msg:send_reply(err, "Markdown")
end
u:logEvent("ban", msg, {
motivation = get_motivation(msg),
admin = admin.user,
user = target.user,
user_id = target.user.id
})
text = i18n("%s banned %s!"):format(admin.user:getLink(), target.user:getLink())
api:sendMessage(msg.from.chat.id, text, "html", true)
end
if blocks[1] == 'unban' then
if target:isAdmin() then
msg:send_reply(i18n("_An admin can't be unbanned_"), "Markdown")
return
end
if target.status ~= "kicked" then
msg:send_reply(i18n("This user is not banned!"))
return
end
local ok, err = api:unbanChatMember(target.chat.id, target.user.id)
if not ok then
msg:send_reply(api_err:trans(err), "Markdown")
return
end
u:logEvent("unban", msg, {
motivation = get_motivation(msg),
admin = admin,
user = target.user,
user_id = target.user.id
})
msg:send_reply(i18n("%s unbanned by %s!"):format(target.user:getLink(), admin.user:getLink()), 'html')
end
end
function _M:onCallbackQuery(matches)
local api = self.api
local msg = self.message
local red = self.red
local i18n = self.i18n
if msg.from.chat.type == "private"
or not msg.from:can("can_restrict_members") then
api:answerCallbackQuery(msg.cb_id, i18n("Sorry, you don't have permission to restrict members"), true)
return
end
if matches[1] == "nil" then
api:answerCallbackQuery(msg.cb_id,
i18n("Tap on the -/+ buttons to change this value. Then select a timeframe to execute the ban"), true)
return
end
local target = ChatMember:new({
user = User:new({id=matches[3]}, self),
chat = msg.from.chat,
}, self)
if matches[1] == "val" then
local key = ("chat:%d:%s:tbanvalue"):format(msg.from.chat.id, target.user.id)
local current_value, new_value
current_value = tonumber(red:get(key)) or 3
if matches[2] == "m" then
new_value = current_value - 1
if new_value < 1 then
api:answerCallbackQuery(msg.cb_id, i18n("You can't set a lower value"))
return --don't proceed
else
red:setex(key, 3600, new_value)
end
elseif matches[2] == "p" then
new_value = current_value + 1
if new_value > 100 then
api:answerCallbackQuery(msg.cb_id, i18n("Stop!!!"), true)
return --don't proceed
else
red:setex(key, 3600, new_value)
end
end
local markup = markup_tempban(self, msg.from.chat.id, target.user.id, new_value)
api:editMessageReplyMarkup(msg.from.chat.id, msg.message_id, nil, markup)
return
end
if matches[1] == 'ban' then
local key = ('chat:%d:%s:tbanvalue'):format(msg.from.chat.id, target.user.id)
local time_value = tonumber(red:get(key)) or 3
local timeframe_string, until_date
if matches[2] == 'h' then
time_value = time_value <= 24 and time_value or 24
timeframe_string = i18n('hours')
until_date = msg.date + (time_value * 3600)
elseif matches[2] == 'd' then
time_value = time_value <= 30 and time_value or 30
timeframe_string = i18n('days')
until_date = msg.date + (time_value * 3600 * 24)
elseif matches[2] == 'm' then
time_value = time_value <= 60 and time_value or 60
timeframe_string = i18n('minutes')
until_date = msg.date + (time_value * 60)
end
local ok, err = target:ban(until_date)
if not ok then
api:editMessageText(msg.from.chat.id, msg.message_id, nil, err)
return
end
local text = i18n("User banned for %d %s"):format(time_value, timeframe_string)
api:editMessageText(msg.from.chat.id, msg.message_id, nil, text)
red:del(key)
end
end
_M.triggers = {
onTextMessage = {
config.cmd..'(kick) (.+)',
config.cmd..'(kick)$',
config.cmd..'(ban) (.+)',
config.cmd..'(ban)$',
config.cmd..'(fwdban)$',
config.cmd..'(tempban)$',
config.cmd..'(tempban) (.+)',
config.cmd..'(unban) (.+)',
config.cmd..'(unban)$'
},
onCallbackQuery = {
'^###cb:tempban:(val):(%a):(%d+):(-%d+)',
'^###cb:tempban:(ban):(%a):(%d+):(-%d+)',
'^###cb:tempban:(nil)$'
}
}
return _M
| gpl-2.0 |
starlightknight/darkstar | scripts/commands/mp.lua | 22 | 1359 | ---------------------------------------------------------------------------------------------------
-- func: mp <amount> <player>
-- desc: Sets the GM or target players mana.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "is"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!mp <amount> {player}");
end;
function onTrigger(player, mp, target)
-- validate amount
if (mp == nil or tonumber(mp) == nil) then
error(player, "You must provide an amount.");
return;
elseif (mp < 0) then
error(player, "Invalid amount.");
return;
end
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format( "Player named '%s' not found!", target ) );
return;
end
end
-- set mp
if (targ:getHP() > 0) then
targ:setMP(mp);
if(targ:getID() ~= player:getID()) then
player:PrintToPlayer(string.format("Set %s's MP to %i.", targ:getName(), targ:getMP()));
end
else
player:PrintToPlayer(string.format("%s is currently dead.", targ:getName()));
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/aileens_delight.lua | 11 | 1521 | -----------------------------------------
-- ID: 5674
-- Item: Aileen's Delight
-- Food Effect: 60 Min, All Races
-----------------------------------------
-- HP +50
-- MP +50
-- STR +4
-- DEX +4
-- VIT +4
-- AGI +4
-- INT +4
-- MND +4
-- CHR +4
-- MP recovered while healing +2
-----------------------------------------
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,5674)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.HP, 50)
target:addMod(dsp.mod.MP, 50)
target:addMod(dsp.mod.STR, 4)
target:addMod(dsp.mod.DEX, 4)
target:addMod(dsp.mod.VIT, 4)
target:addMod(dsp.mod.AGI, 4)
target:addMod(dsp.mod.INT, 4)
target:addMod(dsp.mod.MND, 4)
target:addMod(dsp.mod.CHR, 4)
target:addMod(dsp.mod.MPHEAL, 2)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 50)
target:delMod(dsp.mod.MP, 50)
target:delMod(dsp.mod.STR, 4)
target:delMod(dsp.mod.DEX, 4)
target:delMod(dsp.mod.VIT, 4)
target:delMod(dsp.mod.AGI, 4)
target:delMod(dsp.mod.INT, 4)
target:delMod(dsp.mod.MND, 4)
target:delMod(dsp.mod.CHR, 4)
target:delMod(dsp.mod.MPHEAL, 2)
end
| gpl-3.0 |
tommy3/Urho3D | bin/Data/LuaScripts/49_Urho2DIsometricDemo.lua | 12 | 6480 | -- Urho2D tile map example.
-- This sample demonstrates:
-- - Creating an isometric 2D scene with tile map
-- - Displaying the scene using the Renderer subsystem
-- - Handling keyboard to move a character and zoom 2D camera
-- - Generating physics shapes from the tmx file's objects
-- - Displaying debug geometry for physics and tile map
-- Note that this sample uses some functions from Sample2D utility class.
require "LuaScripts/Utilities/Sample"
require "LuaScripts/Utilities/2D/Sample2D"
function Start()
-- Set filename for load/save functions
demoFilename = "Isometric2D"
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateUIContent("ISOMETRIC 2.5D DEMO")
-- Hook up to the frame update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create the Octree, DebugRenderer and PhysicsWorld2D components to the scene
scene_:CreateComponent("Octree")
scene_:CreateComponent("DebugRenderer")
local physicsWorld = scene_:CreateComponent("PhysicsWorld2D")
physicsWorld.gravity = Vector2.ZERO -- Neutralize gravity as the character will always be grounded
-- Create camera
cameraNode = Node()
local camera = cameraNode:CreateComponent("Camera")
camera.orthographic = true
camera.orthoSize = graphics.height * PIXEL_SIZE
zoom = 2 * Min(graphics.width / 1280, graphics.height / 800) -- Set zoom according to user's resolution to ensure full visibility (initial zoom (2) is set for full visibility at 1280x800 resolution)
camera.zoom = zoom
-- Setup the viewport for displaying the scene
renderer:SetViewport(0, Viewport:new(scene_, camera))
renderer.defaultZone.fogColor = Color(0.2, 0.2, 0.2) -- Set background color for the scene
-- Create tile map from tmx file
local tmxFile = cache:GetResource("TmxFile2D", "Urho2D/Tilesets/atrium.tmx")
local tileMapNode = scene_:CreateChild("TileMap")
local tileMap = tileMapNode:CreateComponent("TileMap2D")
tileMap.tmxFile = tmxFile
local info = tileMap.info
-- Create Spriter Imp character (from sample 33_SpriterAnimation)
CreateCharacter(info, true, 0, Vector3(-5, 11, 0), 0.15)
-- Generate physics collision shapes from the tmx file's objects located in "Physics" (top) layer
local tileMapLayer = tileMap:GetLayer(tileMap.numLayers - 1)
CreateCollisionShapesFromTMXObjects(tileMapNode, tileMapLayer, info)
-- Instantiate enemies and moving platforms at each placeholder of "MovingEntities" layer (placeholders are Poly Line objects defining a path from points)
PopulateMovingEntities(tileMap:GetLayer(tileMap.numLayers - 2))
-- Instantiate coins to pick at each placeholder of "Coins" layer (placeholders for coins are Rectangle objects)
PopulateCoins(tileMap:GetLayer(tileMap.numLayers - 3))
-- Check when scene is rendered
SubscribeToEvent("EndRendering", HandleSceneRendered)
end
function HandleSceneRendered()
UnsubscribeFromEvent("EndRendering")
SaveScene(true) -- Save the scene so we can reload it later
scene_.updateEnabled = false -- Pause the scene as long as the UI is hiding it
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
-- Subscribe HandlePostUpdate() function for processing post update events
SubscribeToEvent("PostUpdate", "HandlePostUpdate")
-- Subscribe to PostRenderUpdate to draw physics shapes
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
-- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent("SceneUpdate")
end
function HandleUpdate(eventType, eventData)
-- Zoom in/out
Zoom(cameraNode:GetComponent("Camera"))
-- Toggle debug geometry with spacebar
if input:GetKeyPress(KEY_Z) then drawDebug = not drawDebug end
-- Check for loading / saving the scene
if input:GetKeyPress(KEY_F5) then
SaveScene()
end
if input:GetKeyPress(KEY_F7) then
ReloadScene(false)
end
end
function HandlePostUpdate(eventType, eventData)
if character2DNode == nil or cameraNode == nil then
return
end
cameraNode.position = Vector3(character2DNode.position.x, character2DNode.position.y, -10) -- Camera tracks character
end
function HandlePostRenderUpdate(eventType, eventData)
if drawDebug then
scene_:GetComponent("PhysicsWorld2D"):DrawDebugGeometry(true)
end
end
-- Character2D script object class
Character2D = ScriptObject()
function Character2D:Start()
self.wounded = false
self.killed = false
self.timer = 0
self.maxCoins = 0
self.remainingCoins = 0
self.remainingLifes = 3
end
function Character2D:Update(timeStep)
local node = self.node
local animatedSprite = node:GetComponent("AnimatedSprite2D")
-- Set direction
local moveDir = Vector3.ZERO -- Reset
local speedX = Clamp(MOVE_SPEED_X / zoom, 0.4, 1)
local speedY = speedX
if input:GetKeyDown(KEY_LEFT) or input:GetKeyDown(KEY_A) then
moveDir = moveDir + Vector3.LEFT * speedX
animatedSprite.flipX = false -- Flip sprite (reset to default play on the X axis)
end
if input:GetKeyDown(KEY_RIGHT) or input:GetKeyDown(KEY_D) then
moveDir = moveDir + Vector3.RIGHT * speedX
animatedSprite.flipX = true -- Flip sprite (flip animation on the X axis)
end
if not moveDir:Equals(Vector3.ZERO) then
speedY = speedX * MOVE_SPEED_SCALE
end
if input:GetKeyDown(KEY_UP) or input:GetKeyDown(KEY_W) then
moveDir = moveDir + Vector3.UP * speedY
end
if input:GetKeyDown(KEY_DOWN) or input:GetKeyDown(KEY_S) then
moveDir = moveDir + Vector3.DOWN * speedY
end
-- Move
if not moveDir:Equals(Vector3.ZERO) then
node:Translate(moveDir * timeStep)
end
-- Animate
if input:GetKeyDown(KEY_SPACE) then
if animatedSprite.animation ~= "attack" then
animatedSprite:SetAnimation("attack", LM_FORCE_LOOPED)
end
elseif not moveDir:Equals(Vector3.ZERO) then
if animatedSprite.animation ~= "run" then
animatedSprite:SetAnimation("run")
end
elseif animatedSprite.animation ~= "idle" then
animatedSprite:SetAnimation("idle")
end
end
| mit |
mslegrand/ta_rmb | lexers/rstats.lua | 1 | 3902 | -- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
-- R LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'rstats'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- Strings.
local sq_str = l.delimited_range("'", true)
local dq_str = l.delimited_range('"', true)
local string = token(l.STRING, sq_str + dq_str)
-- Numbers.
local number = token(l.NUMBER, (l.float + l.integer) * P('i')^-1)
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'break', 'else', 'for', 'if', 'in', 'next', 'repeat', 'return', 'switch',
'try', 'while', 'Inf', 'NA', 'NaN', 'NULL', 'FALSE', 'TRUE'
})
-- Types.
local type = token(l.TYPE, word_match{
'array', 'character', 'complex', 'data.frame', 'double', 'factor', 'function',
'integer', 'list', 'logical', 'matrix', 'numeric', 'vector'
})
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Operators.
local operator = token(l.OPERATOR, S('<->+*/^=.,:;|$()[]{}'))
-- Functions
local funcs= token( l.FUNCTION, word_match{
'NCOL', 'NROW', 'UseMethod', 'abline', 'abs', 'all', 'any', 'apply', 'array', 'as', 'as.character', 'as.data.frame', 'as.double', 'as.factor', 'as.formula', 'as.integer', 'as.list', 'as.logical', 'as.matrix', 'as.name', 'as.numeric', 'as.vector', 'assign', 'attr', 'attributes', 'axis', 'c', 'cat', 'cbind', 'ceiling', 'character', 'checkPtrType', 'class', 'coef', 'colSums', 'colnames', 'cos', 'crossprod', 'cumsum', 'data.frame', 'deparse', 'diag', 'diff', 'dim', 'dimnames', 'dnorm', 'do.call', 'double', 'drop', 'eigen', 'enter', 'environment', 'errorCondition', 'eval', 'exists', 'exit', 'exp', 'expression', 'factor', 'file.path', 'floor', 'for', 'format', 'formatC', 'function', 'get', 'getOption', 'gettextRcmdr', 'grep', 'gsub', 'identical', 'if', 'ifelse', 'in', 'inherits', 'integer', 'invisible', 'is', 'is.character', 'is.data.frame', 'is.element', 'is.factor', 'is.finite', 'is.function', 'is.list', 'is.logical', 'is.matrix', 'is.na', 'is.null', 'is.numeric', 'is.vector', 'isGeneric', 'justDoIt', 'lapply', 'legend', 'length', 'levels', 'library', 'lines', 'list', 'lm', 'log', 'logger', 'match', 'match.arg', 'match.call', 'matrix', 'max', 'mean', 'median', 'message', 'min', 'missing', 'mode', 'model.frame', 'model.matrix', 'mtext', 'na.omit', 'names', 'nchar', 'ncol', 'new', 'nrow', 'numeric', 'on.exit', 'optim', 'options', 'order', 'outer', 'par', 'parent.frame', 'parse', 'paste', 'pchisq', 'plot', 'pmax', 'pnorm', 'points', 'predict', 'print', 'prod', 'qnorm', 'quantile', 'range', 'rbind', 'rep', 'rep.int', 'representation', 'require', 'return', 'rev', 'rm', 'rnorm', 'round', 'row.names', 'rowSums', 'rownames', 'runif', 'sQuote', 'sample', 'sapply', 'sd', 'segments', 'seq', 'seq_len', 'setClass', 'setGeneric', 'setMethod', 'setMethodS3', 'setdiff', 'sign', 'signature', 'signif', 'sin', 'slot', 'solve', 'sort', 'sprintf', 'sqrt', 'standardGeneric', 'stop', 'stopifnot', 'storage.mode', 'str', 'strsplit', 'structure', 'sub', 'substitute', 'substr', 'substring', 'sum', 'summary', 'svalue', 'sweep', 'switch', 't', 'table', 'tapply', 'tclVar', 'tclvalue', 'terms', 'text', 'theWidget', 'throw', 'title', 'tkadd', 'tkbind', 'tkbutton', 'tkconfigure', 'tkdestroy', 'tkentry', 'tkfocus', 'tkframe', 'tkgrid', 'tkgrid.configure', 'tkinsert', 'tklabel', 'tkpack', 'try', 'unclass', 'unique', 'unit', 'unlist', 'var', 'vector', 'warning', 'which', 'while', 'write'
})
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'type', type},
{'function', funcs},
{'identifier', identifier},
{'string', string},
{'comment', comment},
{'number', number},
{'operator', operator},
}
M._foldsymbols = {
[l.OPERATOR] = {['{'] = 1, ['}'] = -1},
_patterns = {'[{}]'}
}
return M
| mit |
pravsingh/Algorithm-Implementations | Derivative/Lua/Yonaba/derivative_test.lua | 26 | 1356 | -- Tests for derivative.lua
local drv = require 'derivative'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
local function fuzzyEqual(a, b, eps)
local eps = eps or 1e-4
return (math.abs(a - b) < eps)
end
run('Testing left derivative', function()
local f = function(x) return x * x end
assert(fuzzyEqual(drv.left(f, 5), 2 * 5))
local f = function(x) return x * x * x end
assert(fuzzyEqual(drv.left(f, 5), 3 * 5 * 5))
end)
run('Testing right derivative', function()
local f = function(x) return x * x end
assert(fuzzyEqual(drv.right(f, 5), 2 * 5))
local f = function(x) return x * x * x end
assert(fuzzyEqual(drv.right(f, 5), 3 * 5 * 5))
end)
run('Testing mid derivative', function()
local f = function(x) return x * x end
assert(fuzzyEqual(drv.mid(f, 5), 2 * 5))
local f = function(x) return x * x * x end
assert(fuzzyEqual(drv.mid(f, 5), 3 * 5 * 5))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
disslove85/NOVA1-BOT | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/modules/base/luasrc/ccache.lua | 82 | 1863 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local io = require "io"
local fs = require "nixio.fs"
local util = require "luci.util"
local nixio = require "nixio"
local debug = require "debug"
local string = require "string"
local package = require "package"
local type, loadfile = type, loadfile
module "luci.ccache"
function cache_ondemand(...)
if debug.getinfo(1, 'S').source ~= "=?" then
cache_enable(...)
end
end
function cache_enable(cachepath, mode)
cachepath = cachepath or "/tmp/luci-modulecache"
mode = mode or "r--r--r--"
local loader = package.loaders[2]
local uid = nixio.getuid()
if not fs.stat(cachepath) then
fs.mkdir(cachepath)
end
local function _encode_filename(name)
local encoded = ""
for i=1, #name do
encoded = encoded .. ("%2X" % string.byte(name, i))
end
return encoded
end
local function _load_sane(file)
local stat = fs.stat(file)
if stat and stat.uid == uid and stat.modestr == mode then
return loadfile(file)
end
end
local function _write_sane(file, func)
if nixio.getuid() == uid then
local fp = io.open(file, "w")
if fp then
fp:write(util.get_bytecode(func))
fp:close()
fs.chmod(file, mode)
end
end
end
package.loaders[2] = function(mod)
local encoded = cachepath .. "/" .. _encode_filename(mod)
local modcons = _load_sane(encoded)
if modcons then
return modcons
end
-- No cachefile
modcons = loader(mod)
if type(modcons) == "function" then
_write_sane(encoded, modcons)
end
return modcons
end
end
| gpl-2.0 |
O-P-E-N/CC-ROUTER | feeds/luci/applications/luci-app-qos/luasrc/model/cbi/qos/qos.lua | 17 | 2481 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
m = Map("qos", translate("Quality of Service"),
translate("With <abbr title=\"Quality of Service\">QoS</abbr> you " ..
"can prioritize network traffic selected by addresses, " ..
"ports or services."))
s = m:section(TypedSection, "interface", translate("Interfaces"))
s.addremove = true
s.anonymous = false
e = s:option(Flag, "enabled", translate("Enable"))
e.rmempty = false
c = s:option(ListValue, "classgroup", translate("Classification group"))
c:value("Default", translate("default"))
c.default = "Default"
s:option(Flag, "overhead", translate("Calculate overhead"))
s:option(Flag, "halfduplex", translate("Half-duplex"))
dl = s:option(Value, "download", translate("Download speed (kbit/s)"))
dl.datatype = "and(uinteger,min(1))"
ul = s:option(Value, "upload", translate("Upload speed (kbit/s)"))
ul.datatype = "and(uinteger,min(1))"
s = m:section(TypedSection, "classify", translate("Classification Rules"))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
s.sortable = true
t = s:option(ListValue, "target", translate("Target"))
t:value("Priority", translate("priority"))
t:value("Express", translate("express"))
t:value("Normal", translate("normal"))
t:value("Bulk", translate("low"))
t.default = "Normal"
srch = s:option(Value, "srchost", translate("Source host"))
srch.rmempty = true
srch:value("", translate("all"))
wa.cbi_add_knownips(srch)
dsth = s:option(Value, "dsthost", translate("Destination host"))
dsth.rmempty = true
dsth:value("", translate("all"))
wa.cbi_add_knownips(dsth)
l7 = s:option(ListValue, "layer7", translate("Service"))
l7.rmempty = true
l7:value("", translate("all"))
local pats = io.popen("find /etc/l7-protocols/ -type f -name '*.pat'")
if pats then
local l
while true do
l = pats:read("*l")
if not l then break end
l = l:match("([^/]+)%.pat$")
if l then
l7:value(l)
end
end
pats:close()
end
p = s:option(Value, "proto", translate("Protocol"))
p:value("", translate("all"))
p:value("tcp", "TCP")
p:value("udp", "UDP")
p:value("icmp", "ICMP")
p.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("all"))
bytes = s:option(Value, "connbytes", translate("Number of bytes"))
comment = s:option(Value, "comment", translate("Comment"))
return m
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Selbina/npcs/Wenzel.lua | 3 | 1051 | ----------------------------------
-- Area: Selbina
-- NPC: Wenzel
-- Type: Item Deliverer
-- !pos 31.961 -14.661 57.997 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, WENZEL_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
williamrussellajb/Alchemist | localization/en.lua | 3 | 2369 | local mkstr = ZO_CreateStringId
local SI = Alchemist.SI
-- output texts
mkstr(SI.NO_DISCOVERIES_AVAILABLE, "No discoveries available.")
mkstr(SI.COMBINATIONS_AVAILABLE, "%d combination(s) available!")
mkstr(SI.COMBINE_THE_FOLLOWING, "Combine the following:")
mkstr(SI.TO_GET_THE_FOLLOWING_DISCOVERIES, ".. to discover the following:")
-- reagents
mkstr(SI.BLESSED_THISTLE, "Blessed Thistle")
mkstr(SI.BLUE_ENTOLOMA, "Blue Entoloma")
mkstr(SI.BUGLOSS, "Bugloss")
mkstr(SI.COLUMBINE, "Columbine")
mkstr(SI.CORN_FLOWER, "Corn Flower")
mkstr(SI.DRAGONTHORN, "Dragonthorn")
mkstr(SI.EMETIC_RUSSULA, "Emetic Russula")
mkstr(SI.IMP_STOOL, "Imp Stool")
mkstr(SI.LADYS_SMOCK, "Lady's Smock")
mkstr(SI.LUMINOUS_RUSSULA, "Luminous Russula")
mkstr(SI.MOUNTAIN_FLOWER, "Mountain Flower")
mkstr(SI.NAMIRAS_ROT, "Namira's Rot")
mkstr(SI.NIRNROOT, "Nirnroot")
mkstr(SI.STINKHORN, "Stinkhorn")
mkstr(SI.VIOLET_COPRINUS, "Violet Coprinus")
mkstr(SI.WATER_HYACINTH, "Water Hyacinth")
mkstr(SI.WHITE_CAP, "White Cap")
mkstr(SI.WORMWOOD, "Wormwood")
-- traits
mkstr(SI.DETECTION, "Detection")
mkstr(SI.INCREASE_ARMOR, "Increase Armor")
mkstr(SI.INCREASE_SPELL_POWER, "Increase Spell Power")
mkstr(SI.INCREASE_SPELL_RESIST, "Increase Spell Resist")
mkstr(SI.INCREASE_WEAPON_POWER, "Increase Weapon Power")
mkstr(SI.INVISIBLE, "Invisible")
mkstr(SI.LOWER_ARMOR, "Lower Armor")
mkstr(SI.LOWER_SPELL_CRIT, "Lower Spell Crit")
mkstr(SI.LOWER_SPELL_POWER, "Lower Spell Power")
mkstr(SI.LOWER_SPELL_RESIST, "Lower Spell Resist")
mkstr(SI.LOWER_WEAPON_CRIT, "Lower Weapon Crit")
mkstr(SI.LOWER_WEAPON_POWER, "Lower Weapon Power")
mkstr(SI.RAVAGE_HEALTH, "Ravage Health")
mkstr(SI.RAVAGE_MAGICKA, "Ravage Magicka")
mkstr(SI.RAVAGE_STAMINA, "Ravage Stamina")
mkstr(SI.REDUCE_SPEED, "Reduce Speed")
mkstr(SI.RESTORE_HEALTH, "Restore Health")
mkstr(SI.RESTORE_MAGICKA, "Restore Magicka")
mkstr(SI.RESTORE_STAMINA, "Restore Stamina")
mkstr(SI.SPEED, "Speed")
mkstr(SI.SPELL_CRIT, "Spell Crit")
mkstr(SI.STUN, "Stun")
mkstr(SI.UNSTOPPABLE, "Unstoppable")
mkstr(SI.WEAPON_CRIT, "Weapon Crit")
| mit |
starlightknight/darkstar | scripts/globals/spells/doton_san.lua | 12 | 1346 | -----------------------------------------
-- Spell: Doton: San
-- Deals earth damage to an enemy and lowers its resistance against wind.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(dsp.merit.DOTON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0
local bonusMab = caster:getMerit(dsp.merit.DOTON_EFFECT) -- T1 mag atk
if(caster:getMerit(dsp.merit.DOTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits
bonusMab = bonusMab + caster:getMerit(dsp.merit.DOTON_SAN) - 5 -- merit gives 5 power but no bonus with one invest, thus subtract 5
bonusAcc = bonusAcc + caster:getMerit(dsp.merit.DOTON_SAN) - 5
end
local params = {}
params.dmg = 134
params.multiplier = 1.5
params.hasMultipleTargetReduction = false
params.resistBonus = bonusAcc
params.mabBonus = bonusMab
dmg = doNinjutsuNuke(caster, target, spell, params)
handleNinjutsuDebuff(caster,target,spell,30,duration,dsp.mod.WINDRES)
return dmg
end | gpl-3.0 |
gedads/Neodynamis | scripts/globals/weaponskills/resolution.lua | 23 | 1835 | -----------------------------------
-- Resolution
-- Great Sword weapon skill
-- Skill Level: 357
-- Delivers a fivefold attack. Damage varies with TP.
-- In order to obtain Resolution, the quest Martial Mastery must be completed.
-- This Weapon Skill's first hit params.ftp is duplicated for all additional hits.
-- Resolution has an attack penalty of -8%.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Element: None
-- Modifiers: STR:73~85%, depending on merit points upgrades.
-- 100%TP 200%TP 300%TP
-- 0.71875 1.5 2.25
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 5;
params.ftp100 = 0.71875; params.ftp200 = 0.84375 params.ftp300 = 0.96875
params.str_wsc = 0.85 + (player:getMerit(MERIT_RESOLUTION) / 100); params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 0.85;
params.multiHitfTP = true
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 0.71875; params.ftp200 = 1.5 params.ftp300 = 2.25;
params.str_wsc = 0.7 + (player:getMerit(MERIT_RESOLUTION) / 100);
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/weaponskills/metatron_torment.lua | 10 | 2376 | -----------------------------------
-- Metatron Torment
-- Hand-to-Hand Skill level: 5 Description: Delivers a threefold attack. Damage varies wit weapon skill
-- Great Axe Weapon Skill
-- Skill Level: N/A
-- Lowers target's defense. Additional effect: temporarily lowers damage taken from enemies.
-- Defense Down effect is 18.5%, 1 minute duration.
-- Damage reduced is 20.4% or 52/256.
-- Lasts 20 seconds at 100TP, 40 seconds at 200TP and 60 seconds at 300TP.
-- Available only when equipped with the Relic Weapons Abaddon Killer (Dynamis use only) or Bravura.
-- Also available as a Latent effect on Barbarus Bhuj
-- Since these Relic Weapons are only available to Warriors, only Warriors may use this Weapon Skill.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: STR:60%
-- 100%TP 200%TP 300%TP
-- 2.75 2.75 2.75
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 2.75 params.ftp200 = 2.75 params.ftp300 = 2.75
params.str_wsc = 0.6 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.str_wsc = 0.8
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
if damage > 0 then
if not target:hasStatusEffect(dsp.effect.ATTACK_DOWN) then
local duration = tp / 1000 * 20 * applyResistanceAddEffect(player, target, dsp.magic.ele.WIND, 0)
target:addStatusEffect(dsp.effect.DEFENSE_DOWN, 19, 0, duration)
end
-- Apply aftermath
dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.RELIC)
end
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Bibiki_Bay/npcs/Noih_Tahparawh.lua | 3 | 3935 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Noih Tahparawh
-- Type: Manaclipper
-- !pos -392 -3 -385 4
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
require("scripts/zones/Bibiki_Bay/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local schedule = 0;
local vHour = VanadielHour();
local vMin = VanadielMinute();
if ( vHour <= 7) then -- Schedule
--Do nothing. -- 0: A - 8:40 - Bibiki Bay (Sunset Docks)
elseif ( vHour == 8 and vMin <= 40) then -- 1: D - 9:20 - Bibiki Bay (Sunset Docks)
--Do nothing. -- 2: A - 20:40 - Bibiki Bay (Sunset Docks)
elseif ( vHour == 8) then -- 3: D - 21:20 - Bibiki Bay (Sunset Docks)
schedule = 1;
elseif ( vHour == 9 and vMin <= 20) then
schedule = 1;
elseif ( vHour <= 19) then
schedule = 2;
elseif ( vHour == 20 and vMin <= 40) then
schedule = 2;
elseif ( vHour == 20) then
schedule = 3;
elseif ( vHour == 21 and vMin <= 20) then
schedule = 3;
end
local arrive = 0;
local depart = 0;
local seconds = 0;
if ( schedule == 0) then -- Arrival, bound for Bibiki Bay (Sunset Docks)
arrive = 1;
if ( vHour == 21) then vHour = 11;
elseif ( vHour == 22) then vHour = 10;
elseif ( vHour == 23) then vHour = 9;
elseif ( vHour == 0) then vHour = 8;
elseif ( vHour == 1) then vHour = 7;
elseif ( vHour == 2) then vHour = 6;
elseif ( vHour == 3) then vHour = 5;
elseif ( vHour == 4) then vHour = 4;
elseif ( vHour == 5) then vHour = 3;
elseif ( vHour == 6) then vHour = 2;
elseif ( vHour == 7) then vHour = 1;
elseif ( vHour == 8) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 40));
elseif ( schedule == 1) then -- Departure to Bibiki Bay (Sunset Docks)
depart = 1;
if ( vHour == 8) then vHour = 1;
elseif ( vHour == 9) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 20));
elseif ( schedule == 2) then -- Arrival, bound for Bibiki Bay (Sunset Docks)
arrive = 1;
if ( vHour == 9) then vHour = 11;
elseif ( vHour == 10) then vHour = 10;
elseif ( vHour == 11) then vHour = 9;
elseif ( vHour == 12) then vHour = 8;
elseif ( vHour == 13) then vHour = 7;
elseif ( vHour == 14) then vHour = 6;
elseif ( vHour == 15) then vHour = 5;
elseif ( vHour == 16) then vHour = 4;
elseif ( vHour == 17) then vHour = 3;
elseif ( vHour == 18) then vHour = 2;
elseif ( vHour == 19) then vHour = 1;
elseif ( vHour == 20) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 40));
elseif ( schedule == 3) then -- Departure to Bibiki Bay (Sunset Docks)
depart = 1;
if ( vHour == 20) then vHour = 1;
elseif ( vHour == 21) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 20));
end
player:startEvent( 0x0013, seconds, depart, arrive, 3, 0, 0, 0, 0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
libmoon/libmoon | lua/proto/arp.lua | 4 | 19931 | ------------------------------------------------------------------------
--- @file arp.lua
--- @brief Address resolution protocol (ARP) utility.
--- Utility functions for the arp_header struct
--- Includes:
--- - Arp constants
--- - Arp address utility
--- - Arp header utility
--- - Definition of Arp packets
--- - Arp handler task
------------------------------------------------------------------------
local ffi = require "ffi"
require "proto.template"
local initHeader = initHeader
local dpdkc = require "dpdkc"
local dpdk = require "dpdk"
local memory = require "memory"
local filter = require "filter"
local ns = require "namespaces"
local libmoon = require "libmoon"
local pipe = require "pipe"
local log = require "log"
local timer = require "timer"
local eth = require "proto.ethernet"
local ntoh, hton = ntoh, hton
local ntoh16, hton16 = ntoh16, hton16
local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift
local format = string.format
local istype = ffi.istype
--------------------------------------------------------------------------------------------------------
---- ARP constants (c.f. http://www.iana.org/assignments/arp-parameters/arp-parameters.xhtml)
--------------------------------------------------------------------------------------------------------
--- Arp protocol constants
local arp = {}
--- Hardware address type for ethernet
arp.HARDWARE_ADDRESS_TYPE_ETHERNET = 1
--- Proto address type for IP (for ethernet based protocols uses etherType numbers \ref ethernet.lua)
arp.PROTO_ADDRESS_TYPE_IP = 0x0800
--- Operation: request
arp.OP_REQUEST = 1
--- Operation: reply
arp.OP_REPLY = 2
--------------------------------------------------------------------------------------------------------
---- ARP header
--------------------------------------------------------------------------------------------------------
-- definition of the header format
arp.headerFormat = [[
uint16_t hrd;
uint16_t pro;
uint8_t hln;
uint8_t pln;
uint16_t op;
union mac_address sha;
union ip4_address spa;
union mac_address tha;
union ip4_address tpa;
]]
--- Variable sized member
arp.headerVariableMember = nil
--- Module for arp_header struct
local arpHeader = initHeader()
arpHeader.__index = arpHeader
--- Set the hardware address type.
--- @param int Type as 16 bit integer.
function arpHeader:setHardwareAddressType(int)
int = int or arp.HARDWARE_ADDRESS_TYPE_ETHERNET
self.hrd = hton16(int)
end
--- Retrieve the hardware address type.
--- @return Type as 16 bit integer.
function arpHeader:getHardwareAddressType()
return hton16(self.hrd)
end
--- Retrieve the hardware address type.
--- @return Type in string format.
function arpHeader:getHardwareAddressTypeString()
local type = self:getHardwareAddressType()
if type == arp.HARDWARE_ADDRESS_TYPE_ETHERNET then
return "Ethernet"
else
return format("0x%04x", type)
end
end
--- Set the protocol address type.
--- @param int Type as 16 bit integer.
function arpHeader:setProtoAddressType(int)
int = int or arp.PROTO_ADDRESS_TYPE_IP
self.pro = hton16(int)
end
--- Retrieve the protocol address type.
--- @return Type as 16 bit integer.
function arpHeader:getProtoAddressType()
return hton16(self.pro)
end
--- Retrieve the protocol address type.
--- @return Type in string format.
function arpHeader:getProtoAddressTypeString()
local type = self:getProtoAddressType()
if type == arp.PROTO_ADDR_TYPE_IP then
return "IPv4"
else
return format("0x%04x", type)
end
end
--- Set the hardware address length.
--- @param int Length as 8 bit integer.
function arpHeader:setHardwareAddressLength(int)
int = int or 6
self.hln = int
end
--- Retrieve the hardware address length.
--- @return Length as 8 bit integer.
function arpHeader:getHardwareAddressLength()
return self.hln
end
--- Retrieve the hardware address length.
--- @return Length in string format.
function arpHeader:getHardwareAddressLengthString()
return self:getHardwareAddressLength()
end
--- Set the protocol address length.
--- @param int Length as 8 bit integer.
function arpHeader:setProtoAddressLength(int)
int = int or 4
self.pln = int
end
--- Retrieve the protocol address length.
--- @return Length as 8 bit integer.
function arpHeader:getProtoAddressLength()
return self.pln
end
--- Retrieve the protocol address length.
--- @return Length in string format.
function arpHeader:getProtoAddressLengthString()
return self:getProtoAddressLength()
end
--- Set the operation.
--- @param int Operation as 16 bit integer.
function arpHeader:setOperation(int)
int = int or arp.OP_REQUEST
self.op = hton16(int)
end
--- Retrieve the operation.
--- @return Operation as 16 bit integer.
function arpHeader:getOperation()
return hton16(self.op)
end
--- Retrieve the operation.
--- @return Operation in string format.
function arpHeader:getOperationString()
local op = self:getOperation()
if op == arp.OP_REQUEST then
return "Request"
elseif op == arp.OP_REPLY then
return "Reply"
else
return op
end
end
--- Set the hardware source address.
--- @param addr Address in 'union mac_address' format.
function arpHeader:setHardwareSrc(addr)
self.sha:set(addr)
end
--- Retrieve the hardware source address.
--- @return Address in 'union mac_address' format.
function arpHeader:getHardwareSrc()
return self.sha:get()
end
--- Set the hardware source address.
--- @param addr Address in string format.
function arpHeader:setHardwareSrcString(addr)
self.sha:setString(addr)
end
--- Retrieve the hardware source address.
--- @return Address in string format.
function arpHeader:getHardwareSrcString()
return self.sha:getString()
end
--- Set the hardware destination address.
--- @param addr Address in 'union mac_address' format.
function arpHeader:setHardwareDst(addr)
self.tha:set(addr)
end
--- Retrieve the hardware destination address.
--- @return Address in 'union mac_address' format.
function arpHeader:getHardwareDst()
return self.tha:get()
end
--- Set the hardware destination address.
--- @param addr Address in string format.
function arpHeader:setHardwareDstString(addr)
self.tha:setString(addr)
end
--- Retrieve the hardware destination address.
--- @return Address in string format.
function arpHeader:getHardwareDstString()
return self.tha:getString()
end
--- Set the protocol source address.
--- @param addr Address in 'struct ip4_address' format.
function arpHeader:setProtoSrc(addr)
self.spa:set(addr)
end
--- Retrieve the protocol source address.
--- @return Address in 'struct ip4_address' format.
function arpHeader:getProtoSrc()
return self.spa:get()
end
--- Set the protocol source address.
--- @param addr Address in source format.
function arpHeader:setProtoSrcString(addr)
self.spa:setString(addr)
end
--- Retrieve the protocol source address.
--- @return Address in string format.
function arpHeader:getProtoSrcString()
return self.spa:getString()
end
--- Set the protocol destination address.
--- @param addr Address in 'struct ip4_address' format.
function arpHeader:setProtoDst(addr)
self.tpa:set(addr)
end
--- Retrieve the protocol destination address.
--- @return Address in 'struct ip4_address' format.
function arpHeader:getProtoDst()
return self.tpa:get()
end
--- Set the protocol destination address.
--- @param addr Address in string format.
function arpHeader:setProtoDstString(addr)
self.tpa:setString(addr)
end
--- Retrieve the protocol destination address.
--- @return Address in string format.
function arpHeader:getProtoDstString()
return self.tpa:getString()
end
--- Set all members of the ip header.
--- Per default, all members are set to default values specified in the respective set function.
--- Optional named arguments can be used to set a member to a user-provided value.
--- @param args Table of named arguments. Available arguments: HardwareAddressType, ProtoAddressType, HardwareAddressLength, ProtoAddressLength, Operation, HardwareSrc, HardwareDst, ProtoSrc, ProtoDst
--- @param pre prefix for namedArgs. Default 'arp'.
--- @code
--- fill() --- only default values
--- fill{ arpOperation=2, ipTTL=100 } --- all members are set to default values with the exception of arpOperation
--- @endcode
function arpHeader:fill(args, pre)
args = args or {}
pre = pre or "arp"
self:setHardwareAddressType(args[pre .. "HardwareAddressType"])
self:setProtoAddressType(args[pre .. "ProtoAddressType"])
self:setHardwareAddressLength(args[pre .. "HardwareAddressLength"])
self:setProtoAddressLength(args[pre .. "ProtoAddressLength"])
self:setOperation(args[pre .. "Operation"])
local hwSrc = pre .. "HardwareSrc"
local hwDst = pre .. "HardwareDst"
local prSrc = pre .. "ProtoSrc"
local prDst = pre .. "ProtoDst"
args[hwSrc] = args[hwSrc] or "01:02:03:04:05:06"
args[hwDst] = args[hwDst] or "07:08:09:0a:0b:0c"
args[prSrc] = args[prSrc] or "0.1.2.3"
args[prDst] = args[prDst] or "4.5.6.7"
-- if for some reason the address is in 'union mac_address'/'union ipv4_address' format, cope with it
if type(args[hwSrc]) == "string" then
self:setHardwareSrcString(args[hwSrc])
else
self:setHardwareSrc(args[hwSrc])
end
if type(args[hwDst]) == "string" then
self:setHardwareDstString(args[hwDst])
else
self:setHardwareDst(args[hwDst])
end
if type(args[prSrc]) == "string" then
self:setProtoSrcString(args[prSrc])
else
self:setProtoSrc(args[prSrc])
end
if type(args[prDst]) == "string" then
self:setProtoDstString(args[prDst])
else
self:setProtoDst(args[prDst])
end
end
--- Retrieve the values of all members.
--- @param pre prefix for namedArgs. Default 'arp'.
--- @return Table of named arguments. For a list of arguments see "See also".
--- @see arpHeader:fill
function arpHeader:get(pre)
pre = pre or "arp"
local args = {}
args[pre .. "HardwareAddressType"] = self:getHardwareAddressType()
args[pre .. "ProtoAddressType"] = self:getProtoAddressType()
args[pre .. "HardwareAddressLength"] = self:getHardwareAddressLength()
args[pre .. "ProtoAddressLength"] = self:getProtoAddressLength()
args[pre .. "Operation"] = self:getOperation()
args[pre .. "HardwareSrc"] = self:getHardwareSrc()
args[pre .. "HardwareDst"] = self:getHardwareDst()
args[pre .. "ProtoSrc"] = self:getProtoSrc()
args[pre .. "ProtoDst"] = self:getProtoDst()
return args
end
--- Retrieve the values of all members.
--- @return Values in string format.
function arpHeader:getString()
local str = "ARP hrd " .. self:getHardwareAddressTypeString()
.. " (hln " .. self:getHardwareAddressLengthString()
.. ") pro " .. self:getProtoAddressTypeString()
.. " (pln " .. self:getProtoAddressLength(String)
.. ") op " .. self:getOperationString()
local op = self:getOperation()
if op == arp.OP_REQUEST then
str = str .. " who-has " .. self:getProtoDstString()
.. " (" .. self:getHardwareDstString()
.. ") tell " .. self:getProtoSrcString()
.. " (" .. self:getHardwareSrcString()
.. ")"
elseif op == arp.OP_REPLY then
str = str .. " " .. self:getProtoSrcString()
.. " is-at " .. self:getHardwareSrcString()
.. " (for " .. self:getProtoDstString()
.. " @ " .. self:getHardwareDstString()
.. ")"
else
str = str .. " " .. self:getHardwareSrcString()
.. " > " .. self:getHardwareDstString()
.. " " .. self:getProtoSrcString()
.. " > " .. self:getProtoDstString()
end
return str
end
---------------------------------------------------------------------------------
---- ARP Handler Task
---------------------------------------------------------------------------------
--- ARP table timeout in seconds
local ARP_AGING_TIME = 30
--- Arp handler task, responds to ARP queries for given IPs and performs arp lookups
--- @todo TODO implement garbage collection/refreshing entries \n
--- the current implementation does not handle large tables efficiently \n
arp.arpTask = "__MG_ARP_TASK"
-- Arp table
local arpTable = ns:get()
local pipes = ns:get()
--- Start the ARP task on a shared core
--- @param queues array of queue pairs and options, each array entry has the following format
--- {rxQueue = rxQueue, txQueue = txQueue, ips = "ip" | {"ip", ...}}
--- rxQueue is optional, packets can alternatively be provided through the pipe API, see arp.handlePacket()
--- Options:
--- gratArpInterval, interval in seconds in which the gratuitous is repeated.
--- this can be useful in poorly configured networks (switch MAC timeout vs router ARP timeout) on ports that never send out packets except for ARP
function arp.startArpTask(queues)
arpTable.stopTask = nil
libmoon.startSharedTask(arp.arpTask, queues)
end
function arp.stopArpTask()
arpTable.stopTask = true
end
local function handleArpPacket(rxBufs, txBufs, nic, ipToMac)
local rxPkt = rxBufs[1]:getArpPacket()
if rxPkt.eth:getType() == eth.TYPE_ARP then
if rxPkt.arp:getOperation() == arp.OP_REQUEST then
local ip = rxPkt.arp:getProtoDst()
local mac = ipToMac[ip]
if mac then
txBufs:alloc(60)
-- TODO: a single-packet API would be nice for things like this
local pkt = txBufs[1]:getArpPacket()
pkt.eth:setSrcString(mac)
pkt.eth:setDst(rxPkt.eth:getSrc())
pkt.arp:setOperation(arp.OP_REPLY)
pkt.arp:setHardwareDst(rxPkt.arp:getHardwareSrc())
pkt.arp:setHardwareSrcString(mac)
pkt.arp:setProtoDst(rxPkt.arp:getProtoSrc())
pkt.arp:setProtoSrc(ip)
nic.txQueue:send(txBufs)
end
elseif rxPkt.arp:getOperation() == arp.OP_REPLY then
-- learn from all arp replies we see (yes, that makes arp cache poisoning easy)
local mac = rxPkt.arp:getHardwareSrcString()
local ip = rxPkt.arp:getProtoSrcString()
arpTable[tostring(parseIPAddress(ip))] = {
state = "current",
mac = mac,
timestamp = time(),
updateTime = time()
}
end
end
rxBufs:freeAll()
end
local function arpTask(qs)
-- two ways to call this: single nic or array of nics
if qs[1] == nil and qs.txQueue then
return arpTask({ qs })
end
local ipToMac = {}
-- loop over NICs/Queues
for i, nic in ipairs(qs) do
if nic.rxQueue and nic.txQueue.id ~= nic.rxQueue.id then
error("both queues must belong to the same device")
end
if type(nic.ips) == "string" then
nic.ips = { nic.ips }
end
ipToMac[tostring(i)] = {}
for _, ip in pairs(nic.ips) do
ipToMac[tostring(i)][parseIPAddress(ip)] = nic.txQueue.dev:getMacString()
end
if nic.rxQueue then
nic.txQueue.dev:l2Filter(eth.TYPE_ARP, nic.rxQueue)
end
local pipe = pipe:newFastPipe()
nic.pipe = pipe
pipes[tostring(i)] = pipe
end
local rxBufs = memory.createBufArray(1)
local txMem = memory.createMemPool(function(buf)
buf:getArpPacket():fill{
arpOperation = arp.OP_REPLY,
pktLength = 60
}
end)
local txBufs = txMem:bufArray(1)
arpTable.taskRunning = true
local gratArpTimer = timer:new(0)
while libmoon.running() and not arpTable.stopTask do
-- send out gratuitous arp
if gratArpTimer:expired() then
gratArpTimer:reset(qs.gratArpInterval or math.huge)
for _, nic in ipairs(qs) do
txBufs:alloc(60)
local pkt = txBufs[1]:getArpPacket()
pkt.eth:setDstString(eth.BROADCAST)
local mac = nic.txQueue.dev:getMacString()
pkt.eth:setSrcString(mac)
pkt.arp:setOperation(arp.OP_REQUEST)
pkt.arp:setHardwareDstString(eth.BROADCAST)
pkt.arp:setProtoDst(parseIPAddress(nic.ips[1]))
pkt.arp:setProtoSrc(parseIPAddress(nic.ips[1]))
pkt.arp:setHardwareSrcString(mac)
nic.txQueue:send(txBufs)
end
end
for i, nic in ipairs(qs) do
if nic.rxQueue then
rx = nic.rxQueue:tryRecvIdle(rxBufs, 1000)
assert(rx <= 1)
if rx > 0 then
handleArpPacket(rxBufs, txBufs, nic, ipToMac[tostring(i)])
end
end
local pkt = nic.pipe:tryRecv(100)
if pkt then
rxBufs[1] = pkt
handleArpPacket(rxBufs, txBufs, nic, ipToMac[tostring(i)])
end
end
local timedOutEntries = {}
-- send requests
arpTable:forEach(function(ip, value)
local ts = time()
if type(value) ~= "table" then
return
end
-- current and updated less than ARP_AGING_TIME ago
if value.state == "current" and value.timestamp + ARP_AGING_TIME > ts then
return
end
-- requested less than a second ago
if (value.state == "requested" or value.state == "refreshing") and value.timestamp + 1 > ts then
return
end
-- didn't get a response while refreshing
if value.state == "refreshing" and value.lookupTime + ARP_AGING_TIME < ts then
table.insert(timedOutEntries, ip)
return
end
-- didn't get a reponse, ever
if value.state == "requested" and value.lookupTime + ARP_AGING_TIME < ts then
table.insert(timedOutEntries, ip)
return
end
if value.state == "current" then
value.state = "refreshing"
value.lookupTime = ts
end
if value.state == "pending" then
value.state = "requested"
value.lookupTime = ts
end
value.timestamp = ts
arpTable[ip] = value
ip = tonumber(ip)
for _, nic in ipairs(qs) do
-- TODO: do not send requests on all devices, but only the relevant
txBufs:alloc(60)
local pkt = txBufs[1]:getArpPacket()
pkt.eth:setDstString(eth.BROADCAST)
pkt.arp:setOperation(arp.OP_REQUEST)
pkt.arp:setHardwareDstString(eth.BROADCAST)
pkt.arp:setProtoDst(ip)
local mac = nic.txQueue.dev:getMacString()
pkt.eth:setSrcString(mac)
pkt.arp:setProtoSrc(parseIPAddress(nic.ips[1]))
pkt.arp:setHardwareSrcString(mac)
nic.txQueue:send(txBufs)
end
end)
for _, ip in ipairs(timedOutEntries) do
arpTable[ip] = nil
end
libmoon.sleepMillisIdle(1)
end
arpTable.taskRunning = nil
end
--- Send a buf containing an ARP packet to the ARP task.
--- The buf is free'd by the ARP task, do not free this (or increase ref count if you still need the buf).
--- @param buf the arp packet
--- @param nic the ID of the NIC from which the packt was received, defaults to 1
--- corresponds to the index in the queue array passed to the arp task
function arp.handlePacket(buf, nic)
nic = nic or 1
local pipe = pipes[tostring(nic)]
if not pipe then
log:fatal("NIC %s not found", nic)
end
pipe:send(buf)
end
--- Perform a non-blocking lookup in the ARP table.
--- Lookup the MAC address for a given IP.
--- Blocks for up to 1 second if the arp task is not yet running
--- Caution: this function uses locks and namespaces, must not be used in the fast path
--- @param ip The ip address in string or cdata format to look up.
function arp.lookup(ip)
if type(ip) == "string" then
ip = parseIPAddress(ip)
elseif type(ip) == "cdata" then
ip = ip:get()
end
if not arpTable.taskRunning then
local waitForArpTask = 0
while not arpTable.taskRunning and waitForArpTask < 10 do
libmoon.sleepMillis(100)
waitForArpTask = waitForArpTask + 1
end
if not arpTable.taskRunning then
error("ARP task is not running")
end
end
local mac = arpTable[tostring(ip)]
if type(mac) == "table" then
return mac.mac, mac.updateTime
end
arpTable.lock(function()
if not arpTable[tostring(ip)] then
arpTable[tostring(ip)] = {state = "pending", timestamp = time()}
end
end)
return nil
end
--- Perform a blocking lookup in the ARP table.
--- @param ip The ip address in string or cdata format to look up.
--- @param timeout timeout in seconds
function arp.blockingLookup(ip, timeout)
local timeout = libmoon.getTime() + timeout
repeat
local mac, ts = arp.lookup(ip)
if mac then
return mac, ts
end
libmoon.sleepMillisIdle(1000)
until libmoon.getTime() >= timeout or not libmoon.running()
end
function arp.waitForStartup()
while not arpTable.taskRunning and libmoon.running() do
libmoon.sleepMillisIdle(1)
end
end
__MG_ARP_TASK = arpTask
---------------------------------------------------------------------------------
---- Metatypes
---------------------------------------------------------------------------------
arp.metatype = arpHeader
return arp
| mit |
ABrandau/OpenRA | mods/d2k/maps/atreides-02a/atreides02a.lua | 4 | 2649 | --[[
Copyright 2007-2019 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
HarkonnenBase = { HConyard, HPower1, HPower2, HBarracks }
HarkonnenReinforcements =
{
easy =
{
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" }
},
normal =
{
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" }
},
hard =
{
{ "trike", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
}
HarkonnenAttackPaths =
{
{ HarkonnenEntry1.Location, HarkonnenRally1.Location },
{ HarkonnenEntry1.Location, HarkonnenRally3.Location },
{ HarkonnenEntry2.Location, HarkonnenRally2.Location },
{ HarkonnenEntry2.Location, HarkonnenRally4.Location }
}
HarkonnenAttackDelay =
{
easy = DateTime.Minutes(5),
normal = DateTime.Minutes(2) + DateTime.Seconds(40),
hard = DateTime.Minutes(1) + DateTime.Seconds(20)
}
HarkonnenAttackWaves =
{
easy = 3,
normal = 6,
hard = 9
}
Tick = function()
if player.HasNoRequiredUnits() then
harkonnen.MarkCompletedObjective(KillAtreides)
end
if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then
Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat")
player.MarkCompletedObjective(KillHarkonnen)
end
end
WorldLoaded = function()
harkonnen = Player.GetPlayer("Harkonnen")
player = Player.GetPlayer("Atreides")
InitObjectives(player)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
KillHarkonnen = player.AddPrimaryObjective("Destroy all Harkonnen forces.")
Camera.Position = AConyard.CenterPosition
Trigger.OnAllKilled(HarkonnenBase, function()
Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt)
end)
local path = function() return Utils.Random(HarkonnenAttackPaths) end
SendCarryallReinforcements(harkonnen, 0, HarkonnenAttackWaves[Difficulty], HarkonnenAttackDelay[Difficulty], path, HarkonnenReinforcements[Difficulty])
Trigger.AfterDelay(0, ActivateAI)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Qufim_Island/npcs/Giant_Footprint.lua | 3 | 1059 | -----------------------------------
-- Area: Qufim Island
-- NPC: Giant Footprint
-- Involved in quest: Regaining Trust
-- !pos 501 -11 354 126
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Qufim_Island/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(GIGANTIC_FOOTPRINT);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("finishRESULT: %u",option);
end; | gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/bowl_of_witch_stew.lua | 11 | 1149 | -----------------------------------------
-- ID: 4344
-- Item: witch_stew
-- Food Effect: 4hours, All Races
-----------------------------------------
-- Magic Points 45
-- Strength -1
-- Mind 4
-- MP Recovered While Healing 4
-- Enmity -4
-----------------------------------------
require("scripts/globals/status")
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,14400,4344)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.MP, 45)
target:addMod(dsp.mod.STR, -1)
target:addMod(dsp.mod.MND, 4)
target:addMod(dsp.mod.MPHEAL, 4)
target:addMod(dsp.mod.ENMITY, -4)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.MP, 45)
target:delMod(dsp.mod.STR, -1)
target:delMod(dsp.mod.MND, 4)
target:delMod(dsp.mod.MPHEAL, 4)
target:delMod(dsp.mod.ENMITY, -4)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/behemoth_steak_+1.lua | 12 | 2003 | -----------------------------------------
-- ID: 6465
-- Item: behemoth_steak_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- HP +45
-- STR +8
-- DEX +8
-- INT -4
-- Attack +24% (cap 165)
-- Ranged Attack +24% (cap 165)
-- Triple Attack +2%
-- Lizard Killer +5
-- hHP +5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,6465);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 45);
target:addMod(MOD_STR, 8);
target:addMod(MOD_DEX, 8);
target:addMod(MOD_INT, -4);
target:addMod(MOD_FOOD_ATTP, 24);
target:addMod(MOD_FOOD_ATT_CAP, 165);
target:addMod(MOD_FOOD_RATTP, 24);
target:addMod(MOD_FOOD_RATT_CAP, 165);
target:addMod(MOD_TRIPLE_ATTACK, 2);
target:addMod(MOD_LIZARD_KILLER, 5);
target:addMod(MOD_HPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 45);
target:delMod(MOD_STR, 8);
target:delMod(MOD_DEX, 8);
target:delMod(MOD_INT, -4);
target:delMod(MOD_FOOD_ATTP, 24);
target:delMod(MOD_FOOD_ATT_CAP, 165);
target:delMod(MOD_FOOD_RATTP, 24);
target:delMod(MOD_FOOD_RATT_CAP, 165);
target:delMod(MOD_TRIPLE_ATTACK, 2);
target:delMod(MOD_LIZARD_KILLER, 5);
target:delMod(MOD_HPHEAL, 5);
end;
| gpl-3.0 |
arrayfire/arrayfire_lua | wrapper/arrayfire/funcs/io.lua | 4 | 1235 | --- IO functions.
-- Modules --
local af = require("arrayfire_lib")
local array = require("impl.array")
-- Imports --
local Call = array.Call
local CallWrap = array.CallWrap
-- Exports --
local M = {}
-- See also: https://github.com/arrayfire/arrayfire/blob/devel/src/api/cpp/imageio.cpp
local function LoadImage (filename, is_color)
return CallWrap("af_load_image", filename, is_color)
end
--
local function SaveImage (filename, in_arr)
Call("af_save_image", filename, in_arr:get())
end
--
function M.Add (into)
for k, v in pairs{
deleteImageMem = function(ptr)
Call("af_delete_image_memory", ptr)
end,
--
loadImage = LoadImage, loadimage = LoadImage,
--
loadImageMem = function(ptr)
return CallWrap("af_load_image_memory", ptr)
end,
loadImageNative = function(filename)
return CallWrap("af_load_image_native", filename)
end,
--
saveImage = SaveImage, saveimage = SaveImage,
--
saveImageMem = function(in_arr, format)
return Call("af_save_image_memory", in_arr:get(), af[format or "AF_FIF_PNG"])
end,
--
saveImageNative = function(filename, in_arr)
Call("af_save_image_native", filename, in_arr:get())
end
} do
into[k] = v
end
end
-- Export the module.
return M | bsd-3-clause |
pedro-andrade-inpe/terrame | packages/base/tests/observer/alternative/Clock.lua | 3 | 1981 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org
-- This code is part of the TerraME framework.
-- This framework is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this software and its documentation.
--
-------------------------------------------------------------------------------------------
return{
Clock = function(unitTest)
local error_func = function()
Clock(2)
end
unitTest:assertError(error_func, namedArgumentsMsg())
error_func = function()
Clock{}
end
unitTest:assertError(error_func, mandatoryArgumentMsg("target"))
error_func = function()
Clock{target = Cell{}}
end
unitTest:assertError(error_func, incompatibleTypeMsg("target", "Timer", Cell{}))
end,
save = function(unitTest)
local c = Clock{target = Timer{}}
local error_func = function()
c:save("file.csv")
end
unitTest:assertError(error_func, invalidFileExtensionMsg(1, "csv"))
end
}
| lgpl-3.0 |
Micr0Bit/OpenRA | lua/stacktraceplus.lua | 59 | 12006 | -- tables
local _G = _G
local string, io, debug, coroutine = string, io, debug, coroutine
-- functions
local tostring, print, require = tostring, print, require
local next, assert = next, assert
local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs
local error = error
assert(debug, "debug table must be available at this point")
local io_open = io.open
local string_gmatch = string.gmatch
local string_sub = string.sub
local table_concat = table.concat
local _M = {
max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)'
}
-- this tables should be weak so the elements in them won't become uncollectable
local m_known_tables = { [_G] = "_G (global table)" }
local function add_known_module(name, desc)
local ok, mod = pcall(require, name)
if ok then
m_known_tables[mod] = desc
end
end
add_known_module("string", "string module")
add_known_module("io", "io module")
add_known_module("os", "os module")
add_known_module("table", "table module")
add_known_module("math", "math module")
add_known_module("package", "package module")
add_known_module("debug", "debug module")
add_known_module("coroutine", "coroutine module")
-- lua5.2
add_known_module("bit32", "bit32 module")
-- luajit
add_known_module("bit", "bit module")
add_known_module("jit", "jit module")
local m_user_known_tables = {}
local m_known_functions = {}
for _, name in ipairs{
-- Lua 5.2, 5.1
"assert",
"collectgarbage",
"dofile",
"error",
"getmetatable",
"ipairs",
"load",
"loadfile",
"next",
"pairs",
"pcall",
"print",
"rawequal",
"rawget",
"rawlen",
"rawset",
"require",
"select",
"setmetatable",
"tonumber",
"tostring",
"type",
"xpcall",
-- Lua 5.1
"gcinfo",
"getfenv",
"loadstring",
"module",
"newproxy",
"setfenv",
"unpack",
-- TODO: add table.* etc functions
} do
if _G[name] then
m_known_functions[_G[name]] = name
end
end
local m_user_known_functions = {}
local function safe_tostring (value)
local ok, err = pcall(tostring, value)
if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end
end
-- Private:
-- Parses a line, looking for possible function definitions (in a very naïve way)
-- Returns '(anonymous)' if no function name was found in the line
local function ParseLine(line)
assert(type(line) == "string")
--print(line)
local match = line:match("^%s*function%s+(%w+)")
if match then
--print("+++++++++++++function", match)
return match
end
match = line:match("^%s*local%s+function%s+(%w+)")
if match then
--print("++++++++++++local", match)
return match
end
match = line:match("^%s*local%s+(%w+)%s+=%s+function")
if match then
--print("++++++++++++local func", match)
return match
end
match = line:match("%s*function%s*%(") -- this is an anonymous function
if match then
--print("+++++++++++++function2", match)
return "(anonymous)"
end
return "(anonymous)"
end
-- Private:
-- Tries to guess a function's name when the debug info structure does not have it.
-- It parses either the file or the string where the function is defined.
-- Returns '?' if the line where the function is defined is not found
local function GuessFunctionName(info)
--print("guessing function name")
if type(info.source) == "string" and info.source:sub(1,1) == "@" then
local file, err = io_open(info.source:sub(2), "r")
if not file then
print("file not found: "..tostring(err)) -- whoops!
return "?"
end
local line
for i = 1, info.linedefined do
line = file:read("*l")
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
else
local line
local lineNumber = 0
for l in string_gmatch(info.source, "([^\n]+)\n-") do
lineNumber = lineNumber + 1
if lineNumber == info.linedefined then
line = l
break
end
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
end
end
---
-- Dumper instances are used to analyze stacks and collect its information.
--
local Dumper = {}
Dumper.new = function(thread)
local t = { lines = {} }
for k,v in pairs(Dumper) do t[k] = v end
t.dumping_same_thread = (thread == coroutine.running())
-- if a thread was supplied, bind it to debug.info and debug.get
-- we also need to skip this additional level we are introducing in the callstack (only if we are running
-- in the same thread we're inspecting)
if type(thread) == "thread" then
t.getinfo = function(level, what)
if t.dumping_same_thread and type(level) == "number" then
level = level + 1
end
return debug.getinfo(thread, level, what)
end
t.getlocal = function(level, loc)
if t.dumping_same_thread then
level = level + 1
end
return debug.getlocal(thread, level, loc)
end
else
t.getinfo = debug.getinfo
t.getlocal = debug.getlocal
end
return t
end
-- helpers for collecting strings to be used when assembling the final trace
function Dumper:add (text)
self.lines[#self.lines + 1] = text
end
function Dumper:add_f (fmt, ...)
self:add(fmt:format(...))
end
function Dumper:concat_lines ()
return table_concat(self.lines)
end
---
-- Private:
-- Iterates over the local variables of a given function.
--
-- @param level The stack level where the function is.
--
function Dumper:DumpLocals (level)
local prefix = "\t "
local i = 1
if self.dumping_same_thread then
level = level + 1
end
local name, value = self.getlocal(level, i)
if not name then
return
end
self:add("\tLocal variables:\r\n")
while name do
if type(value) == "number" then
self:add_f("%s%s = number: %g\r\n", prefix, name, value)
elseif type(value) == "boolean" then
self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value))
elseif type(value) == "string" then
self:add_f("%s%s = string: %q\r\n", prefix, name, value)
elseif type(value) == "userdata" then
self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value))
elseif type(value) == "nil" then
self:add_f("%s%s = nil\r\n", prefix, name)
elseif type(value) == "table" then
if m_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value])
elseif m_user_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value])
else
local txt = "{"
for k,v in pairs(value) do
txt = txt..safe_tostring(k)..":"..safe_tostring(v)
if #txt > _M.max_tb_output_len then
txt = txt.." (more...)"
break
end
if next(value, k) then txt = txt..", " end
end
self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}")
end
elseif type(value) == "function" then
local info = self.getinfo(value, "nS")
local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value]
if info.what == "C" then
self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value)))
else
local source = info.short_src
if source:sub(2,7) == "string" then
source = source:sub(9)
end
--for k,v in pairs(info) do print(k,v) end
fun_name = fun_name or GuessFunctionName(info)
self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source)
end
elseif type(value) == "thread" then
self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value))
end
i = i + 1
name, value = self.getlocal(level, i)
end
end
---
-- Public:
-- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc.
-- This function is suitable to be used as an error handler with pcall or xpcall
--
-- @param thread An optional thread whose stack is to be inspected (defaul is the current thread)
-- @param message An optional error string or object.
-- @param level An optional number telling at which level to start the traceback (default is 1)
--
-- Returns a string with the stack trace and a string with the original error.
--
function _M.stacktrace(thread, message, level)
if type(thread) ~= "thread" then
-- shift parameters left
thread, message, level = nil, thread, message
end
thread = thread or coroutine.running()
level = level or 1
local dumper = Dumper.new(thread)
local original_error
if type(message) == "table" then
dumper:add("an error object {\r\n")
local first = true
for k,v in pairs(message) do
if first then
dumper:add(" ")
first = false
else
dumper:add(",\r\n ")
end
dumper:add(safe_tostring(k))
dumper:add(": ")
dumper:add(safe_tostring(v))
end
dumper:add("\r\n}")
original_error = dumper:concat_lines()
elseif type(message) == "string" then
dumper:add(message)
original_error = message
end
dumper:add("\r\n")
dumper:add[[
Stack Traceback
===============
]]
--print(error_message)
local level_to_show = level
if dumper.dumping_same_thread then level = level + 1 end
local info = dumper.getinfo(level, "nSlf")
while info do
if info.what == "main" then
if string_sub(info.source, 1, 1) == "@" then
dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline)
else
dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline)
end
elseif info.what == "C" then
--print(info.namewhat, info.name)
--for k,v in pairs(info) do print(k,v, type(v)) end
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func)
dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name)
--dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value)))
elseif info.what == "tail" then
--print("tail")
--for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name)
dumper:add_f("(%d) tail call\r\n", level_to_show)
dumper:DumpLocals(level)
elseif info.what == "Lua" then
local source = info.short_src
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name
if source:sub(2, 7) == "string" then
source = source:sub(9)
end
local was_guessed = false
if not function_name or function_name == "?" then
--for k,v in pairs(info) do print(k,v, type(v)) end
function_name = GuessFunctionName(info)
was_guessed = true
end
-- test if we have a file name
local function_type = (info.namewhat == "") and "function" or info.namewhat
if info.source and info.source:sub(1, 1) == "@" then
dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
elseif info.source and info.source:sub(1,1) == '#' then
dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
else
dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source)
end
dumper:DumpLocals(level)
else
dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what)
end
level = level + 1
level_to_show = level_to_show + 1
info = dumper.getinfo(level, "nSlf")
end
return dumper:concat_lines(), original_error
end
--
-- Adds a table to the list of known tables
function _M.add_known_table(tab, description)
if m_known_tables[tab] then
error("Cannot override an already known table")
end
m_user_known_tables[tab] = description
end
--
-- Adds a function to the list of known functions
function _M.add_known_function(fun, description)
if m_known_functions[fun] then
error("Cannot override an already known function")
end
m_user_known_functions[fun] = description
end
return _M
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Port_Windurst/npcs/Ohruru.lua | 9 | 4583 | -----------------------------------
-- Area: Port Windurst
-- NPC: Ohruru
-- Starts & Finishes Repeatable Quest: Catch me if you can
-- Involved in Quest: Wonder Wands
-- Note: Animation for his "Cure" is not functioning. Unable to capture option 1, so if the user says no, he heals them anyways.
-- !pos -108 -5 94 240
-----------------------------------
local ID = require("scripts/zones/Port_Windurst/IDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/status");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
-- player:delQuest(WINDURST,dsp.quest.id.windurst.CATCH_IT_IF_YOU_CAN); -- ======== FOR TESTING ONLY ==========-----
-- ======== FOR TESTING ONLY ==========-----
-- if (player:getCharVar("QuestCatchItIfYouCan_var") == 0 and player:hasStatusEffect(dsp.effect.MUTE) == false and player:hasStatusEffect(dsp.effect.BANE) == false and player:hasStatusEffect(dsp.effect.PLAGUE) == false) then
-- rand = math.random(1,3);
-- if (rand == 1) then
-- player:addStatusEffect(dsp.effect.MUTE,0,0,100);
-- elseif (rand == 2) then
-- player:addStatusEffect(dsp.effect.BANE,0,0,100);
-- elseif (rand == 3) then
-- player:addStatusEffect(dsp.effect.PLAGUE,0,0,100);
-- end
-- end
-- ======== FOR TESTING ONLY ==========-----
Catch = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.CATCH_IT_IF_YOU_CAN);
WonderWands = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.WONDER_WANDS);
if (WonderWands == QUEST_ACCEPTED) then
player:startEvent(258,0,17053);
elseif (Catch == 0) then
prog = player:getCharVar("QuestCatchItIfYouCan_var");
if (prog == 0) then
player:startEvent(230); -- CATCH IT IF YOU CAN: Before Quest 1
player:setCharVar("QuestCatchItIfYouCan_var",1);
elseif (prog == 1) then
player:startEvent(253); -- CATCH IT IF YOU CAN: Before Start
player:setCharVar("QuestCatchItIfYouCan_var",2);
elseif (prog == 2) then
player:startEvent(231); -- CATCH IT IF YOU CAN: Before Quest 2
end
elseif (Catch >= 1 and (player:hasStatusEffect(dsp.effect.MUTE) == true or player:hasStatusEffect(dsp.effect.BANE) == true or player:hasStatusEffect(dsp.effect.PLAGUE) == true)) then
player:startEvent(246); -- CATCH IT IF YOU CAN: Quest Turn In 1
elseif (Catch >= 1 and player:needToZone()) then
player:startEvent(255); -- CATCH IT IF YOU CAN: After Quest
elseif (Catch == 1 and player:hasStatusEffect(dsp.effect.MUTE) == false and player:hasStatusEffect(dsp.effect.BANE) == false and player:hasStatusEffect(dsp.effect.PLAGUE) == false) then
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(248); -- CATCH IT IF YOU CAN: During Quest 1
else
player:startEvent(251); -- CATCH IT IF YOU CAN: During Quest 2
end
elseif (WonderWands == QUEST_COMPLETED) then
player:startEvent(265);
else
player:startEvent(230); -- STANDARD CONVERSATION
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 231) then
player:addQuest(WINDURST,dsp.quest.id.windurst.CATCH_IT_IF_YOU_CAN);
elseif (csid == 246 and option == 0) then
player:needToZone(true);
if (player:hasStatusEffect(dsp.effect.MUTE) == true) then
player:delStatusEffect(dsp.effect.MUTE);
player:addGil(GIL_RATE*1000);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*1000);
elseif (player:hasStatusEffect(dsp.effect.BANE) == true) then
player:delStatusEffect(dsp.effect.BANE);
player:addGil(GIL_RATE*1200);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*1200);
elseif (player:hasStatusEffect(dsp.effect.PLAGUE) == true) then
player:delStatusEffect(dsp.effect.PLAGUE);
player:addGil(GIL_RATE*1500);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*1500);
end
player:setCharVar("QuestCatchItIfYouCan_var",0);
if (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.CATCH_IT_IF_YOU_CAN) == QUEST_ACCEPTED) then
player:completeQuest(WINDURST,dsp.quest.id.windurst.CATCH_IT_IF_YOU_CAN);
player:addFame(WINDURST,75);
else
player:addFame(WINDURST,8);
end
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Riverne-Site_A01/npcs/_0u1.lua | 17 | 1367 | -----------------------------------
-- Area: Riverne Site #A01
-- NPC: Unstable Displacement
-----------------------------------
package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Riverne-Site_A01/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale
player:tradeComplete();
npc:openDoor(RIVERNE_PORTERS);
player:messageSpecial(SD_HAS_GROWN);
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 8) then
player:startEvent(0x6);
else
player:messageSpecial(SD_VERY_SMALL);
end;
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
starlightknight/darkstar | scripts/zones/Port_Bastok/npcs/Evi.lua | 9 | 1836 | -----------------------------------
-- Area: Port Bastok
-- NPC: Evi
-- Starts Quests: Past Perfect (100%)
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
local ID = require("scripts/zones/Port_Bastok/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
PastPerfect = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.PAST_PERFECT);
if (PastPerfect == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TATTERED_MISSION_ORDERS)) then
player:startEvent(131);
elseif (player:getFameLevel(BASTOK) >= 2 and player:getCharVar("PastPerfectVar") == 2) then
player:startEvent(130);
elseif (PastPerfect == QUEST_AVAILABLE) then
player:startEvent(104);
else
player:startEvent(21);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
function onEventFinish(player,csid,option)
if (csid == 104 and player:getCharVar("PastPerfectVar") == 0) then
player:setCharVar("PastPerfectVar",1);
elseif (csid == 130) then
player:addQuest(BASTOK,dsp.quest.id.bastok.PAST_PERFECT);
elseif (csid == 131) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,12560);
else
if (player:addItem(12560)) then
player:delKeyItem(dsp.ki.TATTERED_MISSION_ORDERS);
player:setCharVar("PastPerfectVar",0);
player:messageSpecial(ID.text.ITEM_OBTAINED,12560);
player:addFame(BASTOK,110);
player:completeQuest(BASTOK,dsp.quest.id.bastok.PAST_PERFECT);
end
end
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/mobskills/gates_of_hades.lua | 33 | 1414 | ---------------------------------------------
-- Gates of Hades
--
-- Description: Deals severe Fire damage to enemies within an area of effect. Additional effect: Burn
-- Type: Magical
--
--
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 20' radial
-- Notes: Only used when a cerberus's health is 25% or lower (may not be the case for Orthrus). The burn effect takes off upwards of 20 HP per tick.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1793) then
return 0;
else
return 1;
end
end
local result = 1;
local mobhp = mob:getHPP();
if (mobhp <= 25) then
result = 0;
end;
return result;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_BURN;
local power = 21;
MobStatusEffectMove(mob, target, typeEffect, power, 3, 60);
local dmgmod = 1.8;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*6,ELE_FIRE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/The_Colosseum/npcs/Zandjarl.lua | 12 | 2646 | -----------------------------------
-- Area: The Colosseum
-- NPC: Zandjarl
-- Type: Pankration NPC
-- !pos -599 0 45 71
-----------------------------------
local ID = require("scripts/zones/The_Colosseum/IDs");
-----------------------------------
function onTrade(player,npc,trade)
local RESULT = nil;
local COUNT = trade:getItemCount();
local TOTAL = player:getCurrency("jetton");
local MAX = 100000000;
if (trade:hasItemQty(2184,COUNT)) then
RESULT = 2*COUNT;
elseif (trade:hasItemQty(2185,COUNT)) then
RESULT = 10*COUNT;
elseif (trade:hasItemQty(2186,COUNT)) then
RESULT = 30*COUNT;
elseif (trade:hasItemQty(2187,COUNT)) then
RESULT = 200*COUNT;
end
if (RESULT ~= nil) then
if ((RESULT + TOTAL) > MAX) then
-- player:startEvent(47); ..it no work..
npc:showText(npc, ID.text.EXCEED_THE_LIMIT_OF_JETTONS);
else
-- packet cap says its a "showText" thing..
npc:showText(npc, ID.text.I_CAN_GIVE_YOU, RESULT);
npc:showText(npc, ID.text.THANKS_FOR_STOPPING_BY);
player:addCurrency("jetton", RESULT);
player:tradeComplete();
end
end
end;
function onTrigger(player,npc)
player:startEvent(1900, player:getCurrency("jetton"));
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 1900) then -- onTrigger
local shop =
{
[1] = {itemID = 18721, price = 2, QTY = 1}, -- SoulTrapper
[257] = {itemID = 18724, price = 500, QTY = 1}, -- Soultrapper 2000
[513] = {itemID = 16134, price = 5000, QTY = 1}, -- Zoraal Ja's Helm
[65537] = {itemID = 18722, price = 2, QTY = 12}, -- Blank Soul Plates
[65793] = {itemID = 18725, price = 500, QTY = 12}, -- High Speed Soul plates
[66049] = {itemID = 16135, price = 5000, QTY = 1}, -- Dartorgor's Coif
[131585] = {itemID = 16136, price = 5000, QTY = 1}, -- Lamia No.3's Garland
[197121] = {itemID = 16137, price = 5000, QTY = 1} -- Cacaroon's Hood
}
local result = shop[option];
if (result ~= nil) then
if (result.itemID ~= nil) then
if (player:addItem(result.itemID, result.QTY)) then
player:delCurrency("jetton", result.price);
player:messageSpecial(ID.text.ITEM_OBTAINED,result.itemID);
else
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,result.itemID);
end
end
end
end
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Kuftal_Tunnel/IDs.lua | 9 | 5694 | -----------------------------------
-- Area: Kuftal_Tunnel
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.KUFTAL_TUNNEL] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
FISHING_MESSAGE_OFFSET = 7208, -- You can't fish here.
CHEST_UNLOCKED = 7316, -- You unlock the chest!
FELL = 7334, -- The piece of wood fell off the cliff!
EVIL = 7335, -- You sense an evil presence...
FISHBONES = 7349, -- Fish bones lie scattered about the area...
SENSE_OMINOUS_PRESENCE = 7351, -- You sense an ominous presence...
REGIME_REGISTERED = 10335, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 11419, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
PLAYER_OBTAINS_ITEM = 11387, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 11388, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 11389, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 11390, -- You already possess that temporary item.
NO_COMBINATION = 11395, -- You were unable to enter a combination.
COMMON_SENSE_SURVIVAL = 11419, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
AMEMET_PH =
{
[17490000] = 17490016, -- 123.046 0.250 18.642
[17489994] = 17490016, -- 112.135 -0.278 38.281
[17490001] = 17490016, -- 112.008 -0.530 50.994
[17490003] = 17490016, -- 122.654 -0.491 0.840
[17490008] = 17490016, -- 123.186 0.213 -24.716
[17490005] = 17490016, -- 118.633 -0.470 -43.282
[17490010] = 17490016, -- 109.000 -0.010 -48.000
[17490004] = 17490016, -- 96.365 -0.269 -7.619
[17490002] = 17490016, -- 89.590 -0.321 -9.390
[17489933] = 17490016, -- 68.454 -0.417 -0.413
[17489932] = 17490016, -- 74.662 -0.513 3.685
[17490009] = 17490016, -- 67.998 -0.500 12.000
[17489934] = 17490016, -- 92.000 -0.396 14.000
},
ARACHNE_PH =
{
[17490222] = 17490217, -- 19.000 20.000 37.000
[17490221] = 17490217, -- -10.000 20.000 14.000
[17490219] = 17490217, -- -20.000 20.000 38.000
[17490220] = 17490217, -- -20.000 21.000 1.000
},
BLOODTHIRSTER_MADKIX_PH =
{
[17490173] = 17490159, -- 265.000 9.000 30.000
[17490182] = 17490159, -- 256.000 10.000 34.000
},
PELICAN_PH =
{
[17490097] = 17490101, -- 178.857 20.256 -44.151
[17490094] = 17490101, -- 180.000 21.000 -39.000
[17490098] = 17490101, -- 179.394 20.061 -34.062
},
SABOTENDER_MARIACHI_PH =
{
[17489987] = 17489980, -- -23.543 -0.396 59.578
[17489983] = 17489980, -- -45.000 -0.115 39.000
[17489985] = 17489980, -- -34.263 -0.512 30.437
[17489984] = 17489980, -- -38.791 0.230 26.579
[17489977] = 17489980, -- -41.000 0.088 -3.000
[17489978] = 17489980, -- -54.912 0.347 -1.681
[17489979] = 17489980, -- -58.807 -0.327 -8.531
[17489981] = 17489980, -- -82.074 -0.450 -0.738
[17489982] = 17489980, -- -84.721 -0.325 -2.861
[17489974] = 17489980, -- -41.000 -0.488 -31.000
[17489975] = 17489980, -- -33.717 -0.448 -43.478
[17489971] = 17489980, -- -17.217 -0.956 -57.647
},
YOWIE_PH =
{
[17490175] = 17490204, -- 27.000 19.000 132.000
[17490174] = 17490204, -- 20.000 20.000 118.000
[17490168] = 17490204, -- 19.000 18.000 100.000
[17490167] = 17490204, -- 18.000 21.000 82.000
[17490161] = 17490204, -- 23.000 20.000 75.000
[17490176] = 17490204, -- 19.000 19.000 55.000
[17490160] = 17490204, -- 34.000 21.000 59.000
[17490146] = 17490204, -- 59.000 21.000 65.000
[17490148] = 17490204, -- 58.000 21.000 57.000
[17490144] = 17490204, -- 72.000 21.000 63.000
[17490141] = 17490204, -- 87.000 21.000 59.000
},
TALEKEEPER_OFFSET = 17489926,
MIMIC = 17490230,
CANCER = 17490231,
PHANTOM_WORM = 17490233,
GUIVRE = 17490234,
KETTENKAEFER = 17490235,
},
npc =
{
PHANTOM_WORM_QM = 17490253,
CASKET_BASE = 17490257,
DOOR_ROCK = 17490280,
TREASURE_COFFER = 17490304,
},
}
return zones[dsp.zone.KUFTAL_TUNNEL] | gpl-3.0 |
BillardDRP/nathaniel-rp-addons | addons/billard_rp_ents/lua/entities/billard_weed_harvested/init.lua | 2 | 1137 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel("models/props/cs_office/trash_can_p5.mdl") //Once again, custom models are overrated
self:SetColor(Color(0, 255, 0, 255))
self:SetMaterial("models/props_c17/furniturefabric_002a")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
self:SetUserHealth(0)
self:SetIsUsed(false)
end
function ENT:Think()
if self:GetIsUsed() then
while self:GetUserPerson():Health() > self:GetUserHealth do
self:GetUserPerson():SetHealth(self:GetUserPerson():Health() - 20)
self:NextThink(CurTime() + 1)
end
end
end
function ENT:Use(activator, caller)
if IsValid(caller) and caller:IsPlayer() then
caller:ChatPrint("I'm so high right now, nothing could hurt me!")
self:SetUserHealth(caller:Health())
self:SetUserPerson(caller)
caller:SetHealth(caller:Health() * 8)
self:SetIsUsed(true)
DoGenericUseEffect(caller)
self:Remove()
end
end | gpl-3.0 |
starlightknight/darkstar | scripts/zones/Oldton_Movalpolos/npcs/Tarnotik.lua | 9 | 1132 | -----------------------------------
-- Area: Oldton Movalpolos
-- NPC: Tarnotik
-- Type: Standard NPC
-- !pos 160.896 10.999 -55.659 11
-----------------------------------
require("scripts/globals/missions")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player, npc, trade)
if player:getCurrentMission(COP) >= dsp.mission.id.cop.THREE_PATHS and npcUtil.tradeHas(trade, 1725) then
player:startEvent(32)
end
end
function onTrigger(player, npc)
if player:getCurrentMission(COP) == dsp.mission.id.cop.THREE_PATHS and player:getCharVar("COP_Louverance_s_Path") == 7 then
player:startEvent(34)
else
if math.random() < 0.5 then -- this isn't retail at all.
player:startEvent(30)
else
player:startEvent(31)
end
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32 then
player:confirmTrade()
player:setPos(-116, -119, -620, 253, 13)
elseif csid == 34 then
player:setCharVar("COP_Louverance_s_Path", 8)
end
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Outer_Horutoto_Ruins/npcs/_5ee.lua | 17 | 3749 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Ancient Magical Gizmo #1 (E out of E, F, G, H, I, J)
-- Involved In Mission: The Heart of the Matter
-----------------------------------
package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Outer_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Check if we are on Windurst Mission 1-2
if (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER) then
MissionStatus = player:getVar("MissionStatus");
if (MissionStatus == 2) then
-- Entered a Dark Orb
if (player:getVar("MissionStatus_orb1") == 1) then
player:startEvent(0x002e);
else
player:messageSpecial(ORB_ALREADY_PLACED);
end
elseif (MissionStatus == 4) then
-- Took out a Glowing Orb
if (player:getVar("MissionStatus_orb1") == 2) then
player:startEvent(0x002e);
else
player:messageSpecial(G_ORB_ALREADY_GOTTEN);
end
else
player:messageSpecial(DARK_MANA_ORB_RECHARGER);
end
else
player:messageSpecial(DARK_MANA_ORB_RECHARGER);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x002e) then
orb_value = player:getVar("MissionStatus_orb1");
if (orb_value == 1) then
player:setVar("MissionStatus_orb1",2);
-- Push the text that the player has placed the orb
player:messageSpecial(FIRST_DARK_ORB_IN_PLACE);
--Delete the key item
player:delKeyItem(FIRST_DARK_MANA_ORB);
-- Check if all orbs have been placed or not
if (player:getVar("MissionStatus_orb2") == 2 and
player:getVar("MissionStatus_orb3") == 2 and
player:getVar("MissionStatus_orb4") == 2 and
player:getVar("MissionStatus_orb5") == 2 and
player:getVar("MissionStatus_orb6") == 2) then
player:messageSpecial(ALL_DARK_MANA_ORBS_SET);
player:setVar("MissionStatus",3);
end
elseif (orb_value == 2) then
player:setVar("MissionStatus_orb1",3);
-- Time to get the glowing orb out
player:addKeyItem(FIRST_GLOWING_MANA_ORB);
player:messageSpecial(KEYITEM_OBTAINED,FIRST_GLOWING_MANA_ORB);
-- Check if all orbs have been placed or not
if (player:getVar("MissionStatus_orb2") == 3 and
player:getVar("MissionStatus_orb3") == 3 and
player:getVar("MissionStatus_orb4") == 3 and
player:getVar("MissionStatus_orb5") == 3 and
player:getVar("MissionStatus_orb6") == 3) then
player:messageSpecial(RETRIEVED_ALL_G_ORBS);
player:setVar("MissionStatus",5);
end
end
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/West_Ronfaure/npcs/Phairet.lua | 3 | 2616 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Phairet
-- Involved in Quest: The Trader in the Forest
-- !pos -57 -1 -501 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/West_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local theTraderInTheforest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
if (theTraderInTheforest == QUEST_ACCEPTED) then
if (trade:hasItemQty(592,1) == true and trade:getItemCount() == 1) then -- Trade Supplies Order
player:startEvent(0x007c);
end
elseif (theTraderInTheforest == QUEST_COMPLETED) then
if (trade:getGil() == 50) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4367);
else
player:tradeComplete();
player:addItem(4367);
player:messageSpecial(ITEM_OBTAINED,4367); -- Clump of Batagreens
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local theTraderInTheforest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
local hasBatagreens = player:hasItem(4367); -- Clump of Batagreens
if (theTraderInTheforest == QUEST_ACCEPTED) then
if (hasBatagreens == true) then
player:startEvent(0x007d);
else
player:startEvent(0x0075);
end
elseif (theTraderInTheforest == QUEST_COMPLETED or hasBatagreens == false) then
player:startEvent(0x007f,4367);
else
player:startEvent(0x0075);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x007c) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4367);
else
player:tradeComplete();
player:addItem(4367);
player:messageSpecial(ITEM_OBTAINED, 4367);
end
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/irmik_helvasi.lua | 11 | 1155 | -----------------------------------------
-- ID: 5572
-- Item: irmik_helvasi
-- Food Effect: 3 hours, All Races
-----------------------------------------
-- HP +10% (cap 75)
-- MP +3% (cap 13)
-- INT +1
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5572)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 10)
target:addMod(dsp.mod.FOOD_HP_CAP, 75)
target:addMod(dsp.mod.FOOD_MPP, 3)
target:addMod(dsp.mod.FOOD_MP_CAP, 13)
target:addMod(dsp.mod.INT, 1)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 10)
target:delMod(dsp.mod.FOOD_HP_CAP, 75)
target:delMod(dsp.mod.FOOD_MPP, 3)
target:delMod(dsp.mod.FOOD_MP_CAP, 13)
target:delMod(dsp.mod.INT, 1)
end
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Arrapago_Reef/mobs/Velionis.lua | 11 | 1944 | -----------------------------------
-- Area: Arrapago Reef
-- ZNM: Velionis
-----------------------------------
mixins = {require("scripts/mixins/rage")}
require("scripts/globals/status")
-----------------------------------
-- Todo: blaze spikes effect only activates while not in casting animation
function onMobInitialize(mob)
mob:setMobMod(dsp.mobMod.AUTO_SPIKES, 1)
mob:addStatusEffect(dsp.effect.BLAZE_SPIKES, 250, 0, 0)
mob:getStatusEffect(dsp.effect.BLAZE_SPIKES):setFlag(dsp.effectFlag.DEATH)
mob:setMobMod(dsp.mobMod.IDLE_DESPAWN, 300)
end
function onMobSpawn(mob)
mob:setLocalVar("[rage]timer", 3600) -- 60 minutes
mob:SetAutoAttackEnabled(false)
mob:setMod(dsp.mod.FASTCAST,15)
mob:setLocalVar("HPP", 90)
mob:setMobMod(dsp.mobMod.MAGIC_COOL,10)
end
function onMobFight(mob,target)
local FastCast = mob:getLocalVar("HPP")
if mob:getHPP() <= FastCast then
if mob:getHPP() > 10 then
mob:addMod(dsp.mod.FASTCAST, 15)
mob:setLocalVar("HPP", mob:getHPP() - 10)
end
end
end
function onSpikesDamage(mob, target, damage)
local INT_diff = mob:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)
if INT_diff > 20 then
INT_diff = 20 + (INT_diff - 20) * 0.5 -- INT above 20 is half as effective.
end
local dmg = (damage + INT_diff) * 0.5 -- INT adjustment and base damage averaged together.
local params = {}
params.bonusmab = 0
params.includemab = false
dmg = addBonusesAbility(mob, dsp.magic.ele.FIRE, target, dmg, params)
dmg = dmg * applyResistanceAddEffect(mob, target, dsp.magic.ele.FIRE, 0)
dmg = adjustForTarget(target, dmg, dsp.magic.ele.FIRE)
dmg = finalMagicNonSpellAdjustments(mob, target, dsp.magic.ele.FIRE, dmg)
if dmg < 0 then
dmg = 0
end
return dsp.subEffect.BLAZE_SPIKES, dsp.msg.basic.SPIKES_EFFECT_DMG, dmg
end
function onMobDeath(mob, player, isKiller)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Monastic_Cavern/TextIDs.lua | 3 | 1704 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6386; -- Obtained: <item>.
GIL_OBTAINED = 6387; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7283; -- You unlock the chest!
CHEST_FAIL = 7284; -- Fails to open the chest.
CHEST_TRAP = 7285; -- The chest was trapped!
CHEST_WEAK = 7286; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7287; -- The chest was a mimic!
CHEST_MOOGLE = 7288; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7289; -- The chest was but an illusion...
CHEST_LOCKED = 7290; -- The chest appears to be locked.
-- Other dialog
NOTHING_OUT_OF_ORDINARY = 6400; -- There is nothing out of the ordinary here.
ALTAR = 7262; -- This appears to be an altar.
THE_MAGICITE_GLOWS_OMINOUSLY = 7265; -- The magicite glows ominously.
ORCISH_OVERLORD_ENGAGE = 7295; -- Intruders? Get outs here! We gots us some adventurers!
ORCISH_OVERLORD_DEATH = 7296; -- Gahahahaha... You fell for our trick. I'm not the big boss. He don't need to be troubled by runty little rarabs like you.
ORC_KING_ENGAGE = 7297; -- Ungh? Who are you?So, you've come to kill big boss Bakgodek? I'll crush your scrawny bones myself!
ORC_KING_DEATH = 7298; -- Unghh... Foolish children of Altana. Defeating me won't change anything. There will be others from the north...
-- conquest Base
CONQUEST_BASE = 7047; -- Tallying conquest results...
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/dish_of_spaghetti_nero_di_seppia.lua | 12 | 1809 | -----------------------------------------
-- ID: 5193
-- Item: dish_of_spaghetti_nero_di_seppia
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP % 17 (cap 130)
-- Dexterity 3
-- Vitality 2
-- Agility -1
-- Mind -2
-- Charisma -1
-- Double Attack 1
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5193);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 17);
target:addMod(MOD_FOOD_HP_CAP, 130);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_AGI, -1);
target:addMod(MOD_MND, -2);
target:addMod(MOD_CHR, -1);
target:addMod(MOD_DOUBLE_ATTACK, 1);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 17);
target:delMod(MOD_FOOD_HP_CAP, 130);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_AGI, -1);
target:delMod(MOD_MND, -2);
target:delMod(MOD_CHR, -1);
target:delMod(MOD_DOUBLE_ATTACK, 1);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Aht_Urhgan_Whitegate/npcs/Tehf_Kimasnahya.lua | 3 | 3124 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Tehf Kimasnahya
-- Type: Standard NPC
-- !pos -89.897 -1 6.199 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local gotitall = player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL);
local gotItAllProg = player:getVar("gotitallCS");
local threeMenProg = player:getVar("threemenandaclosetCS");
if (gotitall == QUEST_AVAILABLE) then
player:startEvent(0x0208);
elseif (gotItAllProg == 4) then
player:startEvent(0x020d);
elseif (gotItAllProg == 6) then
player:startEvent(0x020f);
elseif (gotItAllProg >= 7 and player:getVar("Wait1DayForgotitallCS_date") < os.time() and player:needToZone() == false) then
player:startEvent(0x0210);
elseif (gotItAllProg >= 7) then
player:startEvent(0x021b);
elseif (gotItAllProg >= 1 and gotItAllProg <= 3) then
player:startEvent(0x0209);
elseif (threeMenProg == 5) then
player:startEvent(0x034b);
elseif (threeMenProg == 6) then
player:startEvent(0x034c);
else
player:startEvent(0x0211);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0208) then
player:addQuest(AHT_URHGAN,GOT_IT_ALL);
player:setVar("gotitallCS",1);
elseif (csid == 0x020d and option == 0) then
player:setVar("gotitallCS",5);
player:delKeyItem(VIAL_OF_LUMINOUS_WATER);
elseif (csid == 0x020f) then
player:setVar("gotitallCS",7);
player:setVar("Wait1DayForgotitallCS_date", getMidnight());
player:needToZone(true);
elseif (csid == 0x021b) then
player:setVar("gotitallCS",8);
elseif (csid == 0x0210) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18257);
else
player:setVar("Wait1DayForgotitallCS_date",0);
player:setVar("gotitallCS",0);
player:addItem(18257); -- Bibiki Seashell
player:messageSpecial(ITEM_OBTAINED,18257);
player:completeQuest(AHT_URHGAN,GOT_IT_ALL);
end
elseif (csid == 0x034b and option == 1) then
player:setVar("threemenandaclosetCS",6);
end
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Quelveuiat.lua | 9 | 2222 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Quelveuiat
-- Standard Info NPC
-- !pos -3.177 -22.750 -25.970 26
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Tavnazian_Safehold/IDs");
-----------------------------------
function onTrade(player,npc,trade)
local SealionCrestKey = trade:hasItemQty(1658,1);
local CoralCrestKey = trade:hasItemQty(1659,1);
local Count = trade:getItemCount();
if (player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_HARD_DAY_S_KNIGHT) == QUEST_COMPLETED and player:hasKeyItem(dsp.ki.TEMPLE_KNIGHT_KEY) == false) then
-- Trade Sealion and Coral Crest keys to obtain Temple Knight key (keyitem).
if (SealionCrestKey and CoralCrestKey and Count == 2) then
player:addKeyItem(dsp.ki.TEMPLE_KNIGHT_KEY);
player:tradeComplete();
player:messageSpecial(ID.text.KEYITEM_OBTAINED);
end
end
end;
function onTrigger(player,npc)
if (player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_HARD_DAY_S_KNIGHT) == QUEST_AVAILABLE) then
player:startEvent(119);
elseif (player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_HARD_DAY_S_KNIGHT) == QUEST_ACCEPTED and player:getCharVar("SPLINTERSPINE_GRUKJUK") <= 1) then
player:startEvent(120);
elseif (player:getCharVar("SPLINTERSPINE_GRUKJUK") == 2 and player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_HARD_DAY_S_KNIGHT) == QUEST_ACCEPTED) then
player:startEvent(121);
else
player:startEvent(122);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 119 and option == 3) then
player:addQuest(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_HARD_DAY_S_KNIGHT);
elseif (csid == 121) then
player:setCharVar("SPLINTERSPINE_GRUKJUK",0);
player:completeQuest(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_HARD_DAY_S_KNIGHT);
player:addGil(GIL_RATE*2100);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*2100);
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Windurst_Woods/npcs/Ju_Kamja.lua | 3 | 1066 | ----------------------------------
-- Area: Windurst Woods
-- NPC: Ju Kamja
-- Type: Item Deliverer
-- !pos 58.145 -2.5 -136.91 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/AlTaieu/Zone.lua | 32 | 2324 | -----------------------------------
--
-- Zone: AlTaieu (33)
--
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-25,-1 ,-620 ,33);
end
if (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus")==0) then
cs=0x0001;
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==0) then
cs=0x00A7;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0001) then
player:setVar("PromathiaStatus",1);
player:addKeyItem(LIGHT_OF_ALTAIEU);
player:messageSpecial(KEYITEM_OBTAINED,LIGHT_OF_ALTAIEU);
player:addTitle(SEEKER_OF_THE_LIGHT);
elseif (csid == 0x00A7) then
player:setVar("PromathiaStatus",1);
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/PsoXja/npcs/_09b.lua | 3 | 2848 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _09b (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- !pos 278.399 -1.925 -50.000 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == JOBS.THF) then
local X=player:getXPos();
if (npc:getAnimation() == 9) then
if (X <= 278) then
if (GetMobAction(16814092) == 0) then
local Rand = math.random(1,2); -- estimated 50% success as per the wiki
if (Rand == 1) then -- Spawn Gargoyle
player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true);
SpawnMob(16814092):updateClaim(player); -- Gargoyle
else
player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true);
npc:openDoor(30);
end
player:tradeComplete();
else
player:messageSpecial(DOOR_LOCKED);
end
end
end
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local X=player:getXPos();
if (npc:getAnimation() == 9) then
if (X <= 278) then
if (GetMobAction(16814092) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true);
SpawnMob(16814092):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif (X >= 279) then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/RuAun_Gardens/npcs/qm2.lua | 3 | 1472 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: ??? (Seiryu's Spawn)
-- Allows players to spawn the HNM Seiryu with a Gem of the East and a Springstone.
-- !pos 569 -70 -80 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Gem of the East and Springstone
if (GetMobAction(17309981) == 0 and trade:hasItemQty(1418,1) and trade:hasItemQty(1419,1) and trade:getItemCount() == 2) then
player:tradeComplete();
SpawnMob(17309981):updateClaim(player); -- Spawn Seiryu
player:showText(npc,SKY_GOD_OFFSET + 9);
npc:setStatus(STATUS_DISAPPEAR);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(SKY_GOD_OFFSET + 1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Kazham/npcs/Jakoh_Wahcondalo.lua | 3 | 1767 | -----------------------------------
-- Area: Kazham
-- NPC: Jakoh Wahcondalo
-- !pos 101 -16 -115 250
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == KAZAMS_CHIEFTAINESS) then
player:startEvent(0x0072);
elseif (player:getCurrentMission(ZILART) == THE_TEMPLE_OF_UGGALEPIH) then
player:startEvent(0x0073);
elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 2) then
player:startEvent(0x0109);
else
player:startEvent(0x0071);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0072) then
player:addKeyItem(SACRIFICIAL_CHAMBER_KEY);
player:messageSpecial(KEYITEM_OBTAINED,SACRIFICIAL_CHAMBER_KEY);
player:completeMission(ZILART,KAZAMS_CHIEFTAINESS);
player:addMission(ZILART,THE_TEMPLE_OF_UGGALEPIH);
elseif (csid == 0x0109) then
player:setVar("MissionStatus",3);
end
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/abilities/addendum_black.lua | 12 | 1511 | -----------------------------------
-- Ability: Addendum: Black
-- Allows access to additional Black Magic spells while using Dark Arts.
-- Obtained: Scholar Level 30
-- Recast Time: Stratagem Charge
-- Duration: 2 hours
--
-- Level |Charges |Recharge Time per Charge
-- ----- -------- ---------------
-- 10 |1 |4:00 minutes
-- 30 |2 |2:00 minutes
-- 50 |3 |1:20 minutes
-- 70 |4 |1:00 minute
-- 90 |5 |48 seconds
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(dsp.effect.ADDENDUM_BLACK) then
return dsp.msg.basic.EFFECT_ALREADY_ACTIVE, 0
end
return 0,0
end
function onUseAbility(player,target,ability)
player:delStatusEffectSilent(dsp.effect.LIGHT_ARTS)
player:delStatusEffectSilent(dsp.effect.ADDENDUM_WHITE)
player:delStatusEffectSilent(dsp.effect.DARK_ARTS)
local skillbonus = player:getMod(dsp.mod.DARK_ARTS_SKILL)
local effectbonus = player:getMod(dsp.mod.DARK_ARTS_EFFECT)
local helixbonus = 0
if (player:getMainJob() == dsp.job.SCH and player:getMainLvl() >= 20) then
helixbonus = math.floor(player:getMainLvl() / 4)
end
player:addStatusEffectEx(dsp.effect.ADDENDUM_BLACK,dsp.effect.ADDENDUM_BLACK,effectbonus,0,7200,0,helixbonus,true)
return dsp.effect.ADDENDUM_BLACK
end | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Port_Jeuno/npcs/Kochahy-Muwachahy.lua | 3 | 2232 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Kochahy-Muwachahy
-- !pos 40 0 6 246
-------------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/conquest");
require("scripts/zones/Port_Jeuno/TextIDs");
local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno).
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Menu1 = getArg1(guardnation,player);
local Menu3 = conquestRanking();
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
local inventory, size;
if (player:getNation() == 0) then
inventory = SandInv;
size = #SandInv;
elseif (player:getNation() == 1) then
inventory = BastInv;
size = #BastInv;
else
inventory = WindInv;
size = #WindInv;
end
updateConquestGuard(player,csid,option,size,inventory);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
local inventory, size;
if (player:getNation() == 0) then
inventory = SandInv;
size = #SandInv;
elseif (player:getNation() == 1) then
inventory = BastInv;
size = #BastInv;
else
inventory = WindInv;
size = #WindInv;
end
finishConquestGuard(player,csid,option,size,inventory,guardnation);
end;
| gpl-3.0 |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-codec.lua | 80 | 2172 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
codec_a_mu = module:option(ListValue, "codec_a_mu", "A-law and Mulaw direct Coder/Decoder", "")
codec_a_mu:value("yes", "Load")
codec_a_mu:value("no", "Do Not Load")
codec_a_mu:value("auto", "Load as Required")
codec_a_mu.rmempty = true
codec_adpcm = module:option(ListValue, "codec_adpcm", "Adaptive Differential PCM Coder/Decoder", "")
codec_adpcm:value("yes", "Load")
codec_adpcm:value("no", "Do Not Load")
codec_adpcm:value("auto", "Load as Required")
codec_adpcm.rmempty = true
codec_alaw = module:option(ListValue, "codec_alaw", "A-law Coder/Decoder", "")
codec_alaw:value("yes", "Load")
codec_alaw:value("no", "Do Not Load")
codec_alaw:value("auto", "Load as Required")
codec_alaw.rmempty = true
codec_g726 = module:option(ListValue, "codec_g726", "ITU G.726-32kbps G726 Transcoder", "")
codec_g726:value("yes", "Load")
codec_g726:value("no", "Do Not Load")
codec_g726:value("auto", "Load as Required")
codec_g726.rmempty = true
codec_gsm = module:option(ListValue, "codec_gsm", "GSM/PCM16 (signed linear) Codec Translation", "")
codec_gsm:value("yes", "Load")
codec_gsm:value("no", "Do Not Load")
codec_gsm:value("auto", "Load as Required")
codec_gsm.rmempty = true
codec_speex = module:option(ListValue, "codec_speex", "Speex/PCM16 (signed linear) Codec Translator", "")
codec_speex:value("yes", "Load")
codec_speex:value("no", "Do Not Load")
codec_speex:value("auto", "Load as Required")
codec_speex.rmempty = true
codec_ulaw = module:option(ListValue, "codec_ulaw", "Mu-law Coder/Decoder", "")
codec_ulaw:value("yes", "Load")
codec_ulaw:value("no", "Do Not Load")
codec_ulaw:value("auto", "Load as Required")
codec_ulaw.rmempty = true
return cbimap
| gpl-2.0 |
keplerproject/luarocks | spec/doc_spec.lua | 2 | 6174 | local test_env = require("spec.util.test_env")
local run = test_env.run
local testing_paths = test_env.testing_paths
test_env.unload_luarocks()
describe("luarocks doc #integration", function()
before_each(function()
test_env.setup_specs()
end)
describe("basic tests", function()
it("with no flags/arguments", function()
assert.is_false(run.luarocks_bool("doc"))
end)
it("with invalid argument", function()
assert.is_false(run.luarocks_bool("doc invalid"))
end)
it("with no homepage and no doc folder", function()
test_env.run_in_tmp(function(tmpdir)
test_env.write_file("test-1.0-1.rockspec", [[
package = "test"
version = "1.0-1"
source = {
url = "file://test.lua"
}
build = {
type = "builtin",
modules = {
test = "test.lua"
}
}
]], finally)
test_env.write_file("test.lua", "return {}", finally)
assert.is_true(run.luarocks_bool("install test-1.0-1.rockspec"))
assert.is_false(run.luarocks_bool("doc test --home"))
end, finally)
end)
it("with no doc folder but with homepage", function()
test_env.run_in_tmp(function(tmpdir)
test_env.write_file("test-1.0-1.rockspec", [[
package = "test"
version = "1.0-1"
source = {
url = "file://test.lua"
}
description = {
homepage = "http://www.example.com"
}
build = {
type = "builtin",
modules = {
test = "test.lua"
}
}
]], finally)
test_env.write_file("test.lua", "return {}", finally)
assert.is_true(run.luarocks_bool("install test-1.0-1.rockspec"))
local output = assert.is.truthy(run.luarocks("doc test"))
assert.is.truthy(output:find("documentation directory not found"))
end, finally)
end)
end)
describe("#namespaces", function()
it("retrieves docs for a namespaced package from the command-line", function()
assert(run.luarocks_bool("build a_user/a_rock --server=" .. testing_paths.fixtures_dir .. "/a_repo" ))
assert(run.luarocks_bool("build a_rock 1.0 --keep --server=" .. testing_paths.fixtures_dir .. "/a_repo" ))
assert.match("a_rock 2.0", run.luarocks("doc a_user/a_rock"))
end)
end)
describe("tests with flags", function()
it("of installed package", function()
test_env.run_in_tmp(function(tmpdir)
test_env.write_file("test-1.0-1.rockspec", [[
package = "test"
version = "1.0-1"
source = {
url = "file://test.lua"
}
build = {
type = "builtin",
modules = {
test = "test.lua"
}
}
]], finally)
test_env.write_file("test.lua", "return {}", finally)
assert.is_true(run.luarocks_bool("install test-1.0-1.rockspec"))
lfs.mkdir(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc")
test_env.write_file(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc/doc.md", "", finally)
test_env.write_file(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc/readme.md", "", finally)
assert.is_true(run.luarocks_bool("doc test"))
end, finally)
end)
it("with --list", function()
test_env.run_in_tmp(function(tmpdir)
test_env.write_file("test-1.0-1.rockspec", [[
package = "test"
version = "1.0-1"
source = {
url = "file://test.lua"
}
build = {
type = "builtin",
modules = {
test = "test.lua"
}
}
]], finally)
test_env.write_file("test.lua", "return {}", finally)
assert.is_true(run.luarocks_bool("install test-1.0-1.rockspec"))
lfs.mkdir(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc")
test_env.write_file(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc/doc1.md", "", finally)
test_env.write_file(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc/doc2.md", "", finally)
local output = assert.is.truthy(run.luarocks("doc test --list"))
assert.is.truthy(output:find("doc1%.md"))
assert.is.truthy(output:find("doc2%.md"))
end, finally)
end)
it("with --local", function()
assert.is_true(run.luarocks_bool("install --server=" .. testing_paths.fixtures_dir .. "/a_repo a_rock"))
assert.is_true(run.luarocks_bool("doc --server=" .. testing_paths.fixtures_dir .. "/a_repo a_rock --local"))
end)
it("with --porcelain", function()
test_env.run_in_tmp(function(tmpdir)
test_env.write_file("test-1.0-1.rockspec", [[
package = "test"
version = "1.0-1"
source = {
url = "file://test.lua"
}
build = {
type = "builtin",
modules = {
test = "test.lua"
}
}
]], finally)
test_env.write_file("test.lua", "return {}", finally)
assert.is_true(run.luarocks_bool("install test-1.0-1.rockspec"))
lfs.mkdir(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc")
test_env.write_file(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc/doc1.md", "", finally)
test_env.write_file(testing_paths.testing_sys_rocks .. "/test/1.0-1/doc/doc2.md", "", finally)
assert.is_true(run.luarocks_bool("doc test --porcelain"))
end, finally)
end)
end)
end)
| mit |
gedads/Neodynamis | scripts/zones/Beadeaux/npcs/qm2.lua | 3 | 1444 | --------------------------
-- Area: Beadeaux
-- NPC: ??? (qm2)
-- Type: Quest NPC
-- !pos -79 1 -99 147
--------------------------
package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil;
--------------------------
require("scripts/zones/Beadeaux/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/weather");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- TODO: The ??? should only spawn during rainy weather, temporary fix in place to prevent players from getting the keyitem unless the proper weather is present.
if (player:getQuestStatus(BASTOK,BEADEAUX_SMOG) == QUEST_ACCEPTED and player:hasKeyItem(CORRUPTED_DIRT) == false and player:getWeather() == WEATHER_RAIN) then
player:addKeyItem(CORRUPTED_DIRT);
player:messageSpecial(KEYITEM_OBTAINED,CORRUPTED_DIRT);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
hyee/dbcli | mysql/mysqluc.lua | 1 | 3588 |
local env,db,os,java=env,env.getdb(),os,java
local ora=db.C.ora
local utils=env.class(env.subsystem)
function utils:ctor()
self.db=env.getdb()
self.support_redirect=false
self.name="MYSQLUC"
self.command=nil
self.executable="mysqluc.exe"
self.description="Switch to MySQL Utilities, the default working folder is 'mysql/util'. Usage: @@NAME [-n|-d<work_path>] [other args]"
self.help_title='Run mysql script under the "mysqluc" directory. '
self.script_dir,self.extend_dirs=self.db.ROOT_PATH.."mysqluc",{}
self.prompt_pattern="^(.+[>\\$#@] *| *\\d+ +)$"
end
function utils:after_process_created()
self.work_dir=self.work_path
print(self:get_last_line("select * from(&prompt_sql);"))
self:run_command('store set dbcli_utils_settings.sql replace',false)
end
function utils:rebuild_commands(work_dir)
self.cmdlist=self.super.rehash(self,self.script_dir,self.ext_name,self.extend_dirs)
if work_dir and work_dir~=self.script_dir and work_dir~=self.extend_dirs then
local cmds=self.super.rehash(self,work_dir,self.ext_name)
for k,v in pairs(cmds) do
self.cmdlist[k]=v
end
end
end
function utils:run_command(cmd,is_print)
if not self.enter_flag and cmd then
cmd=cmd..'\0'
end
return self.super.run_command(self,cmd,is_print)
end
function utils:set_work_dir(path,quiet)
self.super.set_work_dir(self,path,quiet)
if not quiet and path and path~="" then
self:make_sqlpath()
self:rebuild_commands(self.work_dir)
end
end
function utils:make_sqlpath()
local path={}
if self.work_dir then path[#path+1]=self.work_dir end
if self.extend_dirs then path[#path+1]=self.extend_dirs end
if self.script_dir then path[#path+1]=self.script_dir end
for i=#path,1,-1 do
if path[i]:lower():find(env._CACHE_BASE:lower(),1,true) then table.remove(path,i) end
end
local cmd='dir /s/b/a:d "'..table.concat(path,'" "')..'" 2>nul'
if not env.IS_WINDOWS then
cmd='find "'..table.concat(path,'" "')..'" -type d 2>/dev/null'
end
local dirs=io.popen(cmd)
for n in dirs:lines() do path[#path+1]=n end
table.sort(path,function(a,b)
a,b=a:lower(),b:lower()
local c1=(a:find(self.script_dir:lower(),1,true) and 3) or (self.extend_dirs and a:find(self.extend_dirs:lower(),1,true) and 2) or 1
local c2=(b:find(self.script_dir:lower(),1,true) and 3) or (self.extend_dirs and b:find(self.extend_dirs:lower(),1,true) and 2) or 1
if c1~=c2 then return c1<c2 end
return a<b
end)
self.env['SQLPATH']=table.concat(path,';')
--self.proc:setEnv("SQLPATH",self.env['SQLPATH'])
end
function utils:get_startup_cmd(args,is_native)
db:assert_connect()
local conn=db.connection_info
local props={"--utildir=="..self.work_dir,'--width=200'}
self:make_sqlpath()
self.work_path,self.work_dir=self.work_dir,env._CACHE_PATH
self:rebuild_commands(self.env['SQLPATH'])
for k,v in ipairs(args) do
if args[i]:find("^--utildir=.+") then
props[1]=v
self.work_dir=v:match("=(.*+)")
elseif args[i]:find("^--width=.+") then
props[2]=v
else
props[#props+1]=v
end
end
return props
end
function utils:run_sql(g_sql,g_args,g_cmd,g_file)
end
function utils:after_script()
self.work_path=nil
end
function utils:onload()
env.event.snoop("AFTER_MYSQL_CONNECT",self.terminate,self)
env.event.snoop("ON_DB_DISCONNECTED",self.terminate,self)
end
return utils.new() | mit |
bigrpg/skynet | test/testsocket.lua | 20 | 1085 | local skynet = require "skynet"
local socket = require "skynet.socket"
local mode , id = ...
local function echo(id)
socket.start(id)
while true do
local str = socket.read(id)
if str then
socket.write(id, str)
else
socket.close(id)
return
end
end
end
if mode == "agent" then
id = tonumber(id)
skynet.start(function()
skynet.fork(function()
echo(id)
skynet.exit()
end)
end)
else
local function accept(id)
socket.start(id)
socket.write(id, "Hello Skynet\n")
skynet.newservice(SERVICE_NAME, "agent", id)
-- notice: Some data on this connection(id) may lost before new service start.
-- So, be careful when you want to use start / abandon / start .
socket.abandon(id)
end
skynet.start(function()
local id = socket.listen("127.0.0.1", 8001)
print("Listen socket :", "127.0.0.1", 8001)
socket.start(id , function(id, addr)
print("connect from " .. addr .. " " .. id)
-- you have choices :
-- 1. skynet.newservice("testsocket", "agent", id)
-- 2. skynet.fork(echo, id)
-- 3. accept(id)
accept(id)
end)
end)
end | mit |
gedads/Neodynamis | scripts/zones/Mhaura/npcs/Explorer_Moogle.lua | 17 | 1876 | -----------------------------------
-- Area: Mhaura
-- NPC: Explorer Moogle
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/teleports");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local accept = 0;
local event = 0x014e;
if (player:getGil() < 300) then
accept = 1;
end
if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then
event = event + 1;
end
player:startEvent(event,player:getZoneID(),0,accept);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local price = 300;
if (csid == 0x014e) then
if (option == 1 and player:delGil(price)) then
toExplorerMoogle(player,231);
elseif (option == 2 and player:delGil(price)) then
toExplorerMoogle(player,234);
elseif (option == 3 and player:delGil(price)) then
toExplorerMoogle(player,240);
elseif (option == 4 and player:delGil(price)) then
toExplorerMoogle(player,248);
elseif (option == 5 and player:delGil(price)) then
toExplorerMoogle(player,249);
end
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/zones/Balgas_Dais/bcnms/saintly_invitation.lua | 9 | 1701 | -----------------------------------
-- Area: Horlais Peak
-- Name: Saintly Invitation
-- !pos 299 -123 345 146
-----------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/npc_util")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
if player:hasCompletedMission(WINDURST, dsp.mission.id.windurst.SAINTLY_INVITATION) then
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 1)
else
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
end
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
if player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.SAINTLY_INVITATION then
player:addTitle(dsp.title.VICTOR_OF_THE_BALGA_CONTEST)
npcUtil.giveKeyItem(player, dsp.ki.BALGA_CHAMPION_CERTIFICATE)
player:setCharVar("MissionStatus", 2)
end
end
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/tanners_belt.lua | 15 | 1199 | -----------------------------------------
-- ID: 15448
-- Item: Tanners belt
-- Enchantment: Synthesis image support
-- 2Min, All Races
-----------------------------------------
-- Enchantment: Synthesis image support
-- Duration: 2Min
-- Leathercraft Skill +3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY) == true) then
result = 240;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY,3,0,120);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_SKILL_LTH, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_SKILL_LTH, 1);
end; | gpl-3.0 |
gedads/Neodynamis | scripts/globals/weaponskills/shockwave.lua | 18 | 1486 | -----------------------------------
-- Shockwave
-- Great Sword weapon skill
-- Skill level: 150
-- Delivers an area of effect attack. Sleeps enemies. Duration of effect varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Aqua Gorget.
-- Aligned with the Aqua Belt.
-- Element: None
-- Modifiers: STR:30% ; MND:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
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 = 1; params.ftp300 = 1;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
if (damage > 0 and target:hasStatusEffect(EFFECT_SLEEP_I) == false) then
local duration = (tp/1000 * 60);
target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration);
end
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
starlightknight/darkstar | scripts/globals/maws.lua | 8 | 5885 | -----------------------------------
-- Cavernous Maw global functions
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/quests")
require("scripts/globals/settings")
require("scripts/globals/teleports")
require("scripts/globals/titles")
require("scripts/globals/zone")
-----------------------------------
dsp.maws = dsp.maws or {}
local ZN = dsp.zone
local MAW = dsp.teleport.type.PAST_MAW
local pastMaws =
{ --[ZONE ID] = {Bit Slot in Array, Cutscenes{new to WoTg or add new, mission, warp}, Destination {Coordinates}}
[ZN.BATALLIA_DOWNS] = {bit = 0, cs = {new = 500, msn = 501, warp = 910}, dest = { -51.486, 0.371, 436.972, 128, 84}},
[ZN.ROLANBERRY_FIELDS] = {bit = 1, cs = {new = 500, msn = 501, warp = 904}, dest = {-196.500, 7.999, 361.192, 225, 91}},
[ZN.SAUROMUGUE_CHAMPAIGN] = {bit = 2, cs = {new = 500, msn = 501, warp = 904}, dest = { 366.858, 8.545, -228.861, 95, 98}},
[ZN.JUGNER_FOREST] = {bit = 3, cs = {add = nil, msn = nil, warp = 905}, dest = {-116.093, -8.005, -520.041, 0, 82}},
[ZN.PASHHOW_MARSHLANDS] = {bit = 4, cs = {add = nil, msn = nil, warp = 905}, dest = { 415.945, 24.659, 25.611, 101, 90}},
[ZN.MERIPHATAUD_MOUNTAINS] = {bit = 5, cs = {add = nil, msn = nil, warp = 905}, dest = { 595.000, -32.000, 279.300, 93, 97}},
[ZN.EAST_RONFAURE] = {bit = 6, cs = {add = nil, msn = nil, warp = 904}, dest = { 322.057, -60.059, 503.712, 64, 81}},
[ZN.NORTH_GUSTABERG] = {bit = 7, cs = {add = nil, msn = nil, warp = 903}, dest = { 469.697, -0.050, 478.949, 0, 88}},
[ZN.WEST_SARUTABARUTA] = {bit = 8, cs = {add = nil, msn = nil, warp = 904}, dest = { 2.628, -0.150, -166.562, 32, 95}},
[ZN.BATALLIA_DOWNS_S] = {bit = 0, cs = {add = 100, msn = 701, warp = 101}, dest = { -51.486, 0.371, 436.972, 128, 105}},
[ZN.ROLANBERRY_FIELDS_S] = {bit = 1, cs = {add = 101, msn = 701, warp = 102}, dest = {-196.500, 7.999, 361.192, 225, 110}},
[ZN.SAUROMUGUE_CHAMPAIGN_S] = {bit = 2, cs = {add = 101, msn = 701, warp = 102}, dest = { 366.858, 8.545, -228.861, 95, 120}},
[ZN.JUGNER_FOREST_S] = {bit = 3, cs = {add = 101, msn = nil, warp = 102}, dest = {-116.093, -8.005, -520.041, 0, 104}},
[ZN.PASHHOW_MARSHLANDS_S] = {bit = 4, cs = {add = 100, msn = nil, warp = 101}, dest = { 415.945, 24.659, 25.611, 101, 109}},
[ZN.MERIPHATAUD_MOUNTAINS_S] = {bit = 5, cs = {add = 102, msn = nil, warp = 103}, dest = { 595.000, -32.000, 279.300, 93, 119}},
[ZN.EAST_RONFAURE_S] = {bit = 6, cs = {add = 100, msn = nil, warp = 101}, dest = { 322.057, -60.059, 503.712, 64, 101}},
[ZN.NORTH_GUSTABERG_S] = {bit = 7, cs = {add = 100, msn = nil, warp = 101}, dest = { 469.697, -0.050, 478.949, 0, 106}},
[ZN.WEST_SARUTABARUTA_S] = {bit = 8, cs = {add = 100, msn = nil, warp = 101}, dest = { 2.628, -0.150, -166.562, 32, 115}},
}
local function meetsMission2Reqs(player)
if not player:getCurrentMission(WOTG) == dsp.mission.id.wotg.BACK_TO_THE_BEGINNING then
return false
end
local Q = dsp.quest.id.crystalWar
local Q1 = player:getQuestStatus(CRYSTAL_WAR, Q.CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED
local Q2 = player:getQuestStatus(CRYSTAL_WAR, Q.THE_TIGRESS_STRIKES) == QUEST_COMPLETED
local Q3 = player:getQuestStatus(CRYSTAL_WAR, Q.FIRES_OF_DISCONTENT) == QUEST_COMPLETED
return Q1 or Q2 or Q3
end
dsp.maws.onTrigger = function(player, npc)
local ID = zones[player:getZoneID()]
if not ENABLE_WOTG == 1 then
player:messageSpecial(ID.text.NOTHING_HAPPENS)
return
end
local maw = pastMaws[player:getZoneID()]
local hasMaw = player:hasTeleport(MAW, maw.bit)
local event = nil
if maw.cs.msn and meetsMission2Reqs(player) then
event = maw.cs.msn
elseif hasMaw then
event = maw.cs.warp
else
local hasFeather = player:hasKeyItem(dsp.ki.PURE_WHITE_FEATHER)
if maw.cs.new and not hasFeather then
event = maw.cs.new
elseif maw.cs.add then
event = maw.cs.add
end
end
if event then
player:startEvent(event)
else
player:messageSpecial(ID.text.NOTHING_HAPPENS)
end
end
dsp.maws.onEventFinish = function(player, csid, option)
local maw = pastMaws[player:getZoneID()]
local goToMaw = function()
player:setPos(unpack(maw.dest))
end
local addMaw = function()
if not player:hasTeleport(MAW, maw.bit) then
player:addTeleport(MAW, maw.bit)
end
goToMaw()
end
if csid == maw.cs.warp and option == 1 then
goToMaw() -- Known to have maw, no need to check
elseif maw.cs.add and csid == maw.cs.add and option == 1 then
addMaw()
elseif maw.cs.msn and csid == maw.cs.msn then
player:completeMission(WOTG, dsp.mission.id.wotg.BACK_TO_THE_BEGINNING)
player:addMission(WOTG, dsp.mission.id.wotg.CAIT_SITH)
player:addTitle(dsp.title.CAIT_SITHS_ASSISTANT)
addMaw() -- May not have yet, check
elseif maw.cs.new and csid == maw.cs.new then
local ID = zones[player:getZoneID()]
player:completeMission(WOTG,dsp.mission.id.wotg.CAVERNOUS_MAWS)
player:addMission(WOTG,dsp.mission.id.wotg.BACK_TO_THE_BEGINNING)
player:addKeyItem(dsp.ki.PURE_WHITE_FEATHER)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.PURE_WHITE_FEATHER)
local x = math.random(1, 3)
if x == 1 then
maw = pastMaws[ZN.BATALLIA_DOWNS]
elseif x == 2 then
maw = pastMaws[ZN.ROLANBERRY_FIELDS]
else
maw = pastMaws[ZN.SAUROMUGUE_CHAMPAIGN]
end
addMaw()
end
end | gpl-3.0 |
starlightknight/darkstar | scripts/commands/additem.lua | 12 | 1374 | ---------------------------------------------------------------------------------------------------
-- func: additem <itemId> <quantity> <aug1> <v1> <aug2> <v2> <aug3> <v3> <aug4> <v4> <trial>
-- desc: Adds an item to the GMs inventory.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "iiiiiiiiiii"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!additem <itemId> {quantity} {aug1} {v1} {aug2} {v2} {aug3} {v3} {aug4} {v4} {trial}");
end;
function onTrigger(player, itemId, quantity, aug0, aug0val, aug1, aug1val, aug2, aug2val, aug3, aug3val, trialId)
-- Load needed text ids for players current zone..
local ID = zones[player:getZoneID()]
-- validate itemId
if (itemId == nil or tonumber(itemId) == nil or tonumber(itemId) == 0) then
error(player, "Invalid itemId.");
return;
end
-- Ensure the GM has room to obtain the item...
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial( ID.text.ITEM_CANNOT_BE_OBTAINED, itemId );
return;
end
-- Give the GM the item...
player:addItem( itemId, quantity, aug0, aug0val, aug1, aug1val, aug2, aug2val, aug3, aug3val, trialId );
player:messageSpecial( ID.text.ITEM_OBTAINED, itemId );
end | gpl-3.0 |
starlightknight/darkstar | scripts/globals/mobskills/gregale_wing.lua | 11 | 1298 | ---------------------------------------------
-- Gregale Wing
--
-- Description: An icy wind deals Ice damage to enemies within a very wide area of effect. Additional effect: Paralyze
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 30' radial.
-- Notes: Used only by Jormungand and Isgebind
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:hasStatusEffect(dsp.effect.BLOOD_WEAPON)) then
return 1
elseif (mob:AnimationSub() == 1) then
return 1
elseif (target:isBehind(mob, 48) == true) then
return 1
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.PARALYSIS
MobStatusEffectMove(mob, target, typeEffect, 40, 0, 120)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,dsp.magic.ele.ICE,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.ICE,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.ICE)
return dmg
end
| gpl-3.0 |
dantezhu/neon | examples/demo1/src/cocos/network/DeprecatedNetworkFunc.lua | 61 | 1123 | if nil == cc.XMLHttpRequest then
return
end
--tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of WebSocket will be deprecated begin
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) then
local WebSocketDeprecated = { }
function WebSocketDeprecated.sendTextMsg(self, string)
deprecatedTip("WebSocket:sendTextMsg","WebSocket:sendString")
return self:sendString(string)
end
WebSocket.sendTextMsg = WebSocketDeprecated.sendTextMsg
function WebSocketDeprecated.sendBinaryMsg(self, table,tablesize)
deprecatedTip("WebSocket:sendBinaryMsg","WebSocket:sendString")
string.char(unpack(table))
return self:sendString(string.char(unpack(table)))
end
WebSocket.sendBinaryMsg = WebSocketDeprecated.sendBinaryMsg
end
--functions of WebSocket will be deprecated end
| mit |
gedads/Neodynamis | scripts/zones/Maze_of_Shakhrami/npcs/qm2.lua | 3 | 1840 | -----------------------------------
-- Area: Maze of Shakhrami
-- NPC: qm2
-- Type: Quest NPC
-- !pos 143 9 -219 198
-----------------------------------
package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Maze_of_Shakhrami/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local wyrm1 = 17588701;
local wyrm2 = 17588702;
local wyrm3 = 17588703;
if (player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN) ~= QUEST_AVAILABLE and
player:getVar("ECO_WARRIOR_ACTIVE") == 238 and
player:hasStatusEffect(EFFECT_LEVEL_RESTRICTION) and
player:hasKeyItem(INDIGESTED_MEAT) == false) then
if (player:getVar("ECOR_WAR_WIN-NMs_killed") == 1) then
player:addKeyItem(INDIGESTED_MEAT);
player:messageSpecial(KEYITEM_OBTAINED,INDIGESTED_MEAT);
elseif (GetMobAction(wyrm1) + GetMobAction(wyrm1) + GetMobAction(wyrm1) == 0) then
SpawnMob(wyrm1):updateClaim(player);
SpawnMob(wyrm2):updateClaim(player);
SpawnMob(wyrm3):updateClaim(player);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
beraldoleal/config | .config/awesome/lain/util/init.lua | 4 | 4715 | --[[
Lain
Layouts, widgets and utilities for Awesome WM
Utilities section
Licensed under GNU General Public License v2
* (c) 2013, Luca CPZ
* (c) 2010-2012, Peter Hofmann
--]]
local awful = require("awful")
local sqrt = math.sqrt
local pairs = pairs
local client = client
local tonumber = tonumber
local wrequire = require("lain.helpers").wrequire
local setmetatable = setmetatable
-- Lain utilities submodule
-- lain.util
local util = { _NAME = "lain.util" }
-- Like awful.menu.clients, but only show clients of currently selected tags
function util.menu_clients_current_tags(menu, args)
-- List of currently selected tags.
local cls_tags = awful.screen.focused().selected_tags
if cls_tags == nil then return nil end
-- Final list of menu items.
local cls_t = {}
-- For each selected tag get all clients of that tag and add them to
-- the menu. A click on a menu item will raise that client.
for i = 1,#cls_tags do
local t = cls_tags[i]
local cls = t:clients()
for k, c in pairs(cls) do
cls_t[#cls_t + 1] = { awful.util.escape(c.name) or "",
function ()
c.minimized = false
client.focus = c
c:raise()
end,
c.icon }
end
end
-- No clients? Then quit.
if #cls_t <= 0 then return nil end
-- menu may contain some predefined values, otherwise start with a
-- fresh menu.
if not menu then menu = {} end
-- Set the list of items and show the menu.
menu.items = cls_t
local m = awful.menu(menu)
m:show(args)
return m
end
-- Magnify a client: set it to "float" and resize it.
function util.magnify_client(c, width_f, height_f)
if c and not c.floating then
util.magnified_client = c
util.mc(c, width_f, height_f)
else
util.magnified_client = nil
c.floating = false
end
end
-- https://github.com/lcpz/lain/issues/195
function util.mc(c, width_f, height_f)
c = c or util.magnified_client
if not c then return end
c.floating = true
local s = awful.screen.focused()
local mg = s.workarea
local g = {}
local mwfact = width_f or s.selected_tag.master_width_factor or 0.5
g.width = sqrt(mwfact) * mg.width
g.height = sqrt(height_f or mwfact) * mg.height
g.x = mg.x + (mg.width - g.width) / 2
g.y = mg.y + (mg.height - g.height) / 2
if c then c:geometry(g) end -- if c is still a valid object
end
-- Non-empty tag browsing
-- direction in {-1, 1} <-> {previous, next} non-empty tag
function util.tag_view_nonempty(direction, sc)
local s = sc or awful.screen.focused()
for i = 1, #s.tags do
awful.tag.viewidx(direction, s)
if #s.clients > 0 then
return
end
end
end
-- {{{ Dynamic tagging
-- Add a new tag
function util.add_tag(layout)
awful.prompt.run {
prompt = "New tag name: ",
textbox = awful.screen.focused().mypromptbox.widget,
exe_callback = function(name)
if not name or #name == 0 then return end
awful.tag.add(name, { screen = awful.screen.focused(), layout = layout or awful.layout.suit.tile }):view_only()
end
}
end
-- Rename current tag
function util.rename_tag()
awful.prompt.run {
prompt = "Rename tag: ",
textbox = awful.screen.focused().mypromptbox.widget,
exe_callback = function(new_name)
if not new_name or #new_name == 0 then return end
local t = awful.screen.focused().selected_tag
if t then
t.name = new_name
end
end
}
end
-- Move current tag
-- pos in {-1, 1} <-> {previous, next} tag position
function util.move_tag(pos)
local tag = awful.screen.focused().selected_tag
if tonumber(pos) <= -1 then
awful.tag.move(tag.index - 1, tag)
else
awful.tag.move(tag.index + 1, tag)
end
end
-- Delete current tag
-- Any rule set on the tag shall be broken
function util.delete_tag()
local t = awful.screen.focused().selected_tag
if not t then return end
t:delete()
end
-- }}}
-- On the fly useless gaps change
function util.useless_gaps_resize(thatmuch, s, t)
local scr = s or awful.screen.focused()
local tag = t or scr.selected_tag
tag.gap = tag.gap + tonumber(thatmuch)
awful.layout.arrange(scr)
end
return setmetatable(util, { __index = wrequire })
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.